diff --git a/.vscode/settings.json b/.vscode/settings.json index 29d0986..2d6d7e3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -15,8 +15,6 @@ "underride", "unifiedpush", "unredact", - "webpush", - "subprofile", - "subprofiles" + "webpush" ] } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index cfba062..7638ad6 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -47,12 +47,6 @@ - - - - - - main(List args) => build(args, (input, output) async { libFileName = "libgomuks.dylib"; final iosConfig = codeConfig.iOS; iosSdk = iosConfig.targetSdk; - final minVersion = iosConfig.deploymentVersion.major; + final minVersion = iosConfig.targetVersion; iosSdkPath = await getXCodeTool(sdkType: iosSdk.type); final archTriple = switch (targetArch) { @@ -53,8 +53,7 @@ Future main(List args) => build(args, (input, output) async { libFileName = "libgomuks.dylib"; extraEnv = { "SDKROOT": await getXCodeTool(), - "MACOSX_DEPLOYMENT_TARGET": codeConfig.macOS.deploymentVersion.major - .toString(), + "MACOSX_DEPLOYMENT_TARGET": codeConfig.macOS.targetVersion.toString(), }; break; case OS.windows: diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 0fe5f5c..1612bb0 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -16,10 +16,6 @@ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - 5A4E00000000000000000008 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A4E00000000000000000001 /* ShareViewController.swift */; }; - 5A4E00000000000000000009 /* MainInterface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5A4E00000000000000000007 /* MainInterface.storyboard */; }; - 5A4E0000000000000000000A /* ShareExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 5A4E00000000000000000005 /* ShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; - 5A4E0000000000000000000B /* better-share-handler-models in Frameworks */ = {isa = PBXBuildFile; productRef = 5A4E00000000000000000015 /* better-share-handler-models */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -30,13 +26,6 @@ remoteGlobalIDString = 97C146ED1CF9000F007C117D; remoteInfo = Runner; }; - 5A4E00000000000000000012 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 97C146E61CF9000F007C117D /* Project object */; - proxyType = 1; - remoteGlobalIDString = 5A4E0000000000000000000D; - remoteInfo = ShareExtension; - }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -50,17 +39,6 @@ name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; - 5A4E00000000000000000011 /* Embed App Extensions */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 13; - files = ( - 5A4E0000000000000000000A /* ShareExtension.appex in Embed App Extensions */, - ); - name = "Embed App Extensions"; - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ @@ -81,12 +59,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 5A4E00000000000000000001 /* ShareViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = ""; }; - 5A4E00000000000000000002 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/MainInterface.storyboard; sourceTree = ""; }; - 5A4E00000000000000000003 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 5A4E00000000000000000004 /* ShareExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = ShareExtension.entitlements; sourceTree = ""; }; - 5A4E00000000000000000005 /* ShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = ShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; - 5A4E00000000000000000006 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -105,14 +77,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 5A4E0000000000000000000F /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 5A4E0000000000000000000B /* better-share-handler-models in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -143,7 +107,6 @@ 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 331C8082294A63A400263BE5 /* RunnerTests */, - 5A4E0000000000000000000C /* ShareExtension */, ); sourceTree = ""; }; @@ -152,7 +115,6 @@ children = ( 97C146EE1CF9000F007C117D /* Runner.app */, 331C8081294A63A400263BE5 /* RunnerTests.xctest */, - 5A4E00000000000000000005 /* ShareExtension.appex */, ); name = Products; sourceTree = ""; @@ -169,22 +131,10 @@ 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, - 5A4E00000000000000000006 /* Runner.entitlements */, ); path = Runner; sourceTree = ""; }; - 5A4E0000000000000000000C /* ShareExtension */ = { - isa = PBXGroup; - children = ( - 5A4E00000000000000000001 /* ShareViewController.swift */, - 5A4E00000000000000000007 /* MainInterface.storyboard */, - 5A4E00000000000000000003 /* Info.plist */, - 5A4E00000000000000000004 /* ShareExtension.entitlements */, - ); - path = ShareExtension; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -215,13 +165,11 @@ 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, - 5A4E00000000000000000011 /* Embed App Extensions */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, ); buildRules = ( ); dependencies = ( - 5A4E00000000000000000013 /* PBXTargetDependency */, ); name = Runner; packageProductDependencies = ( @@ -231,26 +179,6 @@ productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; }; - 5A4E0000000000000000000D /* ShareExtension */ = { - isa = PBXNativeTarget; - buildConfigurationList = 5A4E00000000000000000016 /* Build configuration list for PBXNativeTarget "ShareExtension" */; - buildPhases = ( - 5A4E0000000000000000000E /* Sources */, - 5A4E0000000000000000000F /* Frameworks */, - 5A4E00000000000000000010 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = ShareExtension; - packageProductDependencies = ( - 5A4E00000000000000000015 /* better-share-handler-models */, - ); - productName = ShareExtension; - productReference = 5A4E00000000000000000005 /* ShareExtension.appex */; - productType = "com.apple.product-type.app-extension"; - }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -269,9 +197,6 @@ CreatedOnToolsVersion = 7.3.1; LastSwiftMigration = 1100; }; - 5A4E0000000000000000000D = { - CreatedOnToolsVersion = 15.0; - }; }; }; buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; @@ -285,7 +210,6 @@ mainGroup = 97C146E51CF9000F007C117D; packageReferences = ( 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, - 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "better_share_handler" */, ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; @@ -293,7 +217,6 @@ targets = ( 97C146ED1CF9000F007C117D /* Runner */, 331C8080294A63A400263BE5 /* RunnerTests */, - 5A4E0000000000000000000D /* ShareExtension */, ); }; /* End PBXProject section */ @@ -317,14 +240,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 5A4E00000000000000000010 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 5A4E00000000000000000009 /* MainInterface.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ @@ -380,14 +295,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 5A4E0000000000000000000E /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 5A4E00000000000000000008 /* ShareViewController.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -396,11 +303,6 @@ target = 97C146ED1CF9000F007C117D /* Runner */; targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; }; - 5A4E00000000000000000013 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 5A4E0000000000000000000D /* ShareExtension */; - targetProxy = 5A4E00000000000000000012 /* PBXContainerItemProxy */; - }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -420,14 +322,6 @@ name = LaunchScreen.storyboard; sourceTree = ""; }; - 5A4E00000000000000000007 /* MainInterface.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 5A4E00000000000000000002 /* Base */, - ); - name = MainInterface.storyboard; - sourceTree = ""; - }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ @@ -474,7 +368,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -492,7 +386,6 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; DEVELOPMENT_TEAM = PK66NJM372; ENABLE_BITCODE = NO; - CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", @@ -602,7 +495,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -653,7 +546,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -673,7 +566,6 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; DEVELOPMENT_TEAM = PK66NJM372; ENABLE_BITCODE = NO; - CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", @@ -697,7 +589,6 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; DEVELOPMENT_TEAM = PK66NJM372; ENABLE_BITCODE = NO; - CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", @@ -711,87 +602,6 @@ }; name = Release; }; - 5A4E00000000000000000017 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = PK66NJM372; - GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_FILE = ShareExtension/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@executable_path/../../Frameworks", - ); - MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; - PRODUCT_BUNDLE_IDENTIFIER = nexus.federated.nexus.ShareExtension; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 5A4E00000000000000000018 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = PK66NJM372; - GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_FILE = ShareExtension/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@executable_path/../../Frameworks", - ); - MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; - PRODUCT_BUNDLE_IDENTIFIER = nexus.federated.nexus.ShareExtension; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Release; - }; - 5A4E00000000000000000019 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; - DEVELOPMENT_TEAM = PK66NJM372; - GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_FILE = ShareExtension/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@executable_path/../../Frameworks", - ); - MARKETING_VERSION = "$(FLUTTER_BUILD_NAME)"; - PRODUCT_BUNDLE_IDENTIFIER = nexus.federated.nexus.ShareExtension; - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Profile; - }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -825,16 +635,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 5A4E00000000000000000016 /* Build configuration list for PBXNativeTarget "ShareExtension" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 5A4E00000000000000000017 /* Debug */, - 5A4E00000000000000000018 /* Release */, - 5A4E00000000000000000019 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ @@ -842,10 +642,6 @@ isa = XCLocalSwiftPackageReference; relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; }; - 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "better_share_handler" */ = { - isa = XCLocalSwiftPackageReference; - relativePath = "Flutter/ephemeral/Packages/.packages/better_share_handler-1.1.1"; - }; /* End XCLocalSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ @@ -853,11 +649,6 @@ isa = XCSwiftPackageProductDependency; productName = FlutterGeneratedPluginSwiftPackage; }; - 5A4E00000000000000000015 /* better-share-handler-models */ = { - isa = XCSwiftPackageProductDependency; - package = 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "better_share_handler" */; - productName = "better-share-handler-models"; - }; /* End XCSwiftPackageProductDependency section */ }; rootObject = 97C146E61CF9000F007C117D /* Project object */; diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index a26f7b5..7deed9e 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -31,15 +31,6 @@ matrix - - - CFBundleTypeRole - Editor - CFBundleURLSchemes - - ShareMedia-$(PRODUCT_BUNDLE_IDENTIFIER) - - CFBundleVersion $(FLUTTER_BUILD_NUMBER) diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements deleted file mode 100644 index 23cb05e..0000000 --- a/ios/Runner/Runner.entitlements +++ /dev/null @@ -1,10 +0,0 @@ - - - - - com.apple.security.application-groups - - group.nexus.federated.nexus - - - diff --git a/ios/ShareExtension/Base.lproj/MainInterface.storyboard b/ios/ShareExtension/Base.lproj/MainInterface.storyboard deleted file mode 100644 index 286a508..0000000 --- a/ios/ShareExtension/Base.lproj/MainInterface.storyboard +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ios/ShareExtension/Info.plist b/ios/ShareExtension/Info.plist deleted file mode 100644 index 76d4a29..0000000 --- a/ios/ShareExtension/Info.plist +++ /dev/null @@ -1,41 +0,0 @@ - - - - - CFBundleDisplayName - Nexus - CFBundleShortVersionString - $(FLUTTER_BUILD_NAME) - CFBundleVersion - $(FLUTTER_BUILD_NUMBER) - NSExtension - - NSExtensionAttributes - - PHSupportedMediaTypes - - Video - Image - - - NSExtensionActivationRule - - NSExtensionActivationSupportsText - - NSExtensionActivationSupportsWebURLWithMaxCount - 1 - NSExtensionActivationSupportsImageWithMaxCount - 1 - NSExtensionActivationSupportsMovieWithMaxCount - 1 - NSExtensionActivationSupportsFileWithMaxCount - 1 - - - NSExtensionMainStoryboard - MainInterface - NSExtensionPointIdentifier - com.apple.share-services - - - diff --git a/ios/ShareExtension/ShareExtension.entitlements b/ios/ShareExtension/ShareExtension.entitlements deleted file mode 100644 index 23cb05e..0000000 --- a/ios/ShareExtension/ShareExtension.entitlements +++ /dev/null @@ -1,10 +0,0 @@ - - - - - com.apple.security.application-groups - - group.nexus.federated.nexus - - - diff --git a/ios/ShareExtension/ShareViewController.swift b/ios/ShareExtension/ShareViewController.swift deleted file mode 100644 index 76f4931..0000000 --- a/ios/ShareExtension/ShareViewController.swift +++ /dev/null @@ -1,5 +0,0 @@ -import better_share_handler_models - -// Saves what was shared to the App Group, then opens Nexus, which asks which -// room to send it to. See ShareRequestController. -class ShareViewController: ShareHandlerIosViewController {} diff --git a/lib/controllers/account_data.dart b/lib/controllers/account_data.dart index debad12..62997b5 100644 --- a/lib/controllers/account_data.dart +++ b/lib/controllers/account_data.dart @@ -5,9 +5,6 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter/foundation.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/client.dart"; -import "package:nexus/controllers/pending_subprofiles.dart"; -import "package:nexus/controllers/rooms.dart"; -import "package:nexus/models/per_message_profiles.dart"; import "package:nexus/models/account_data.dart"; import "package:nexus/models/push_rules.dart"; import "package:nexus/models/requests/update_push_rule.dart"; @@ -76,45 +73,6 @@ class AccountDataController extends Notifier { (data) => data.ignoredUserList.contains(userId) == ignored, ); - Future setPerMessageProfiles(PerMessageProfiles profiles) => - _sendAndWait( - () => ref - .read(ClientController.provider.notifier) - .setAccountData( - .new(type: AccountData.perMessageProfilesKey, content: profiles), - ), - (data) => data.perMessageProfiles == profiles, - ); - - Future setRoomProfile(String roomId, String profileId) { - const type = AccountData.perMessageProfilesKey; - const key = "default_profile_id"; - final current = ref - .read(RoomsController.provider)[roomId] - ?.accountData[type]; - - return ref.read(PendingSubprofilesController.provider.notifier).track( - roomId, - profileId, - () async { - await ref - .read(ClientController.provider.notifier) - .setAccountData( - .new( - type: type, - roomId: roomId, - content: {...?current, key: profileId}, - ), - ); - await ref - .read(RoomsController.provider.notifier) - .awaitRooms( - (rooms) => rooms[roomId]?.accountData[type]?[key] == profileId, - ); - }, - ); - } - /// Saves [rule] of [kind], creating it if it's new, or otherwise changing only /// its actions and whether it's enabled. Future savePushRule(PushRuleKind kind, PushRule rule) { diff --git a/lib/controllers/account_management.dart b/lib/controllers/account_management.dart deleted file mode 100644 index 172ff5a..0000000 --- a/lib/controllers/account_management.dart +++ /dev/null @@ -1,24 +0,0 @@ -import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/controllers/client.dart"; -import "package:nexus/controllers/client_state.dart"; -import "package:nexus/models/account_management.dart"; - -/// Where the homeserver lets the user manage their account, if it says. -class AccountManagementController extends AsyncNotifier { - @override - Future build() async { - final homeserver = ref.watch( - ClientStateController.provider.select((state) => state?.homeserverUrl), - ); - if (homeserver == null) return null; - - return ref - .read(ClientController.provider.notifier) - .getAccountManagement(.parse(homeserver)); - } - - static final provider = - AsyncNotifierProvider( - AccountManagementController.new, - ); -} diff --git a/lib/controllers/bot_argument_suggestions.dart b/lib/controllers/bot_argument_suggestions.dart index c97d07f..04c2152 100644 --- a/lib/controllers/bot_argument_suggestions.dart +++ b/lib/controllers/bot_argument_suggestions.dart @@ -66,7 +66,7 @@ class BotArgumentSuggestionsController(final ComposerParams composer) ), ) => BotArgumentSuggestion( - title: displayName ?? userId.localpart!, + title: displayName ?? userId.localpart, subtitle: userId, avatar: avatarUrl, text: userId, diff --git a/lib/controllers/bot_commands.dart b/lib/controllers/bot_commands.dart index 887c874..49dc414 100644 --- a/lib/controllers/bot_commands.dart +++ b/lib/controllers/bot_commands.dart @@ -50,7 +50,7 @@ class BotCommandsController(final String roomId) ) => BotCommand( sender: sender, - botName: displayName ?? sender.localpart!, + botName: displayName ?? sender.localpart, botAvatar: avatarUrl, description: description, ), diff --git a/lib/controllers/client.dart b/lib/controllers/client.dart index b7b8ffd..3a1ac6c 100644 --- a/lib/controllers/client.dart +++ b/lib/controllers/client.dart @@ -36,8 +36,6 @@ import "package:nexus/models/requests/get_mentions.dart"; import "package:nexus/models/requests/get_related_events.dart"; import "package:nexus/models/requests/get_room_state.dart"; import "package:nexus/models/requests/get_specific_room_state.dart"; -import "package:nexus/models/content/content.dart"; -import "package:nexus/models/account_management.dart"; import "package:nexus/models/requests/get_space_hierarchy.dart"; import "package:nexus/models/requests/get_room_directory.dart"; import "package:nexus/models/requests/get_threads.dart"; @@ -282,19 +280,24 @@ class ClientController(final String? accountId) extends AsyncNotifier { Future resetEncryption(RecoveryKey key) => sendCommand("reset_encryption", key.toJson()); - Future getAccountManagement(Uri homeserver) async => - switch ((await sendCommand("get_login_flows", { - "homeserver_url": homeserver.toString(), - }))["oauth"]) { - {"account_management_uri": final String uri} && final oauth => .new( - .parse(uri), - .new( - (oauth["account_management_actions_supported"] as List? ?? []) - .whereType(), - ), - ), - _ => null, - }; + Future getCrossSigningResetUrl(Uri homeserver) async { + const action = "org.matrix.cross_signing_reset"; + final oauth = (await sendCommand("get_login_flows", { + "homeserver_url": homeserver.toString(), + }))["oauth"]; + + if (oauth?["account_management_uri"] case final String uri + when (oauth["account_management_actions_supported"] as List?)?.contains( + action, + ) ?? + false) { + final parsed = Uri.parse(uri); + return parsed.replace( + queryParameters: {...parsed.queryParameters, "action": action}, + ); + } + return null; + } Future joinRoom(JoinRoomRequest request) async => (await sendCommand("join_room", request.toJson()))["room_id"]; @@ -333,50 +336,15 @@ class ClientController(final String? accountId) extends AsyncNotifier { ); } - /// The raw JSON of the events [request] asks for, for when the parsed - /// content would lose fields. - Future getSpecificRoomStateJson( - GetSpecificRoomStateRequest request, - ) async => - (await sendCommand("get_specific_room_state", request.toJson())) - as List? ?? - []; - Future> getSpecificRoomState( GetSpecificRoomStateRequest request, ) async => .new( - (await getSpecificRoomStateJson(request)).map((event) => .fromJson(event)), + ((await sendCommand("get_specific_room_state", request.toJson())) + as List? ?? + []) + .map((event) => .fromJson(event)), ); - Future updateMembership( - String roomId, - String userId, - IMap changes, - ) async { - final type = EventType.membership.type; - final current = switch ((await getSpecificRoomStateJson( - .new( - keys: .new([.new(roomId: roomId, type: type, stateKey: userId)]), - ), - )).firstOrNull) { - {"content": final Map content} => content.cast(), - _ => throw Exception("You aren't a member of this room"), - }; - - return await sendCommand("set_state", { - "room_id": roomId, - "type": type, - "state_key": userId, - "content": current.lock - .addAll(changes) - .removeWhere( - (key, value) => - value == null || key == "join_authorised_via_users_server", - ) - .unlock, - }); - } - Future?> getRelatedEvents( GetRelatedEventsRequest request, ) async { @@ -446,17 +414,17 @@ class ClientController(final String? accountId) extends AsyncNotifier { Future registerPusher(RegisterPusherRequest request) => sendCommand("register_homeserver_push", request.toJson()); - Future deregisterPusher(DeregisterPusherRequest request) => sendCommand( - "register_homeserver_push", - {...request.toJson(), "kind": null}, - ); + Future deregisterPusher(DeregisterPusherRequest request) => + sendCommand("register_homeserver_push", { + ...request.toJson(), + "kind": null, + }); Future uploadMedia(UploadMediaRequest request) async => .fromJson(await sendCommand("upload_media", request.toJson())); Future downloadMedia(DownloadMediaRequest request) async { if (accountId == null && - !isInBackground && ref.read(ClientStateController.provider)?.isLoggedIn != true) { throw StateError("Can't download media while logged out"); } diff --git a/lib/controllers/composer_draft.dart b/lib/controllers/composer_draft.dart index 65eb3cb..25ed273 100644 --- a/lib/controllers/composer_draft.dart +++ b/lib/controllers/composer_draft.dart @@ -1,11 +1,8 @@ -import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:fluttertagger/fluttertagger.dart"; import "package:nexus/controllers/attachment.dart"; import "package:nexus/controllers/bot_command_draft.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/helpers/extensions/get_filename.dart"; -import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/is_media.dart"; import "package:nexus/helpers/extensions/with_latest_edit.dart"; import "package:nexus/models/composer_draft.dart"; @@ -52,10 +49,8 @@ class ComposerDraftController(final ComposerParams composer) }, ); - final tagged = _restoreTags(text); state = ComposerDraft( - text: tagged.text, - tags: tagged.tags, + text: text, textCommands: commands, relatedEvent: rowId, relationType: .edit, @@ -81,52 +76,6 @@ class ComposerDraftController(final ComposerParams composer) _botCommand.clear(); } - static final _tagPattern = RegExp( - r"\[@[^\]]*\]\(matrix:u/([^)\s]+)\)" - r"|\[#[^\]]*\]\(matrix:roomid/([^)?\s]+)[^)\s]*\)" - r"|\[#[^\]]*\]\(matrix:r/([^)?\s]+)[^)\s]*\)" - r'|!\[:([^\]\s]+):\]\(mxc://[^)\s]+(?: "(?:[^"\\]|\\.)*")?\)', - ); - - /// Turns the mentions and custom emoji in [text], an edit source, back into - /// tags, formatted like the composer's tagTextFormatter. - ({String text, IList tags}) _restoreTags(String text) { - final rooms = ref.read(RoomsController.provider); - Tag tagOf(Match match) => - switch ((match[1], match[2], match[3], match[4])) { - (final userId?, _, _, _) => .new( - id: match[0]!, - text: userId.split(":").first, - triggerCharacter: "@", - ), - (_, final roomId?, _, _) => .new( - id: match[0]!, - text: - rooms["!$roomId"]?.metadata?.canonicalAlias?.localpart ?? - "!$roomId", - triggerCharacter: "#", - ), - (_, _, final alias?, _) => .new( - id: match[0]!, - text: "#$alias".localpart!, - triggerCharacter: "#", - ), - (_, _, _, final shortcode) => .new( - id: match[0]!, - text: shortcode!, - triggerCharacter: ":", - ), - }; - - return ( - text: text.replaceAllMapped(_tagPattern, (match) { - final tag = tagOf(match); - return "${tag.triggerCharacter}${tag.id}#${tag.text}#"; - }), - tags: _tagPattern.allMatches(text).map(tagOf).toISet().toIList(), - ); - } - void dismiss() { if (state.isEditing) return _restoreBeforeEdit(); state = state.copyWith(relatedEvent: null); diff --git a/lib/controllers/launch_scope.dart b/lib/controllers/launch_scope.dart deleted file mode 100644 index b4303b8..0000000 --- a/lib/controllers/launch_scope.dart +++ /dev/null @@ -1,10 +0,0 @@ -import "package:flutter_riverpod/flutter_riverpod.dart"; - -class LaunchScopeController extends Notifier { - @override - bool build() => true; - - static final provider = NotifierProvider( - LaunchScopeController.new, - ); -} diff --git a/lib/controllers/notification.dart b/lib/controllers/notification.dart index 618d849..e8a5dff 100644 --- a/lib/controllers/notification.dart +++ b/lib/controllers/notification.dart @@ -2,15 +2,11 @@ import "dart:async"; import "dart:convert"; import "dart:io"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter/services.dart"; import "package:material_ui/material_ui.dart"; import "package:nexus/controllers/active_account.dart"; -import "package:nexus/controllers/launch_scope.dart"; import "package:nexus/controllers/portal.dart"; -import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/sidebar_page.dart"; -import "package:nexus/helpers/shown_notifications_helper.dart"; import "package:nexus/main.dart"; import "package:flutter_local_notifications/flutter_local_notifications.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; @@ -30,17 +26,7 @@ class NotificationController Future build() async { final notifications = FlutterLocalNotificationsPlugin(); - if (Platform.isLinux) { - const MethodChannel("nexus/notifications") - .setMethodCallHandler((call) async { - if (call case MethodCall( - method: "notificationClicked", - arguments: final String payload, - )) { - _open(payload); - } - }); - } else { + if (!Platform.isLinux) { final darwin = DarwinInitializationSettings(); await notifications.initialize( @@ -58,89 +44,26 @@ class NotificationController if (details.payload case final payload?) _open(payload); }, ); - - await notifications - .resolvePlatformSpecificImplementation< - AndroidFlutterLocalNotificationsPlugin - >() - ?.deleteNotificationChannel(channelId: "messages"); - - // Taps that launched the app don't reach the callback above - if (!isInBackground && ref.read(LaunchScopeController.provider)) { - if (await notifications.getNotificationAppLaunchDetails() - case NotificationAppLaunchDetails( - didNotificationLaunchApp: true, - notificationResponse: NotificationResponse(:final payload?), - )) { - _open(payload); - } - } } - // Reading a room, here or on another client, dismisses its notifications - if (!isInBackground) { - ref.listen( - RoomsController.provider.select( - (rooms) => rooms - .where((_, room) => room.metadata?.unreadNotifications == 0) - .keys - .toISet(), - ), - (previous, read) { - final newlyRead = read.difference(previous ?? const ISetConst({})); - if (newlyRead.isEmpty) return; + if (Platform.isLinux) { + const notificationChannel = MethodChannel("nexus/notifications"); - final accountId = ref.read(ActiveAccountController.provider); - dismiss( - newlyRead.map((roomId) => threadIdFor(accountId, roomId)).toISet(), - ).onError(showError); - }, - fireImmediately: true, - ); + notificationChannel.setMethodCallHandler((call) async { + if (call.method != "notificationClicked") { + return; + } + + if (call.arguments case final String payload) _open(payload); + }); } return notifications; } - static String threadIdFor(String accountId, String roomId) => - "$accountId/$roomId"; - static String payloadFor(String accountId, int rowId) => "$accountId:$rowId"; - static const _messagesChannel = "messages_v2"; - static const _androidGroup = "nexus.federated.nexus.MESSAGES"; - - /// Dismisses the notifications shown for [threadIds]. - Future dismiss(ISet threadIds) async { - final ids = await ref - .read(ShownNotificationsHelper.provider) - .remove(threadIds); - if (ids.isEmpty) return; - - if (Platform.isLinux) { - final portal = await ref.read(PortalController.provider.future); - await Future.wait( - ids.map((id) => portal.notification.removeNotification(id.toString())), - ); - return; - } - - final controller = await future; - await Future.wait(ids.map((id) => controller.cancel(id: id))); - - // The summary would otherwise outlive its group - if (Platform.isAndroid && - (await controller.getActiveNotifications()).every( - (notification) => notification.id == 0, - )) { - await controller.cancel(id: 0); - } - } - void _open(String payload) { - navigatorKey.currentState?.popUntil((route) => route.isFirst); - ref.read(SidebarPageController.provider.notifier).set(.notifications); - final (accountId, rowId) = switch (payload.split(":")) { [final accountId, final rowId] => (accountId, int.tryParse(rowId)), // From before notifications were per account @@ -149,6 +72,9 @@ class NotificationController }; if (rowId == null) return; + navigatorKey.currentState?.popUntil((route) => route.isFirst); + ref.read(SidebarPageController.provider.notifier).set(.notifications); + ref .read(ActiveAccountController.provider.notifier) .switchTo( @@ -158,50 +84,73 @@ class NotificationController .onError(showError); } - // Each resolves to null except on its own platform Future requestPermissions() async { + if (Platform.isLinux) { + return true; + } + final controller = await future; - return await controller - .resolvePlatformSpecificImplementation< - IOSFlutterLocalNotificationsPlugin - >() - ?.requestPermissions(alert: true, badge: true, sound: true) ?? - await controller - .resolvePlatformSpecificImplementation< - MacOSFlutterLocalNotificationsPlugin - >() - ?.requestPermissions(alert: true, badge: true, sound: true) ?? - await controller - .resolvePlatformSpecificImplementation< - AndroidFlutterLocalNotificationsPlugin - >() - ?.requestNotificationsPermission() ?? - true; + if (Platform.isIOS) { + return await controller + .resolvePlatformSpecificImplementation< + IOSFlutterLocalNotificationsPlugin + >() + ?.requestPermissions(alert: true, badge: true, sound: true) ?? + true; + } else if (Platform.isMacOS) { + return await controller + .resolvePlatformSpecificImplementation< + MacOSFlutterLocalNotificationsPlugin + >() + ?.requestPermissions(alert: true, badge: true, sound: true) ?? + true; + } else if (Platform.isAndroid) { + return await controller + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin + >() + ?.requestNotificationsPermission() ?? + true; + } + + return true; } /// Whether notifications can currently be shown, without prompting Future permissionsGranted() async { + if (Platform.isLinux) { + return true; + } + final controller = await future; - return (await controller - .resolvePlatformSpecificImplementation< - IOSFlutterLocalNotificationsPlugin - >() - ?.checkPermissions()) - ?.isEnabled ?? - (await controller - .resolvePlatformSpecificImplementation< - MacOSFlutterLocalNotificationsPlugin - >() - ?.checkPermissions()) - ?.isEnabled ?? - await controller - .resolvePlatformSpecificImplementation< - AndroidFlutterLocalNotificationsPlugin - >() - ?.areNotificationsEnabled() ?? - true; + if (Platform.isIOS) { + return (await controller + .resolvePlatformSpecificImplementation< + IOSFlutterLocalNotificationsPlugin + >() + ?.checkPermissions()) + ?.isEnabled ?? + true; + } else if (Platform.isMacOS) { + return (await controller + .resolvePlatformSpecificImplementation< + MacOSFlutterLocalNotificationsPlugin + >() + ?.checkPermissions()) + ?.isEnabled ?? + true; + } else if (Platform.isAndroid) { + return await controller + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin + >() + ?.areNotificationsEnabled() ?? + true; + } + + return true; } /// Passing [message] shows it as a chat message in the conversation for @@ -224,7 +173,6 @@ class NotificationController // In DMs the title is already the sender final sender = message == null || message.isDm ? null : message.sender; final prefixedBody = sender == null ? body : "${sender.name}: $body"; - final shown = ref.read(ShownNotificationsHelper.provider); if (Platform.isLinux) { final portal = await ref.read(PortalController.provider.future); @@ -251,7 +199,6 @@ class NotificationController // ), ], ); - if (threadId != null) await shown.add(threadId, id); return; } @@ -267,7 +214,6 @@ class NotificationController .onError((_, _) => null) : null; - final largeIcon = icon == null ? null : FilePathAndroidBitmap(icon.path); final darwin = DarwinNotificationDetails( subtitle: subtitle, presentSound: sound, @@ -284,24 +230,24 @@ class NotificationController ? .new( "general", "General", - groupKey: _androidGroup, subText: subtitle, silent: !sound, when: timestamp?.millisecondsSinceEpoch, - largeIcon: largeIcon, + largeIcon: icon == null + ? null + : FilePathAndroidBitmap(icon.path), styleInformation: BigTextStyleInformation(body), ) : .new( - _messagesChannel, + "messages", "Messages", - importance: .high, - priority: .high, - groupKey: _androidGroup, subText: subtitle, silent: !sound, when: timestamp?.millisecondsSinceEpoch, category: .message, - largeIcon: largeIcon, + largeIcon: icon == null + ? null + : FilePathAndroidBitmap(icon.path), styleInformation: MessagingStyleInformation( .new(key: message.self.id, name: message.self.name), conversationTitle: message.isDm ? null : title, @@ -314,12 +260,11 @@ class NotificationController .new( key: message.sender.id, name: message.sender.name, - icon: switch (message.senderAvatar) { - final avatar? => BitmapFilePathAndroidIcon( - avatar.path, - ), - null => null, - }, + icon: message.senderAvatar == null + ? null + : BitmapFilePathAndroidIcon( + message.senderAvatar!.path, + ), ), ), ], @@ -336,28 +281,6 @@ class NotificationController ), ), ); - - if (threadId != null) await shown.add(threadId, id); - - if (Platform.isAndroid) { - await controller.show( - id: 0, - title: "Nexus", - payload: payload, - notificationDetails: const .new( - android: .new( - _messagesChannel, - "Messages", - importance: .high, - groupKey: _androidGroup, - setAsGroupSummary: true, - groupAlertBehavior: .children, - onlyAlertOnce: true, - silent: true, - ), - ), - ); - } } static final provider = diff --git a/lib/controllers/pending_subprofiles.dart b/lib/controllers/pending_subprofiles.dart deleted file mode 100644 index 1e7b9b0..0000000 --- a/lib/controllers/pending_subprofiles.dart +++ /dev/null @@ -1,45 +0,0 @@ -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:flutter_riverpod/flutter_riverpod.dart"; - -typedef PendingSubprofile = ({String id, Future synced}); - -/// Subprofiles just chosen for rooms, by room ID, until they come down sync. -/// gomuks only learns of them then, so messages sent before would use the -/// previous one. -class PendingSubprofilesController - extends Notifier> { - @override - IMap build() => const .empty(); - - Future track( - String roomId, - String id, - Future Function() save, - ) async { - final synced = save(); - state = state.add(roomId, (id: id, synced: synced)); - - try { - await synced; - } finally { - // Unless another subprofile was chosen meanwhile - if (state[roomId]?.synced == synced) state = state.remove(roomId); - } - } - - Future settled(String roomId) async { - try { - await state[roomId]?.synced; - } catch (_) { - throw Exception( - "The message wasn't sent, as the subprofile chosen for this room couldn't be saved", - ); - } - } - - static final provider = - NotifierProvider< - PendingSubprofilesController, - IMap - >(PendingSubprofilesController.new); -} diff --git a/lib/controllers/room_chat.dart b/lib/controllers/room_chat.dart index e0a6765..2a53a0d 100644 --- a/lib/controllers/room_chat.dart +++ b/lib/controllers/room_chat.dart @@ -7,8 +7,6 @@ import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:fluttertagger/fluttertagger.dart"; import "package:nexus/controllers/attachment.dart"; import "package:nexus/controllers/client.dart"; -import "package:nexus/controllers/pending_subprofiles.dart"; -import "package:nexus/controllers/subprofiles.dart"; import "package:nexus/controllers/event.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/thread_replies.dart"; @@ -401,7 +399,6 @@ class RoomChatController(final ChatParams info) required RelationType relationType, int? relatedEventRowId, }) async { - final subprofile = subprofileFor(text); final events = ref.read(RoomsController.provider)[info.roomId]?.events; final relatedEvent = relatedEventRowId == null ? null @@ -440,7 +437,6 @@ class RoomChatController(final ChatParams info) ); final client = ref.read(ClientController.provider.notifier); - await awaitSubprofile(text, subprofile); final event = await client.sendMessage( SendMessageRequest( roomId: info.roomId, @@ -462,24 +458,6 @@ class RoomChatController(final ChatParams info) addSent(event); } - String? subprofileFor(String text, {bool synced = false}) { - final subprofiles = ref.read(SubprofilesController.provider(info.roomId)); - return (subprofiles.triggeredBy(text) ?? - (synced ? subprofiles.synced : subprofiles.current)) - ?.id; - } - - Future awaitSubprofile(String text, String? shown) async { - await ref - .read(PendingSubprofilesController.provider.notifier) - .settled(info.roomId); - if (subprofileFor(text, synced: true) != shown) { - throw Exception( - "The message wasn't sent, as it would have been sent as a different subprofile than shown", - ); - } - } - /// Shows [event], which was just sent, until it comes down sync. void addSent(Event? event) { if (event case final event?) { @@ -636,7 +614,6 @@ class RoomChatController(final ChatParams info) .read(RoomsController.provider)[info.roomId] ?.events[repliedEventRowId]; - await awaitSubprofile("", subprofileFor("")); final event = await ref .read(ClientController.provider.notifier) .sendMessage( diff --git a/lib/controllers/room_profile.dart b/lib/controllers/room_profile.dart deleted file mode 100644 index e42129d..0000000 --- a/lib/controllers/room_profile.dart +++ /dev/null @@ -1,101 +0,0 @@ -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/controllers/client.dart"; -import "package:nexus/controllers/client_state.dart"; -import "package:nexus/controllers/profile.dart"; -import "package:nexus/controllers/rooms.dart"; -import "package:nexus/models/content/content.dart"; -import "package:nexus/models/content/membership.dart"; -import "package:nexus/models/profile_response.dart"; -import "package:nexus/models/room.dart"; - -/// The current user's member event content in [roomId], which holds the -/// avatar and display name they have there, fetching only that event if it -/// hasn't been yet. -class RoomProfileController(final String roomId) - extends AsyncNotifier { - String? get _userId => ref.read(ClientStateController.provider)?.userId; - - @override - Future build() async { - final userId = ref.watch( - ClientStateController.provider.select((state) => state?.userId), - ); - if (userId == null) return null; - - MembershipContent? memberOf(IMap rooms) => - switch (rooms[roomId]) { - final room? => - switch (room.state[EventType.membership.type]?[userId]) { - final rowId? => switch (room.events[rowId]?.content) { - final MembershipContent content => content, - _ => null, - }, - null => null, - }, - null => null, - }; - - if (memberOf(ref.read(RoomsController.provider)) == null) { - ref - .read(RoomsController.provider.notifier) - .addSpecificState( - await ref - .read(ClientController.provider.notifier) - .getSpecificRoomState( - .new( - keys: .new([ - .new( - roomId: roomId, - type: EventType.membership.type, - stateKey: userId, - ), - ]), - ), - ), - ); - } - - return ref.watch(RoomsController.provider.select(memberOf)); - } - - /// Sets [changes] in the member event, waiting for it to come down sync. - Future setFields(IMap changes) async { - final userId = _userId; - if (userId == null) return; - - final eventId = await ref - .read(ClientController.provider.notifier) - .updateMembership(roomId, userId, changes); - if (eventId != null) { - await ref - .read(RoomsController.provider.notifier) - .awaitState( - roomId, - EventType.membership.type, - eventId, - stateKey: userId, - ); - } - } - - /// Replaces the room's avatar and display name with the global ones. - Future reset() async { - final userId = _userId; - if (userId == null) return; - - final profile = (await ref.read(ProfileController.provider(userId).future)) - .profile; - await setFields( - .new({ - Profile.displayNameKey: profile.displayName, - Profile.avatarUrlKey: profile.avatarUrl?.toString(), - }), - ); - } - - static final provider = AsyncNotifierProvider.autoDispose - .family( - RoomProfileController.new, - ); -} diff --git a/lib/controllers/rooms.dart b/lib/controllers/rooms.dart index 91d8093..66ffa3b 100644 --- a/lib/controllers/rooms.dart +++ b/lib/controllers/rooms.dart @@ -189,7 +189,6 @@ class RoomsController extends Notifier> { ? incoming.timeline : existing.timeline.addAll(incoming.timeline), receipts: mergeReceipts(existing.receipts, incoming.receipts), - accountData: existing.accountData.addAll(incoming.accountData), ) ?? incoming.copyWith( receipts: mergeReceipts(const .empty(), incoming.receipts), diff --git a/lib/controllers/selected_room.dart b/lib/controllers/selected_room.dart index a48a340..075fcdd 100644 --- a/lib/controllers/selected_room.dart +++ b/lib/controllers/selected_room.dart @@ -22,16 +22,9 @@ class SelectedRoomController extends Notifier { .addAll([?space.room?.metadata?.id]), ), ); - if (roomIds == null || roomIds.contains(roomId)) return roomId; + if (roomIds == null) return roomId; - final fallback = roomIds.firstOrNull; - Future.microtask(() { - if (!ref.mounted) return; - ref - .read(KeyController.provider(KeyController.roomKey).notifier) - .set(fallback); - }); - return fallback; + return roomIds.contains(roomId) ? roomId : roomIds.firstOrNull; } static final provider = NotifierProvider( diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index 5121d6b..999fea6 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -5,10 +5,10 @@ import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; import "package:intl/intl.dart"; +import "package:m3e_buttons/m3e_buttons.dart"; import "package:multi_state_switch/multi_state_switch.dart"; import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/account_data.dart"; -import "package:nexus/controllers/account_management.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/enabled_image_packs.dart"; @@ -24,7 +24,6 @@ import "package:nexus/helpers/extensions/distributor_name.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/room_image_packs.dart"; import "package:nexus/helpers/hooks/saving.dart"; -import "package:nexus/helpers/launch_helper.dart"; import "package:nexus/models/account_data.dart"; import "package:nexus/models/client_state.dart"; import "package:nexus/models/image_pack.dart"; @@ -43,7 +42,6 @@ import "package:nexus/widgets/settings/block_user_field.dart"; import "package:nexus/widgets/settings/dialog_list_tile.dart"; import "package:nexus/widgets/settings/enable_image_packs_sheet.dart"; import "package:nexus/widgets/settings/keyword_field.dart"; -import "package:nexus/widgets/settings/subprofile_sheet.dart"; import "package:nexus/widgets/users/user_bottom_sheet.dart"; import "package:nexus/widgets/encryption/reset_encryption_sheet.dart"; @@ -52,40 +50,6 @@ class SettingsSectionsController @override Future>> build() async { final settings = await ref.watch(SettingsController.provider.future); - final subprofiles = ref.watch( - AccountDataController.provider.select((data) => data.perMessageProfiles), - ); - // Not awaited, so a slow homeserver doesn't hold up the rest of settings - final accountManagement = ref - .watch(AccountManagementController.provider) - .value; - - // Opens [url], a page of the homeserver's account management - Setting link( - String title, - String description, - IconData icon, - Uri url, { - bool danger = false, - }) => .new( - title: title, - description: description, - icon: icon, - builder: (title, description, icon) => Builder( - builder: (context) { - final error = Theme.of(context).colorScheme.error; - return ListTile( - leading: Icon(icon), - title: Text(title), - subtitle: Text(description), - trailing: Icon(Icons.open_in_new), - textColor: danger ? error : null, - iconColor: danger ? error : null, - onTap: () => ref.read(LaunchHelper.provider).launchUrl(url), - ); - }, - ), - ); // Loads the enabled packs' state, so they can be shown ref.watch(EnabledImagePacksController.provider); @@ -292,7 +256,7 @@ class SettingsSectionsController ), .new( title: "Room Ordering", - description: "Sort rooms and subspaces by recent activity or the order their space sets, optionally showing mentioned and unread ones first.", + description: "Sort rooms by recent activity, optionally showing mentioned and unread rooms first.", icon: Icons.sort, builder: (title, description, icon) => DialogListTile( icon: Icon(icon), @@ -301,11 +265,8 @@ class SettingsSectionsController value: settings.roomOrder, options: RoomOrder.values, getName: (option) => switch (option) { - .unreadFirst => "Mentioned, then unread, then recent", - .unreadFirstSpaceOrder => - "Mentioned, then unread, then space order", + .unreadFirst => "Mentioned, then unread", .recentActivity => "Recent activity only", - .spaceOrder => "Space order only", }, onChanged: (value) => ref .read(SettingsController.provider.notifier) @@ -378,17 +339,17 @@ class SettingsSectionsController ), ), .new( - title: "Show Hidden Events", - description: "Shows events that are usually hidden, like reactions, edits, deletions and server ACL changes, in conversations.", - icon: Icons.visibility, + title: "Hide Server ACL Events", + description: "Hides server ACL (server ban list) changes from appearing in conversations.", + icon: Icons.dns, builder: (title, description, icon) => SwitchListTile( title: Text(title), subtitle: Text(description), secondary: Icon(icon), - value: settings.showHiddenEvents, + value: settings.hideServerAclEvents, onChanged: (value) => ref .read(SettingsController.provider.notifier) - .set(settings.copyWith(showHiddenEvents: value)) + .set(settings.copyWith(hideServerAclEvents: value)) .onError(showError), ), ), @@ -447,116 +408,6 @@ class SettingsSectionsController ), ]), ), - .new( - title: "Subprofiles", - icon: Icons.groups, - settings: .new([ - .new( - title: "Enable Subprofiles", - description: "Send messages as other names and avatars, chosen per room from the composer.", - icon: Icons.groups, - builder: (title, description, icon) => SwitchListTile( - title: Text(title), - subtitle: Text(description), - secondary: Icon(icon), - value: settings.subprofiles, - onChanged: (value) => ref - .read(SettingsController.provider.notifier) - .set(settings.copyWith(subprofiles: value)) - .onError(showError), - ), - ), - if (settings.subprofiles) ...[ - .new( - title: "Latch Triggered Subprofiles", - description: "After you send a message with a subprofile's trigger, keep sending as it in that room until you choose another.", - icon: Icons.push_pin, - builder: (title, description, icon) => SwitchListTile( - title: Text(title), - subtitle: Text(description), - secondary: Icon(icon), - value: settings.latchSubprofiles, - onChanged: (value) => ref - .read(SettingsController.provider.notifier) - .set(settings.copyWith(latchSubprofiles: value)) - .onError(showError), - ), - ), - if (subprofiles.profiles.isNotEmpty) - .new( - title: "Default Subprofile", - description: "Who you send as in rooms you haven't chosen a subprofile for.", - icon: Icons.person_pin, - builder: (title, description, icon) => - DialogListTile( - icon: Icon(icon), - title: title, - subtitle: Text(description), - value: subprofiles.defaultProfileId ?? "", - options: [ - "", - ...subprofiles.profiles.map( - (profile) => profile.id, - ), - ], - getName: (id) => switch (subprofiles.byId(id)) { - final profile? => profile.displayName ?? id, - null => "Account Profile", - }, - onChanged: (id) => accountData - .setPerMessageProfiles( - subprofiles.copyWith( - defaultProfileId: id.isEmpty ? null : id, - ), - ) - .onError(showError), - ), - ), - header( - "Subprofiles", - "The names and avatars you can send messages as.", - Icons.groups, - ), - ...subprofiles.profiles.map( - (subprofile) => Setting( - title: subprofile.displayName ?? subprofile.id, - description: "A subprofile.", - icon: Icons.person, - builder: (title, _, _) => Builder( - builder: (context) => ListTile( - leading: AvatarOrHash(subprofile.avatarUrl, title), - title: Text(title), - subtitle: switch (subprofile.triggers.firstOrNull) { - final trigger? => Text( - "Trigger: ${trigger.prefix}text${trigger.suffix}", - ), - null => null, - }, - trailing: Icon(Icons.chevron_right), - onTap: () => context.showAdaptiveSheet( - (_) => SubprofileSheet(subprofile: subprofile), - ), - ), - ), - ), - ), - .new( - title: "Add Subprofile", - description: "Create a name and avatar to send messages as.", - icon: Icons.add, - builder: (title, _, icon) => Builder( - builder: (context) => ListTile( - leading: Icon(icon), - title: Text(title), - onTap: () => context.showAdaptiveSheet( - (_) => const SubprofileSheet(), - ), - ), - ), - ), - ], - ]), - ), .new( title: "Image Packs", icon: Icons.emoji_emotions, @@ -905,7 +756,7 @@ class SettingsSectionsController return ListTile( enabled: !saving.active, - leading: AvatarOrHash(profile?.avatarUrl, name!), + leading: AvatarOrHash(profile?.avatarUrl, name), title: Text(name, overflow: .ellipsis), subtitle: Text(userId, overflow: .ellipsis), onTap: () => context.showAdaptiveSheet( @@ -939,47 +790,24 @@ class SettingsSectionsController ]), ), .new( - title: "Account Management", - icon: Icons.manage_accounts, + title: "Other", + icon: Icons.key, settings: .new([ - if (accountManagement case final management?) - link( - "Manage Account", - "Change your password, email, and other account details on your homeserver's website.", - Icons.manage_accounts, - management.uri, - ), - if (accountManagement?.urlFor(.devicesList) case final url?) - link( - "Devices", - "See and sign out the devices logged in to your account, on your homeserver's website.", - Icons.devices, - url, - ), .new( title: "Reset Encryption Identity", description: "Replace your encryption identity and recovery key with new ones, if you've lost your recovery key or your encryption is broken.", builder: (title, description, icon) => Builder( - builder: (context) => ListTile( - leading: Icon(icon), - title: Text(title), - subtitle: Text(description), - trailing: Icon(Icons.chevron_right), - onTap: () => context.showAdaptiveSheet( + builder: (context) => M3EButton.icon( + onPressed: () => context.showAdaptiveSheet( (_) => const ResetEncryptionSheet(), ), + label: Text(title), + icon: Icon(icon), + tooltip: description, ), ), icon: Icons.key_off, ), - if (accountManagement?.urlFor(.accountDeactivate) case final url?) - link( - "Deactivate Account", - "Permanently deactivate your account, on your homeserver's website. This can't be undone.", - Icons.no_accounts, - url, - danger: true, - ), ]), ), ]), diff --git a/lib/controllers/share_request.dart b/lib/controllers/share_request.dart deleted file mode 100644 index ce7a9ca..0000000 --- a/lib/controllers/share_request.dart +++ /dev/null @@ -1,33 +0,0 @@ -import "dart:io"; - -import "package:better_share_handler/better_share_handler.dart"; -import "package:flutter_riverpod/flutter_riverpod.dart"; - -class ShareRequestController extends Notifier { - @override - SharedMedia? build() { - if (!(Platform.isAndroid || Platform.isIOS)) return null; - - final sharing = ShareHandler.instance; - final subscription = sharing.sharedMediaStream.listen( - (media) => state = media, - ); - ref.onDispose(subscription.cancel); - sharing.getInitialSharedMedia().then((media) { - if (media != null) state = media; - }).ignore(); - - return null; - } - - void consume() { - state = null; - // So the same share isn't received again once the app is reopened - ShareHandler.instance.resetInitialSharedMedia().ignore(); - } - - static final provider = - NotifierProvider( - ShareRequestController.new, - ); -} diff --git a/lib/controllers/spaces.dart b/lib/controllers/spaces.dart index 07e1fd7..4d6dffe 100644 --- a/lib/controllers/spaces.dart +++ b/lib/controllers/spaces.dart @@ -10,11 +10,8 @@ import "package:nexus/controllers/space_edges.dart"; import "package:nexus/models/room.dart"; import "package:nexus/models/room_metadata.dart"; import "package:nexus/models/space.dart"; -import "package:nexus/models/space_edge.dart"; import "package:nexus/models/subspace.dart"; -typedef _SortKey = ({int priority, DateTime activity, int index}); - class SpacesController extends AsyncNotifier> { @override Future> build() async { @@ -23,27 +20,9 @@ class SpacesController extends AsyncNotifier> { final spaceEdges = ref.watch(SpaceEdgesController.provider); final accountData = ref.watch(AccountDataController.provider); - bool hasValidOrder(SpaceEdge edge) => - edge.order.isNotEmpty && - edge.order.length <= 50 && - edge.order.codeUnits.every((unit) => unit >= 0x20 && unit <= 0x7E); - - int compareEdges(SpaceEdge a, SpaceEdge b) => - switch ((hasValidOrder(a), hasValidOrder(b))) { - (true, false) => -1, - (false, true) => 1, - (true, true) when a.order != b.order => a.order.compareTo(b.order), - _ => switch (a.childEventRowId.compareTo(b.childEventRowId)) { - 0 => a.childId.compareTo(b.childId), - final byRowId => byRowId, - }, - }; - final childrenById = spaceEdges.map( - (spaceId, edges) => .new( - spaceId, - edges.sort(compareEdges).map((edge) => edge.childId).toList(), - ), + (spaceId, edges) => + MapEntry(spaceId, edges.map((edge) => edge.childId).toList()), ); /// Everything under [spaceId], however deep, skipping any already @@ -81,7 +60,6 @@ class SpacesController extends AsyncNotifier> { room: room, children: .new( collectDescendants(childId) - .where((id) => !childrenById.containsKey(id)) .map((id) => rooms[id]) .nonNulls, ), @@ -91,10 +69,6 @@ class SpacesController extends AsyncNotifier> { ) .nonNulls, ), - childrenIndex: directChildrenIds - .where(rooms.containsKey) - .takeWhile(childrenById.containsKey) - .length, ); } @@ -164,67 +138,31 @@ class SpacesController extends AsyncNotifier> { SettingsController.provider.selectAsync((data) => data.roomOrder), ); - int priority(Room? room) => switch (room?.metadata) { - _ when !roomOrder.byUnread => 0, + // Mentioned -> Unread -> Other + int unreadPriority(Room room) => switch (room.metadata) { RoomMetadata(unreadHighlights: > 0) => 0, RoomMetadata(unreadNotifications: > 0) || RoomMetadata(unreadMessages: > 0) => 1, _ => 2, }; - DateTime activity(Room room) => room.metadata?.sortingTimestamp ?? .new(0); - return .new( - allSpaces.map((space) { - final bySpace = roomOrder.bySpace && space.room != null; - int compare(_SortKey a, _SortKey b) => - switch (a.priority.compareTo(b.priority)) { - 0 when bySpace => a.index.compareTo(b.index), - 0 => b.activity.compareTo(a.activity), - final byPriority => byPriority, - }; + return allSpaces + .map( + (space) => space.copyWith( + children: space.children.sort((a, b) { + if (roomOrder == .unreadFirst) { + final byUnread = unreadPriority(a).compareTo(unreadPriority(b)); + if (byUnread != 0) return byUnread; + } - _SortKey roomKey(int index, Room room) => - (priority: priority(room), activity: activity(room), index: index); - - _SortKey groupKey(int index, IList rooms) => ( - priority: rooms.map(priority).minOrNull ?? priority(null), - activity: rooms.map(activity).maxOrNull ?? .new(0), - index: index, - ); - - IList sortRooms(IList rooms) => .new( - rooms.indexed - .sorted( - (a, b) => compare(roomKey(a.$1, a.$2), roomKey(b.$1, b.$2)), - ) - .map((entry) => entry.$2), - ); - - final subSpaces = space.subSpaces.indexed - .map( - (entry) => ( - subspace: entry.$2, - key: groupKey(entry.$1, entry.$2.children), - ), - ) - .sorted((a, b) => compare(a.key, b.key)); - - final childrenKey = groupKey(space.childrenIndex, space.children); - return space.copyWith( - children: sortRooms(space.children), - subSpaces: .new( - subSpaces.map( - (entry) => entry.subspace.copyWith( - children: sortRooms(entry.subspace.children), - ), - ), + // Most recent activity first + return (b.metadata?.sortingTimestamp ?? DateTime(0)).compareTo( + a.metadata?.sortingTimestamp ?? DateTime(0), + ); + }), ), - childrenIndex: subSpaces - .where((entry) => compare(entry.key, childrenKey) < 0) - .length, - ); - }), - ); + ) + .toIList(); } static final provider = AsyncNotifierProvider>( diff --git a/lib/controllers/subprofiles.dart b/lib/controllers/subprofiles.dart deleted file mode 100644 index 21b1a0d..0000000 --- a/lib/controllers/subprofiles.dart +++ /dev/null @@ -1,68 +0,0 @@ -import "package:collection/collection.dart"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:flutter/foundation.dart"; -import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/controllers/account_data.dart"; -import "package:nexus/controllers/pending_subprofiles.dart"; -import "package:nexus/controllers/rooms.dart"; -import "package:nexus/models/account_data.dart"; -import "package:nexus/models/per_message_profiles.dart"; -import "package:nexus/models/room_subprofiles.dart"; - -class SubprofilesController(final String roomId) - extends Notifier { - @override - RoomSubprofiles build() { - final global = ref.watch( - AccountDataController.provider.select((data) => data.perMessageProfiles), - ); - final roomJson = ref.watch( - RoomsController.provider.select( - (rooms) => - rooms[roomId]?.accountData[AccountData.perMessageProfilesKey], - ), - ); - - PerMessageProfiles? room; - if (roomJson != null) { - try { - room = .fromJson(roomJson); - } catch (error) { - debugPrint("Ignoring invalid room per-message profiles: $error"); - } - } - - final roomIds = room?.profiles.map((profile) => profile.id).toISet(); - final profiles = (room?.profiles ?? const IList.empty()) - .addAll( - global.profiles.where( - (profile) => !(roomIds?.contains(profile.id) ?? false), - ), - ); - - StoredProfile? byId(String? id) => id == null || id.isEmpty - ? null - : profiles.firstWhereOrNull((profile) => profile.id == id); - final syncedId = room?.defaultProfileId ?? global.defaultProfileId; - - return .new( - profiles: profiles, - triggerOrder: (room?.profiles ?? const IList.empty()) - .addAll(global.profiles), - current: byId( - ref.watch( - PendingSubprofilesController.provider.select( - (pending) => pending[roomId]?.id, - ), - ) ?? - syncedId, - ), - synced: byId(syncedId), - ); - } - - static final provider = NotifierProvider.autoDispose - .family( - SubprofilesController.new, - ); -} diff --git a/lib/controllers/unified_push.dart b/lib/controllers/unified_push.dart index d6f3777..25675e2 100644 --- a/lib/controllers/unified_push.dart +++ b/lib/controllers/unified_push.dart @@ -121,20 +121,18 @@ class UnifiedPushController extends AsyncNotifier { final icon = notification.roomAvatar == null ? null - : await client - .downloadMedia(.new(mxc: notification.roomAvatar!)) - .then((file) => file) - .onError((_, _) => null); + : await client.downloadMedia( + .new(mxc: notification.roomAvatar!, isAvatar: true), + ); final pmp = notification.perMessageProfile; final senderAvatarUrl = pmp?.avatar ?? notification.sender.avatar; // Only Android can show the sender's avatar final senderAvatar = senderAvatarUrl == null || !Platform.isAndroid ? null - : await client - .downloadMedia(.new(mxc: senderAvatarUrl)) - .then((file) => file) - .onError((_, _) => null); + : await client.downloadMedia( + .new(mxc: senderAvatarUrl, isAvatar: true), + ); await ref .read(NotificationController.provider.notifier) @@ -145,10 +143,7 @@ class UnifiedPushController extends AsyncNotifier { "$accountId/${Platform.isAndroid ? notification.roomId : notification.eventId}" .hashCode & 0x7fffffff, - threadId: NotificationController.threadIdFor( - accountId, - notification.roomId, - ), + threadId: "$accountId/${notification.roomId}", title: notification.roomName, subtitle: hasOtherAccounts ? notification.self.id : null, body: notification.text, @@ -225,8 +220,7 @@ class UnifiedPushController extends AsyncNotifier { CapabilitiesController.provider.future, ); - final vapid = capabilities.webPushVapid; - if (vapid == null) { + if (capabilities.webpush?.vapid == null) { throw UnsupportedError( "Your homeserver does not support MSC4174 (Web Push), and therefore cannot send notifications to Nexus.", ); @@ -244,7 +238,7 @@ class UnifiedPushController extends AsyncNotifier { await Future.wait([ UnifiedPush.register( instance: deviceId, - vapid: vapid, + vapid: capabilities.webpush?.vapid, ), endpoint.future, ], eagerError: true); diff --git a/lib/controllers/unified_push_allowed.dart b/lib/controllers/unified_push_allowed.dart index 978f4ab..6dd1cf7 100644 --- a/lib/controllers/unified_push_allowed.dart +++ b/lib/controllers/unified_push_allowed.dart @@ -23,7 +23,7 @@ class UnifiedPushAllowedController extends AsyncNotifier { CapabilitiesController.provider.future, ); - if (capabilities.webPushVapid == null) { + if (capabilities.webpush?.vapid == null) { return "Your homeserver does not support MSC4174 (Web Push), and therefore cannot send notifications to Nexus."; } diff --git a/lib/helpers/extensions/get_all_child_rooms.dart b/lib/helpers/extensions/get_all_child_rooms.dart index c2fbfaa..7a17eec 100644 --- a/lib/helpers/extensions/get_all_child_rooms.dart +++ b/lib/helpers/extensions/get_all_child_rooms.dart @@ -3,10 +3,6 @@ import "package:nexus/models/room.dart"; import "package:nexus/models/space.dart"; extension GetAllChildRooms on Space { - IList get allChildRooms => subSpaces - .map((subspace) => subspace.children) - .toIList() - .insert(childrenIndex, children) - .expand((rooms) => rooms) - .toIList(); + IList get allChildRooms => + children.addAll(subSpaces.expand((s) => s.children)); } diff --git a/lib/helpers/extensions/get_localpart.dart b/lib/helpers/extensions/get_localpart.dart index d0ad620..200d2d0 100644 --- a/lib/helpers/extensions/get_localpart.dart +++ b/lib/helpers/extensions/get_localpart.dart @@ -1,5 +1,5 @@ extension GetLocalpart on String { - String? get localpart => length > 1 ? substring(1).split(":").first : null; + String get localpart => length > 1 ? substring(1).split(":").first : "?"; /// Whether this looks like a valid Matrix user ID, e.g. `@user:example.com`. bool get isValidUserId => RegExp(r"^@[^:\s]+:[^\s]+$").hasMatch(this); diff --git a/lib/helpers/extensions/show_image_viewer.dart b/lib/helpers/extensions/show_image_viewer.dart index 366d1e2..9be95b8 100644 --- a/lib/helpers/extensions/show_image_viewer.dart +++ b/lib/helpers/extensions/show_image_viewer.dart @@ -10,7 +10,7 @@ import "package:nexus/widgets/common/error_dialog.dart"; extension ShowImageViewer on BuildContext { /// Shows the image from [request] fullscreen, zoomable. /// - /// The download button suggests [downloadFilename], falling back to the media ID. + /// If [downloadFilename] is set, a download button is shown, suggesting it. void showImageViewer( WidgetRef ref, DownloadMediaRequest request, { @@ -58,15 +58,16 @@ extension ShowImageViewer on BuildContext { mainAxisSize: .min, spacing: 8, children: [ - M3EButton( - onPressed: () => context.saveAttachment( - ref, - request.mxc, - encrypted: request.encrypted, - filename: downloadFilename, + if (downloadFilename != null) + M3EButton( + onPressed: () => context.saveAttachment( + ref, + request.mxc, + encrypted: request.encrypted, + filename: downloadFilename, + ), + child: Icon(Icons.download), ), - child: Icon(Icons.download), - ), M3EButton( onPressed: Navigator.of(context).pop, child: Icon(Icons.close), diff --git a/lib/helpers/shown_notifications_helper.dart b/lib/helpers/shown_notifications_helper.dart deleted file mode 100644 index 17d3975..0000000 --- a/lib/helpers/shown_notifications_helper.dart +++ /dev/null @@ -1,52 +0,0 @@ -import "dart:convert"; - -import "package:collection/collection.dart"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:nexus/controllers/shared_prefs.dart"; - -class ShownNotificationsHelper(final Ref ref) { - static const _key = "shownNotifications"; - - /// Applies [update], returning the IDs from before it. - Future>> _update( - IMap> Function(IMap> shown) update, - ) async { - final prefs = ref.read(SharedPrefsController.provider); - final shown = IMap>.fromJson( - json.decode(await prefs.getString(_key) ?? "{}"), - (threadId) => threadId as String, - (ids) => .fromJson(ids, (id) => id as int), - ); - - await prefs.setString( - _key, - json.encode( - update(shown) - .toJson((threadId) => threadId, (ids) => ids.toJson((id) => id)), - ), - ); - return shown; - } - - Future add(String threadId, int id) => _update( - (shown) => shown.update( - threadId, - (ids) => ids.add(id), - ifAbsent: () => .new({id}), - ), - ); - - /// Forgets the notifications shown for [threadIds], returning their IDs. - Future> remove(ISet threadIds) async { - final shown = await _update( - (shown) => - shown.removeWhere((threadId, _) => threadIds.contains(threadId)), - ); - return threadIds.map((threadId) => shown[threadId]).nonNulls.flattened; - } - - static final provider = Provider( - ShownNotificationsHelper.new, - ); -} diff --git a/lib/models/account_data.dart b/lib/models/account_data.dart index 94149f3..51176cd 100644 --- a/lib/models/account_data.dart +++ b/lib/models/account_data.dart @@ -1,6 +1,5 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:freezed_annotation/freezed_annotation.dart"; -import "package:nexus/models/per_message_profiles.dart"; import "package:nexus/models/push_rules.dart"; part "account_data.freezed.dart"; @@ -28,8 +27,6 @@ class const AccountData({ final PushRules pushRules = const .new(), @JsonKey(name: AccountData.ignoredUserListKey) final IgnoredUserList ignoredUserList = const .new(), - @JsonKey(name: AccountData.perMessageProfilesKey) - final PerMessageProfiles perMessageProfiles = const .new(), }) with _$AccountData { static const invitePermissionConfigKey = "m.invite_permission_config"; static const directKey = "m.direct"; @@ -38,7 +35,6 @@ class const AccountData({ static const legacyImagePackRoomsKey = "im.ponies.emote_rooms"; static const pushRulesKey = "m.push_rules"; static const ignoredUserListKey = "m.ignored_user_list"; - static const perMessageProfilesKey = "fi.mau.msc4461.per_message_profiles.v3"; ImagePackRooms get enabledImagePacks => imagePackRooms ?? legacyImagePackRooms ?? const .new(); diff --git a/lib/models/account_management.dart b/lib/models/account_management.dart deleted file mode 100644 index 8bc8d1c..0000000 --- a/lib/models/account_management.dart +++ /dev/null @@ -1,19 +0,0 @@ -import "package:collection/collection.dart"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; - -// Later names first, then those from MSC4191, which servers may still use -enum AccountManagementAction(final List names) { - devicesList(["org.matrix.devices_list", "org.matrix.sessions_list"]), - accountDeactivate(["org.matrix.account_deactivate"]), - crossSigningReset(["org.matrix.cross_signing_reset"]), -} - -class const AccountManagement(final Uri uri, final ISet actions) { - Uri? urlFor(AccountManagementAction action) => - switch (action.names.firstWhereOrNull(actions.contains)) { - final name? => uri.replace( - queryParameters: {...uri.queryParameters, "action": name}, - ), - null => null, - }; -} diff --git a/lib/models/capabilities.dart b/lib/models/capabilities.dart index 9224cf5..cdf86b7 100644 --- a/lib/models/capabilities.dart +++ b/lib/models/capabilities.dart @@ -10,14 +10,6 @@ class const Capabilities({ @JsonKey(name: "org.matrix.msc4174.webpush") final WebPush? webpush, @JsonKey(name: "m.room_versions") final RoomVersions? roomVersions, }) with _$Capabilities { - /// The VAPID key to register Web Push pushers with, or null if the - /// homeserver can't send Web Push. Continuwuity sends a key even when the - /// feature is disabled, so `enabled` must be checked too. - String? get webPushVapid => switch (webpush) { - WebPush(enabled: true, :final vapid) => vapid, - _ => null, - }; - Map toJson() => _$CapabilitiesToJson(this); factory Capabilities.fromJson(Map json) => diff --git a/lib/models/composer_draft.dart b/lib/models/composer_draft.dart index 44e34ab..ea72f30 100644 --- a/lib/models/composer_draft.dart +++ b/lib/models/composer_draft.dart @@ -24,10 +24,6 @@ class const ComposerDraft({ final PollStart? poll, final LocationMessageContent? location, - // Bumped when the text is replaced from outside the composer, so that it - // rebuilds its text field from the draft - final int textReplacements = 0, - // The draft from before an edit, restored once it is sent or cancelled final ({ComposerDraft draft, BotCommandDraft? botCommand})? beforeEdit, }) with _$ComposerDraft { diff --git a/lib/models/event.dart b/lib/models/event.dart index c9c88cd..1467750 100644 --- a/lib/models/event.dart +++ b/lib/models/event.dart @@ -65,15 +65,14 @@ class const Event({ } } - factory Event.fromJson(Map json) => _$EventFromJson(json) - .copyWith( + factory Event.fromJson(Map json) => + _$EventFromJson(json).copyWith( replyTo: replyToFromJson(getContentFromJson(json)), - pmp: switch (getContentFromJson( - json, - )["com.beeper.per_message_profile"]) { - null => null, - final pmp => .fromJsonWithCatch(pmp), - }, + pmp: json["content"]?["com.beeper.per_message_profile"] == null + ? null + : .fromJsonWithCatch( + json["content"]?["com.beeper.per_message_profile"], + ), content: .fromEventJson( getContentFromJson(json), json["decrypted_type"] ?? json["type"], diff --git a/lib/models/per_message_profiles.dart b/lib/models/per_message_profiles.dart deleted file mode 100644 index 9d4c386..0000000 --- a/lib/models/per_message_profiles.dart +++ /dev/null @@ -1,53 +0,0 @@ -import "package:collection/collection.dart"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:freezed_annotation/freezed_annotation.dart"; - -part "per_message_profiles.freezed.dart"; -part "per_message_profiles.g.dart"; - -@Freezed(toJson: false, fromJson: false) -@JsonSerializable(includeIfNull: false) -class const PerMessageProfiles({ - final String? defaultProfileId, - final IList profiles = const .empty(), -}) with _$PerMessageProfiles { - StoredProfile? byId(String? id) => - profiles.firstWhereOrNull((profile) => profile.id == id); - - Map toJson() => _$PerMessageProfilesToJson(this); - - factory PerMessageProfiles.fromJson(Map json) => - _$PerMessageProfilesFromJson(json); -} - -@Freezed(toJson: false, fromJson: false) -@JsonSerializable(includeIfNull: false) -class const StoredProfile({ - required final String id, - @JsonKey(name: "displayname") final String? displayName, - final Uri? avatarUrl, - final IList triggers = const .empty(), -}) with _$StoredProfile { - Map toJson() => _$StoredProfileToJson(this); - - factory StoredProfile.fromJson(Map json) => - _$StoredProfileFromJson(json); -} - -@Freezed(toJson: false, fromJson: false) -@JsonSerializable(includeIfNull: false) -class const ProfileTrigger({ - final String prefix = "", - final String suffix = "", - final bool keepTrigger = false, -}) with _$ProfileTrigger { - bool matches(String text) => - text.length >= prefix.length + suffix.length && - text.startsWith(prefix) && - text.endsWith(suffix); - - Map toJson() => _$ProfileTriggerToJson(this); - - factory ProfileTrigger.fromJson(Map json) => - _$ProfileTriggerFromJson(json); -} diff --git a/lib/models/requests/download_media.dart b/lib/models/requests/download_media.dart index 8d9b21b..c9751f8 100644 --- a/lib/models/requests/download_media.dart +++ b/lib/models/requests/download_media.dart @@ -8,6 +8,8 @@ part "download_media.g.dart"; class const DownloadMediaRequest({ required final Uri mxc, final bool encrypted = false, + final bool isAvatar = false, + final bool thumbnailAvatar = false, }) with _$DownloadMediaRequest { Map toJson() => _$DownloadMediaRequestToJson(this); diff --git a/lib/models/room.dart b/lib/models/room.dart index f93b261..b809a23 100644 --- a/lib/models/room.dart +++ b/lib/models/room.dart @@ -45,12 +45,10 @@ class const Room({ final IMap> state = const .empty(), final IMap> receipts = const .empty(), - - @JsonKey(fromJson: Room.accountDataJsonToIMap) - final IMap> accountData = const .empty(), final bool dismissNotifications = false, final bool hasMore = true, + // IMap accountData, // IList notifications, }) with _$Room { static IMap timelineTupleJsonToIMap(List json) => @@ -63,15 +61,6 @@ class const Room({ ), ); - static IMap> accountDataJsonToIMap( - Map json, - ) => .fromEntries( - json.entries.map( - (entry) => - .new(entry.key, Map.from(entry.value["content"])), - ), - ); - static IMap eventsJsonToIMap(List json) => IMap.fromEntries( json.map((eventJson) { diff --git a/lib/models/room_order.dart b/lib/models/room_order.dart index b9cf46c..c0b5166 100644 --- a/lib/models/room_order.dart +++ b/lib/models/room_order.dart @@ -1,6 +1 @@ -enum RoomOrder({required final bool byUnread, required final bool bySpace}) { - unreadFirst(byUnread: true, bySpace: false), - unreadFirstSpaceOrder(byUnread: true, bySpace: true), - recentActivity(byUnread: false, bySpace: false), - spaceOrder(byUnread: false, bySpace: true), -} +enum RoomOrder { unreadFirst, recentActivity } diff --git a/lib/models/room_subprofiles.dart b/lib/models/room_subprofiles.dart deleted file mode 100644 index 073536c..0000000 --- a/lib/models/room_subprofiles.dart +++ /dev/null @@ -1,37 +0,0 @@ -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:freezed_annotation/freezed_annotation.dart"; -import "package:nexus/models/per_message_profiles.dart"; - -part "room_subprofiles.freezed.dart"; - -@freezed -class const RoomSubprofiles({ - required final IList profiles, - // Each trigger is tried in this order, as gomuks does when sending - required final IList triggerOrder, - final StoredProfile? current, - final StoredProfile? synced, -}) with _$RoomSubprofiles { - // The subprofile [text] triggers, and what's left once its trigger is removed - ({StoredProfile profile, String body})? triggerMatch(String text) => - triggerOrder - .where((profile) => profile.id.isNotEmpty) - .expand( - (profile) => profile.triggers - .where((trigger) => trigger.matches(text)) - .map( - (trigger) => ( - profile: profile, - body: trigger.keepTrigger - ? text - : text.substring( - trigger.prefix.length, - text.length - trigger.suffix.length, - ), - ), - ), - ) - .firstOrNull; - - StoredProfile? triggeredBy(String text) => triggerMatch(text)?.profile; -} diff --git a/lib/models/settings.dart b/lib/models/settings.dart index 6e08a0e..79c3d64 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -18,13 +18,10 @@ class const Settings({ final bool showMinimizeButton = false, final bool swipeToReply = false, final bool hideMembershipEvents = false, - final bool showHiddenEvents = false, - @JsonKey(unknownEnumValue: RoomOrder.unreadFirst) + final bool hideServerAclEvents = true, final RoomOrder roomOrder = .unreadFirst, final NameColor nameColor = .powerLevel, final ShowAndSend typingIndicators = .showAndSend, - final bool subprofiles = false, - final bool latchSubprofiles = false, /// When not sending, read receipts are still sent privately, so that the /// user's other devices know what has been read. diff --git a/lib/models/space.dart b/lib/models/space.dart index dec86a7..97efe7a 100644 --- a/lib/models/space.dart +++ b/lib/models/space.dart @@ -14,5 +14,4 @@ class const Space({ final Room? room, required final IList children, required final IList subSpaces, - final int childrenIndex = 0, }) with _$Space; diff --git a/lib/models/space_edge.dart b/lib/models/space_edge.dart index 41aea2f..ea74130 100644 --- a/lib/models/space_edge.dart +++ b/lib/models/space_edge.dart @@ -7,8 +7,6 @@ part "space_edge.g.dart"; @JsonSerializable() class const SpaceEdge({ required final String childId, - @JsonKey(name: "child_event_rowid") final int childEventRowId = 0, - final String order = "", final bool suggested = false, }) with _$SpaceEdge { Map toJson() => _$SpaceEdgeToJson(this); diff --git a/lib/widgets/account_scope.dart b/lib/widgets/account_scope.dart index 12badd5..ff8db09 100644 --- a/lib/widgets/account_scope.dart +++ b/lib/widgets/account_scope.dart @@ -3,7 +3,6 @@ import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_riverpod/misc.dart"; import "package:material_ui/material_ui.dart"; import "package:nexus/controllers/active_account.dart"; -import "package:nexus/controllers/launch_scope.dart"; import "package:nexus/controllers/notification_request.dart"; /// Runs [child] as one account, in a [ProviderScope] of its own that's @@ -24,7 +23,6 @@ class const AccountScope({ accountId: initialAccountId, notificationRowId: null, )); - final isLaunch = useState(true); return ProviderScope( key: ValueKey(active.value.accountId), @@ -32,17 +30,14 @@ class const AccountScope({ observers: observers, overrides: [ ActiveAccountController.provider.overrideWith( - () => ActiveAccountController(active.value.accountId, (next) { - isLaunch.value = false; - active.value = next; - }), + () => ActiveAccountController( + active.value.accountId, + (next) => active.value = next, + ), ), NotificationRequestController.provider.overrideWithBuild( (_, _) => active.value.notificationRowId, ), - LaunchScopeController.provider.overrideWithBuild( - (_, _) => isLaunch.value, - ), ...overrides, ], child: child, diff --git a/lib/widgets/avatars/avatar_or_hash.dart b/lib/widgets/avatars/avatar_or_hash.dart index 7945035..bb14c78 100644 --- a/lib/widgets/avatars/avatar_or_hash.dart +++ b/lib/widgets/avatars/avatar_or_hash.dart @@ -37,7 +37,7 @@ final class const AvatarOrHash( child: avatar == null ? fallback ?? box : Image( - image: MxcImage(ref, .new(mxc: avatar!)), + image: MxcImage(ref, .new(mxc: avatar!, isAvatar: true)), fit: .cover, loadingBuilder: (_, child, loadingProgress) => loadingProgress == null ? child : fallback ?? box, diff --git a/lib/widgets/avatars/editable_avatar.dart b/lib/widgets/avatars/editable_avatar.dart index 63461c5..5640342 100644 --- a/lib/widgets/avatars/editable_avatar.dart +++ b/lib/widgets/avatars/editable_avatar.dart @@ -55,10 +55,6 @@ class const EditableAvatar({ child: Builder( builder: (context) => IconButton.filled( tooltip: "Edit avatar", - // The theme's default barely contrasts with the button - style: IconButton.styleFrom( - foregroundColor: Theme.of(context).colorScheme.onPrimary, - ), icon: Icon(Icons.edit), onPressed: saving.active ? null diff --git a/lib/widgets/common/expandable_image.dart b/lib/widgets/common/expandable_image.dart index d034b62..34a1f76 100644 --- a/lib/widgets/common/expandable_image.dart +++ b/lib/widgets/common/expandable_image.dart @@ -7,7 +7,7 @@ final class const ExpandableImage( final DownloadMediaRequest? request, { required final Widget child, - /// Suggested filename when downloading, falling back to the media ID + /// If set, a download button is shown, suggesting this filename final String? downloadFilename, final int? size, super.key, diff --git a/lib/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index f251838..3b722e0 100644 --- a/lib/widgets/composer/composer.dart +++ b/lib/widgets/composer/composer.dart @@ -3,7 +3,6 @@ import "dart:io"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:collection/collection.dart"; import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; -import "package:nexus/widgets/composer/subprofile_button.dart"; import "package:nexus/controllers/bot_argument_suggestions.dart"; import "package:nexus/controllers/bot_command_draft.dart"; import "package:nexus/controllers/bot_commands.dart"; @@ -27,9 +26,6 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:nexus/controllers/attachment.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/settings.dart"; -import "package:nexus/controllers/account_data.dart"; -import "package:nexus/controllers/subprofiles.dart"; -import "package:nexus/models/settings.dart"; import "package:nexus/controllers/image_picker.dart"; import "package:nexus/helpers/file_dialog_helper.dart"; import "package:image_picker/image_picker.dart"; @@ -98,7 +94,6 @@ class const Composer( :poll, :location, :textCommands, - :textReplacements, ) = ref.watch( draftProvider.select( (draft) => ( @@ -109,7 +104,6 @@ class const Composer( poll: draft.poll, location: draft.location, textCommands: draft.textCommands, - textReplacements: draft.textReplacements, ), ), ); @@ -151,7 +145,7 @@ class const Composer( ]; }, ); - }, [composer, editingEvent, hasReplacement, textReplacements]); + }, [composer, editingEvent, hasReplacement]); useEffect( // After the frame, as FlutterTagger and TextField still use it until then () => @@ -436,32 +430,6 @@ class const Composer( attachment != null && attachment.$2 == null) { return; } - final subprofiles = ref.read(SubprofilesController.provider(roomId)); - final match = subprofiles.triggerMatch(controller.text); - void switchSubprofile(String id) { - if (id == subprofiles.current?.id) return; - ref - .read(AccountDataController.provider.notifier) - .setRoomProfile(roomId, id) - .onError(showError); - } - - // A trigger on its own would send an empty message, so it switches to - // its subprofile instead - if (match != null && match.body.trim().isEmpty && attachment == null) { - switchSubprofile(match.profile.id); - controller.text = ""; - return; - } - - // gomuks sends this message as the triggered subprofile itself, this - // keeps sending as it afterwards - if (ref.read(SettingsController.provider).value - case Settings(subprofiles: true, latchSubprofiles: true) - when match != null) { - switchSubprofile(match.profile.id); - } - onSend( "${TextCommand.prefixOf(textCommands)}${controller.formattedText}", shouldMention: shouldMention.value, @@ -509,539 +477,513 @@ class const Composer( fontWeight: .bold, ); - return TextFieldTapRegion( - child: Padding( - padding: .all(12), - child: Column( - children: [ - if (attachment != null) - Card( - margin: .only(bottom: 8), - child: Column( - children: [ - ListTile( - leading: switch (attachment.$2) { - null => SizedBox( - width: 16, - height: 16, - child: CircularProgressIndicator(), - ), - ImageMessageContent() => Icon(Icons.image), - VideoMessageContent() => Icon(Icons.movie), - AudioMessageContent() => Icon(Icons.audiotrack), - _ => Icon(Icons.file_copy), - }, - title: Text(attachment.$1), - trailing: IconButton( - onPressed: () => ref.invalidate(attachmentProvider), - icon: Icon(Icons.close), - ), - ), - AnimatedSize( - duration: Durations.short4, - alignment: .topCenter, - child: switch (attachment.$2) { - final content? - when content is! FileMessageContent && - content.isMedia => - Padding( - padding: EdgeInsets.all(12).copyWith(top: 0), - child: Align( - alignment: .centerLeft, - child: ConstrainedBox( - constraints: .loose(.square(300)), - child: MessageMedia(content), - ), - ), - ), - _ => SizedBox(width: .infinity), - }, - ), - ], - ), - ), - AnimatedSize( - duration: Durations.short4, - alignment: .bottomCenter, - child: BotCommandPanel( - composer, - commands: botCommands, - textCommands: availableTextCommands, - controller: controller, - onPick: pickBotCommand, - onPickText: pickTextCommand, - ), - ), - ClipRRect( - borderRadius: .all(.circular(12)), + return Padding( + padding: .all(12), + child: Column( + children: [ + if (attachment != null) + Card( + margin: .only(bottom: 8), child: Column( children: [ - RelationPreview( - relatedEvent, - shouldMention: shouldMention.value, - toggleShouldMention: () => - shouldMention.value = !shouldMention.value, - relationType: relationType, - onDismiss: dismiss, - ), - Container( - color: theme.colorScheme.surfaceContainerHighest, - child: Row( - mainAxisAlignment: .center, - children: - ref.watch( - PowerLevelController.provider( - .new(eventType: .message, roomId: roomId), - ), - ) - ? [ - SubprofileButton(roomId, controller: controller), - IconButton( - onPressed: hasReplacement - ? null - : () => context.showAdaptiveSheet( - (context) => EmojiPicker( - roomId: roomId, - onSelection: - ( - value, { - shortcode, - description, - }) { - Navigator.of(context).pop(); - if (shortcode == null) { - controller.text += value; - } else { - final text = - "${controller.text}:"; - controller.value = .new( - text: text, - selection: .collapsed( - offset: text.length, - ), - ); - controller.addTag( - id: ImagePack.emojiMarkdown( - shortcode, - value, - description: description, - ), - name: shortcode, - ); - } - node?.requestFocus(); - }, - ), - ), - icon: Icon(Icons.emoji_emotions), - ), - AdaptiveMenuButton( - tooltip: "Add media", - enabled: attachment == null && !hasReplacement, - itemBuilder: (context) => [ - for (final (source, title, icon) in [ - if (Platform.isAndroid || Platform.isIOS) - ( - ImageSource.camera, - "Camera", - Icons.add_a_photo, - ), - ( - ImageSource.gallery, - "Gallery", - Icons.add_photo_alternate, - ), - ]) - PopupMenuItem( - child: ListTile( - title: Text(title), - leading: Icon(icon), - ), - onTap: () => attach( - source == .gallery - ? ref - .read( - FileDialogHelper.provider, - ) - .pickFile(images: true) - : ref - .read( - ImagePickerController - .provider, - ) - .pickImage(source: source), - ).onError(showError), - ), - PopupMenuItem( - onTap: () => attach( - ref - .read(FileDialogHelper.provider) - .pickFile(), - ).onError(showError), - child: ListTile( - title: Text("Files"), - leading: Icon(Icons.attachment), - ), - ), - if (canSendStickers) - PopupMenuItem( - // Stickers can't replace messages - enabled: !isEditing, - onTap: () => context.showAdaptiveSheet( - (context) => StickerPicker( - roomId: roomId, - onSelection: (shortcode, image) { - Navigator.of(context).pop(); - draftNotifier.update( - (draft) => draft.copyWith( - sticker: (shortcode, image), - ), - ); - }, - ), - ), - child: ListTile( - title: Text("Sticker"), - leading: Icon(Icons.sticky_note_2), - ), - ), - if (canSendPolls) - PopupMenuItem( - enabled: !isEditing, - onTap: () => context.showAdaptiveSheet( - (context) => CreatePollSheet( - onCreate: (created) { - Navigator.of(context).pop(); - draftNotifier.update( - (draft) => - draft.copyWith(poll: created), - ); - }, - ), - ), - child: ListTile( - title: Text("Poll"), - leading: Icon(Icons.poll), - ), - ), - PopupMenuItem( - enabled: !isEditing, - onTap: () => context.showAdaptiveSheet( - enableDrag: false, - (context) => LocationPickerSheet( - onPick: (picked) { - Navigator.of(context).pop(); - draftNotifier.update( - (draft) => draft.copyWith( - location: picked, - ), - ); - }, - ), - ), - child: ListTile( - title: Text("Location"), - leading: Icon(Icons.location_on), - ), - ), - ], - icon: Icon(Icons.add), - ), - SizedBox(width: 8), - Expanded( - child: AnimatedSize( - duration: Durations.short4, - alignment: .bottomCenter, - child: switch (( - sticker, - poll, - location, - botCommand, - )) { - (_, final draft?, _, _) => - ComposerReplacement( - removeTooltip: "Remove poll", - onRemove: () { - draftNotifier.update( - (draft) => - draft.copyWith(poll: null), - ); - node?.requestFocus(); - }, - onKeyEvent: sendOnEnter, - ListTile( - leading: Icon( - Icons.poll, - color: theme.colorScheme.primary, - ), - title: Text(draft.question), - subtitle: Text( - draft.answers - .map((answer) => answer.text) - .join(" · "), - maxLines: 1, - overflow: .ellipsis, - ), - ), - ), - ( - (final shortcode, final image)?, - _, - _, - _, - ) => - ComposerReplacement( - removeTooltip: "Remove sticker", - onRemove: () { - draftNotifier.update( - (draft) => - draft.copyWith(sticker: null), - ); - node?.requestFocus(); - }, - onKeyEvent: sendOnEnter, - Align( - alignment: .centerLeft, - child: ConstrainedBox( - constraints: .loose(.square(128)), - child: MxcEmoji( - image.url, - label: image.body ?? shortcode, - ), - ), - ), - ), - (_, _, final draft?, _) => - ComposerReplacement( - removeTooltip: "Remove location", - onRemove: () { - draftNotifier.update( - (draft) => - draft.copyWith(location: null), - ); - node?.requestFocus(); - }, - onKeyEvent: sendOnEnter, - ListTile( - leading: Icon( - draft.assetType == .pin - ? Icons.location_pin - : Icons.my_location, - color: theme.colorScheme.primary, - ), - title: Text( - draft.description ?? - (draft.assetType == .pin - ? "Location" - : "My location"), - ), - subtitle: Text( - draft.point?.formatted ?? - draft.geoUri.toString(), - maxLines: 1, - overflow: .ellipsis, - ), - ), - ), - (_, _, _, final draft?) => - ComposerReplacement( - removeTooltip: "Remove command", - onRemove: () => - removeBotCommand(keepText: false), - onKeyEvent: sendOnEnter, - BotCommandForm( - draft, - key: ValueKey(draft.command), - onSubmit: send, - onRemove: () => - removeBotCommand(keepText: true), - ), - ), - (null, null, null, null) => FlutterTagger( - // Attaches each new controller - key: ObjectKey(controller), - triggerStrategy: .eager, - onFormattedTextChanged: - onFormattedTextChanged, - // Keeps the trigger character, so tags - // can be restored from drafts - tagTextFormatter: ( - id, - tag, - triggerCharacter, - ) => "$triggerCharacter$id#$tag#", - // Characters that continue a search, for - // e.g. :+1, :custom_emoji or @user:server - searchRegex: .new(r"^[\w.:+-]*$"), - overlay: TaggerOverlay( - query.value, - roomId: roomId, - triggerCharacter: - triggerCharacter.value, - addTag: ({required id, required name}) { - controller.addTag(id: id, name: name); - node?.requestFocus(); - }, - insertText: (text) { - final end = - controller.selection.baseOffset; - controller - ..dismissOverlay() - ..value = controller.value.replaced( - .new( - start: - end - - query.value.length - - 1, - end: end, - ), - "$text ", - ); - node?.requestFocus(); - }, - ), - controller: controller, - onSearch: - (newQuery, newTriggerCharacter) { - triggerCharacter.value = - newTriggerCharacter; - query.value = newQuery; - }, - triggerCharacterAndStyles: { - "@": style, - "#": style, - ":": style, - }, - builder: (context, key) => Focus( - onKeyEvent: onTextFieldKeyEvent, - // Overrides the keyboard shortcut for pasting - child: Actions( - actions: { - PasteTextIntent: PasteFilesAction( - pasteFiles, - ), - }, - child: Row( - spacing: 4, - children: [ - ...textCommands.map( - (command) => InputChip( - label: Text(command.prefix), - tooltip: command.description, - visualDensity: .compact, - materialTapTargetSize: - .shrinkWrap, - onDeleted: () => - removeTextCommand( - command, - ), - ), - ), - Expanded( - child: TextField( - maxLines: 12, - minLines: 1, - textCapitalization: - .sentences, - onChanged: pickTypedCommand, - autofocus: - (Platform.isLinux || - Platform.isMacOS || - Platform.isWindows), - decoration: .new( - hintText: - "Your message here...", - border: .none, - ), - controller: controller, - key: key, - focusNode: node, - // Touch taps outside don't unfocus on mobile by default - onTapOutside: (_) => - node?.unfocus(), - // The toolbar's paste button doesn't use the shortcut's action, so replace it too - contextMenuBuilder: - ( - _, - editableText, - ) => AdaptiveTextSelectionToolbar.buttonItems( - anchors: editableText - .contextMenuAnchors, - buttonItems: editableText - .contextMenuButtonItems - .map( - (item) => - item.type == - .paste - ? item.copyWith( - onPressed: () async { - editableText - .hideToolbar(); - if (!await pasteFiles()) { - item.onPressed - ?.call(); - } - }, - ) - : item, - ) - .toList(), - ), - // Images pasted from Android keyboards' clipboards are inserted as content - contentInsertionConfiguration: .new( - onContentInserted: (content) { - if (attachment != null) { - return; - } - - if (content.data - case final data?) { - attachBytes( - data, - "image.${content.mimeType.split("/").last}", - ).onError(showError); - } - }, - ), - ), - ), - ], - ), - ), - ), - ), - }, - ), - ), - IconButton( - onPressed: - attachment != null && attachment.$2 == null - ? null - : send, - icon: Icon(Icons.send), - tooltip: "Send message", - ), - ] - : [ - Expanded( - child: Padding( - padding: .symmetric( - horizontal: 8, - vertical: 12, - ), - child: Text( - "You don't have permission to send messages in this room...", - ), - ), - ), - ], + ListTile( + leading: switch (attachment.$2) { + null => SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(), + ), + ImageMessageContent() => Icon(Icons.image), + VideoMessageContent() => Icon(Icons.movie), + AudioMessageContent() => Icon(Icons.audiotrack), + _ => Icon(Icons.file_copy), + }, + title: Text(attachment.$1), + trailing: IconButton( + onPressed: () => ref.invalidate(attachmentProvider), + icon: Icon(Icons.close), ), ), + AnimatedSize( + duration: Durations.short4, + alignment: .topCenter, + child: switch (attachment.$2) { + final content? + when content is! FileMessageContent && + content.isMedia => + Padding( + padding: EdgeInsets.all(12).copyWith(top: 0), + child: Align( + alignment: .centerLeft, + child: ConstrainedBox( + constraints: .loose(.square(300)), + child: MessageMedia(content), + ), + ), + ), + _ => SizedBox(width: .infinity), + }, + ), ], ), ), - ], - ), + AnimatedSize( + duration: Durations.short4, + alignment: .bottomCenter, + child: BotCommandPanel( + composer, + commands: botCommands, + textCommands: availableTextCommands, + controller: controller, + onPick: pickBotCommand, + onPickText: pickTextCommand, + ), + ), + ClipRRect( + borderRadius: .all(.circular(12)), + child: Column( + children: [ + RelationPreview( + relatedEvent, + shouldMention: shouldMention.value, + toggleShouldMention: () => + shouldMention.value = !shouldMention.value, + relationType: relationType, + onDismiss: dismiss, + ), + Container( + color: theme.colorScheme.surfaceContainerHighest, + child: Row( + mainAxisAlignment: .center, + children: + ref.watch( + PowerLevelController.provider( + .new(eventType: .message, roomId: roomId), + ), + ) + ? [ + IconButton( + onPressed: hasReplacement + ? null + : () => context.showAdaptiveSheet( + (context) => EmojiPicker( + roomId: roomId, + onSelection: + (value, {shortcode, description}) { + Navigator.of(context).pop(); + if (shortcode == null) { + controller.text += value; + } else { + final text = + "${controller.text}:"; + controller.value = .new( + text: text, + selection: .collapsed( + offset: text.length, + ), + ); + controller.addTag( + id: ImagePack.emojiMarkdown( + shortcode, + value, + description: description, + ), + name: shortcode, + ); + } + node?.requestFocus(); + }, + ), + ), + icon: Icon(Icons.emoji_emotions), + ), + AdaptiveMenuButton( + tooltip: "Add media", + enabled: attachment == null && !hasReplacement, + itemBuilder: (context) => [ + for (final (source, title, icon) in [ + if (Platform.isAndroid || Platform.isIOS) + ( + ImageSource.camera, + "Camera", + Icons.add_a_photo, + ), + ( + ImageSource.gallery, + "Gallery", + Icons.add_photo_alternate, + ), + ]) + PopupMenuItem( + child: ListTile( + title: Text(title), + leading: Icon(icon), + ), + onTap: () => attach( + source == .gallery + ? ref + .read(FileDialogHelper.provider) + .pickFile(images: true) + : ref + .read( + ImagePickerController + .provider, + ) + .pickImage(source: source), + ).onError(showError), + ), + PopupMenuItem( + onTap: () => attach( + ref + .read(FileDialogHelper.provider) + .pickFile(), + ).onError(showError), + child: ListTile( + title: Text("Files"), + leading: Icon(Icons.attachment), + ), + ), + if (canSendStickers) + PopupMenuItem( + // Stickers can't replace messages + enabled: !isEditing, + onTap: () => context.showAdaptiveSheet( + (context) => StickerPicker( + roomId: roomId, + onSelection: (shortcode, image) { + Navigator.of(context).pop(); + draftNotifier.update( + (draft) => draft.copyWith( + sticker: (shortcode, image), + ), + ); + }, + ), + ), + child: ListTile( + title: Text("Sticker"), + leading: Icon(Icons.sticky_note_2), + ), + ), + if (canSendPolls) + PopupMenuItem( + enabled: !isEditing, + onTap: () => context.showAdaptiveSheet( + (context) => CreatePollSheet( + onCreate: (created) { + Navigator.of(context).pop(); + draftNotifier.update( + (draft) => + draft.copyWith(poll: created), + ); + }, + ), + ), + child: ListTile( + title: Text("Poll"), + leading: Icon(Icons.poll), + ), + ), + PopupMenuItem( + enabled: !isEditing, + onTap: () => context.showAdaptiveSheet( + enableDrag: false, + (context) => LocationPickerSheet( + onPick: (picked) { + Navigator.of(context).pop(); + draftNotifier.update( + (draft) => + draft.copyWith(location: picked), + ); + }, + ), + ), + child: ListTile( + title: Text("Location"), + leading: Icon(Icons.location_on), + ), + ), + ], + icon: Icon(Icons.add), + ), + SizedBox(width: 8), + Expanded( + child: AnimatedSize( + duration: Durations.short4, + alignment: .bottomCenter, + child: switch (( + sticker, + poll, + location, + botCommand, + )) { + (_, final draft?, _, _) => + ComposerReplacement( + removeTooltip: "Remove poll", + onRemove: () { + draftNotifier.update( + (draft) => draft.copyWith(poll: null), + ); + node?.requestFocus(); + }, + onKeyEvent: sendOnEnter, + ListTile( + leading: Icon( + Icons.poll, + color: theme.colorScheme.primary, + ), + title: Text(draft.question), + subtitle: Text( + draft.answers + .map((answer) => answer.text) + .join(" · "), + maxLines: 1, + overflow: .ellipsis, + ), + ), + ), + ((final shortcode, final image)?, _, _, _) => + ComposerReplacement( + removeTooltip: "Remove sticker", + onRemove: () { + draftNotifier.update( + (draft) => + draft.copyWith(sticker: null), + ); + node?.requestFocus(); + }, + onKeyEvent: sendOnEnter, + Align( + alignment: .centerLeft, + child: ConstrainedBox( + constraints: .loose(.square(128)), + child: MxcEmoji( + image.url, + label: image.body ?? shortcode, + ), + ), + ), + ), + (_, _, final draft?, _) => + ComposerReplacement( + removeTooltip: "Remove location", + onRemove: () { + draftNotifier.update( + (draft) => + draft.copyWith(location: null), + ); + node?.requestFocus(); + }, + onKeyEvent: sendOnEnter, + ListTile( + leading: Icon( + draft.assetType == .pin + ? Icons.location_pin + : Icons.my_location, + color: theme.colorScheme.primary, + ), + title: Text( + draft.description ?? + (draft.assetType == .pin + ? "Location" + : "My location"), + ), + subtitle: Text( + draft.point?.formatted ?? + draft.geoUri.toString(), + maxLines: 1, + overflow: .ellipsis, + ), + ), + ), + (_, _, _, final draft?) => + ComposerReplacement( + removeTooltip: "Remove command", + onRemove: () => + removeBotCommand(keepText: false), + onKeyEvent: sendOnEnter, + BotCommandForm( + draft, + key: ValueKey(draft.command), + onSubmit: send, + onRemove: () => + removeBotCommand(keepText: true), + ), + ), + (null, null, null, null) => FlutterTagger( + // Attaches each new controller + key: ObjectKey(controller), + triggerStrategy: .eager, + onFormattedTextChanged: + onFormattedTextChanged, + // Keeps the trigger character, so tags + // can be restored from drafts + tagTextFormatter: ( + id, + tag, + triggerCharacter, + ) => "$triggerCharacter$id#$tag#", + // Characters that continue a search, for + // e.g. :+1, :custom_emoji or @user:server + searchRegex: .new(r"^[\w.:+-]*$"), + overlay: TaggerOverlay( + query.value, + roomId: roomId, + triggerCharacter: triggerCharacter.value, + addTag: ({required id, required name}) { + controller.addTag(id: id, name: name); + node?.requestFocus(); + }, + insertText: (text) { + final end = + controller.selection.baseOffset; + controller + ..dismissOverlay() + ..value = controller.value.replaced( + .new( + start: + end - query.value.length - 1, + end: end, + ), + "$text ", + ); + node?.requestFocus(); + }, + ), + controller: controller, + onSearch: (newQuery, newTriggerCharacter) { + triggerCharacter.value = + newTriggerCharacter; + query.value = newQuery; + }, + triggerCharacterAndStyles: { + "@": style, + "#": style, + ":": style, + }, + builder: (context, key) => Focus( + onKeyEvent: onTextFieldKeyEvent, + // Overrides the keyboard shortcut for pasting + child: Actions( + actions: { + PasteTextIntent: PasteFilesAction( + pasteFiles, + ), + }, + child: Row( + spacing: 4, + children: [ + ...textCommands.map( + (command) => InputChip( + label: Text(command.prefix), + tooltip: command.description, + visualDensity: .compact, + materialTapTargetSize: + .shrinkWrap, + onDeleted: () => + removeTextCommand(command), + ), + ), + Expanded( + child: TextField( + maxLines: 12, + minLines: 1, + textCapitalization: .sentences, + onChanged: pickTypedCommand, + autofocus: + (Platform.isLinux || + Platform.isMacOS || + Platform.isWindows), + decoration: .new( + hintText: + "Your message here...", + border: .none, + ), + controller: controller, + key: key, + focusNode: node, + // The toolbar's paste button doesn't use the shortcut's action, so replace it too + contextMenuBuilder: + ( + _, + editableText, + ) => AdaptiveTextSelectionToolbar.buttonItems( + anchors: editableText + .contextMenuAnchors, + buttonItems: editableText + .contextMenuButtonItems + .map( + (item) => + item.type == + .paste + ? item.copyWith( + onPressed: () async { + editableText + .hideToolbar(); + if (!await pasteFiles()) { + item.onPressed + ?.call(); + } + }, + ) + : item, + ) + .toList(), + ), + // Images pasted from Android keyboards' clipboards are inserted as content + contentInsertionConfiguration: .new( + onContentInserted: (content) { + if (attachment != null) { + return; + } + + if (content.data + case final data?) { + attachBytes( + data, + "image.${content.mimeType.split("/").last}", + ).onError(showError); + } + }, + ), + ), + ), + ], + ), + ), + ), + ), + }, + ), + ), + IconButton( + onPressed: + attachment != null && attachment.$2 == null + ? null + : send, + icon: Icon(Icons.send), + tooltip: "Send message", + ), + ] + : [ + Expanded( + child: Padding( + padding: .symmetric( + horizontal: 8, + vertical: 12, + ), + child: Text( + "You don't have permission to send messages in this room...", + ), + ), + ), + ], + ), + ), + ], + ), + ), + ], ), ); } diff --git a/lib/widgets/composer/overlays/room_overlay.dart b/lib/widgets/composer/overlays/room_overlay.dart index 0c2fed9..c95db16 100644 --- a/lib/widgets/composer/overlays/room_overlay.dart +++ b/lib/widgets/composer/overlays/room_overlay.dart @@ -2,7 +2,6 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/controllers/via.dart"; -import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/weighted_search.dart"; import "package:nexus/widgets/avatars/avatar_or_hash.dart"; @@ -42,15 +41,15 @@ class const RoomOverlay( ? null : Text(room.metadata!.topic!, maxLines: 1), onTap: () { - final alias = room.metadata?.canonicalAlias; + final vias = ref.watch(ViaController.provider(room)).viaQuery; addTag( - id: alias == null - ? "[#$name](matrix:roomid/${room.metadata?.id.substring(1)}${ref.read(ViaController.provider(room)).viaQuery})" - : "[#$name](matrix:r/${alias.substring(1)})", + id: "[#$name](matrix:roomid/${room.metadata?.id.substring(1)}$vias)", name: - room.metadata?.canonicalAlias?.localpart ?? - room.metadata?.id ?? - "Unknown Room", + (room.metadata?.canonicalAlias ?? room.metadata?.id) + ?.substring(1) + .split(":") + .first ?? + "", ); }, ); diff --git a/lib/widgets/composer/overlays/tagger_overlay.dart b/lib/widgets/composer/overlays/tagger_overlay.dart index 264ed8c..e32a328 100644 --- a/lib/widgets/composer/overlays/tagger_overlay.dart +++ b/lib/widgets/composer/overlays/tagger_overlay.dart @@ -16,30 +16,27 @@ class const TaggerOverlay( }) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - // Lives in an overlay, so taps on it would otherwise unfocus the composer - return TextFieldTapRegion( - child: Padding( - padding: .all(8), - child: ClipRRect( - borderRadius: .all(.circular(12)), - child: Container( - color: Theme.of(context).colorScheme.surfaceContainerHigh, - padding: .all(8), - child: Material( - color: Colors.transparent, - child: switch (triggerCharacter) { - "@" => UserOverlay(query, roomId: roomId, addTag: addTag), - "#" => RoomOverlay(query, addTag: addTag), - ":" => EmojiOverlay( - query, - roomId: roomId, - addTag: addTag, - insertText: insertText, - ), + return Padding( + padding: .all(8), + child: ClipRRect( + borderRadius: .all(.circular(12)), + child: Container( + color: Theme.of(context).colorScheme.surfaceContainerHigh, + padding: .all(8), + child: Material( + color: Colors.transparent, + child: switch (triggerCharacter) { + "@" => UserOverlay(query, roomId: roomId, addTag: addTag), + "#" => RoomOverlay(query, addTag: addTag), + ":" => EmojiOverlay( + query, + roomId: roomId, + addTag: addTag, + insertText: insertText, + ), - _ => Loading(), - }, - ), + _ => Loading(), + }, ), ), ), diff --git a/lib/widgets/composer/overlays/user_overlay.dart b/lib/widgets/composer/overlays/user_overlay.dart index 40cb028..845fb3a 100644 --- a/lib/widgets/composer/overlays/user_overlay.dart +++ b/lib/widgets/composer/overlays/user_overlay.dart @@ -36,13 +36,13 @@ class const UserOverlay( ListTile( leading: AvatarOrHash( avatarUrl, - displayName ?? member.stateKey!.localpart!, + displayName ?? member.stateKey!.localpart, ), - title: Text(displayName ?? member.stateKey!.localpart!), + title: Text(displayName ?? member.stateKey!.localpart), subtitle: Text(member.stateKey!), onTap: () => addTag( id: "[@${displayName ?? member.stateKey!.localpart}](matrix:u/${member.stateKey!.substring(1)})", - name: member.stateKey!.localpart!, + name: member.stateKey!.localpart, ), ), _ => SizedBox.shrink(), diff --git a/lib/widgets/composer/subprofile_button.dart b/lib/widgets/composer/subprofile_button.dart deleted file mode 100644 index dc54b97..0000000 --- a/lib/widgets/composer/subprofile_button.dart +++ /dev/null @@ -1,53 +0,0 @@ -import "package:flutter_hooks/flutter_hooks.dart"; -import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; -import "package:material_ui/material_ui.dart"; -import "package:nexus/controllers/subprofiles.dart"; -import "package:nexus/controllers/settings.dart"; -import "package:nexus/models/room_subprofiles.dart"; -import "package:nexus/widgets/avatars/avatar_or_hash.dart"; -import "package:nexus/widgets/composer/subprofile_picker.dart"; - -/// Chooses the subprofile messages are sent as in [roomId], if subprofiles are -/// on. It shows the one the text in [controller] would trigger, if any. -class const SubprofileButton( - final String roomId, { - required final TextEditingController controller, - super.key, -}) extends HookConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final enabled = ref.watch( - SettingsController.provider.select( - (settings) => settings.value?.subprofiles ?? false, - ), - ); - final subprofiles = ref.watch(SubprofilesController.provider(roomId)); - final RoomSubprofiles(:profiles, :current) = subprofiles; - final triggered = useListenableSelector( - controller, - () => subprofiles.triggeredBy(controller.text), - ); - if (!enabled || profiles.isEmpty) return const SizedBox.shrink(); - final shown = triggered ?? current; - - return IconButton( - tooltip: switch ((triggered, current)) { - (final triggered?, _) => - "Sending this message as ${triggered.displayName ?? triggered.id}", - (null, final current?) => - "Sending as ${current.displayName ?? current.id}", - (null, null) => "Choose subprofile", - }, - icon: switch (shown) { - final shown? => AvatarOrHash( - shown.avatarUrl, - shown.displayName ?? shown.id, - ), - null => Icon(Icons.person), - }, - onPressed: () => - context.showAdaptivePopover((_) => SubprofilePicker(roomId)), - ); - } -} diff --git a/lib/widgets/composer/subprofile_picker.dart b/lib/widgets/composer/subprofile_picker.dart deleted file mode 100644 index 425038e..0000000 --- a/lib/widgets/composer/subprofile_picker.dart +++ /dev/null @@ -1,101 +0,0 @@ -import "package:flutter_hooks/flutter_hooks.dart"; -import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:material_ui/material_ui.dart"; -import "package:nexus/controllers/account_data.dart"; -import "package:nexus/controllers/subprofiles.dart"; -import "package:nexus/main.dart"; -import "package:nexus/widgets/avatars/avatar_or_hash.dart"; - -/// Searches the subprofiles usable in [roomId], to choose which messages are -/// sent as there. -class const SubprofilePicker(final String roomId, {super.key}) - extends HookConsumerWidget { - static const accountProfile = "Account Profile"; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final subprofiles = ref.watch(SubprofilesController.provider(roomId)); - final searchController = useTextEditingController(); - final query = useValueListenable(searchController).text - .trim() - .toLowerCase(); - bool found(String text) => text.toLowerCase().contains(query); - - // An empty ID is the account profile - final results = <({String id, String name, Uri? avatar})>[ - if (found(accountProfile)) (id: "", name: accountProfile, avatar: null), - ...subprofiles.profiles - .where( - (profile) => - found(profile.displayName ?? profile.id) || - profile.triggers.any( - (trigger) => [ - trigger.prefix, - trigger.suffix, - ].any((part) => part.isNotEmpty && found(part)), - ), - ) - .map( - (profile) => ( - id: profile.id, - name: profile.displayName ?? profile.id, - avatar: profile.avatarUrl, - ), - ), - ]; - - void choose(String id) { - Navigator.of(context).pop(); - if (id == (subprofiles.current?.id ?? "")) return; - ref - .read(AccountDataController.provider.notifier) - .setRoomProfile(roomId, id) - .onError(showError); - } - - return Column( - mainAxisSize: .min, - crossAxisAlignment: .stretch, - children: [ - Padding( - padding: .all(16), - child: TextField( - controller: searchController, - autofocus: true, - onSubmitted: (_) { - if (results.firstOrNull case final first?) choose(first.id); - }, - decoration: const .new( - prefixIcon: Icon(Icons.search), - hintText: "Search subprofiles", - ), - ), - ), - Flexible( - child: results.isEmpty - ? Padding( - padding: .only(bottom: 16), - child: Text("No subprofiles found", textAlign: .center), - ) - : ListView( - shrinkWrap: true, - padding: .only(bottom: 8), - children: results.map((result) { - final selected = - (subprofiles.current?.id ?? "") == result.id; - return ListTile( - selected: selected, - leading: result.id.isEmpty - ? Icon(Icons.person) - : AvatarOrHash(result.avatar, result.name), - title: Text(result.name), - trailing: selected ? Icon(Icons.check) : null, - onTap: () => choose(result.id), - ); - }).toList(), - ), - ), - ], - ); - } -} diff --git a/lib/widgets/composer/typing_indicator.dart b/lib/widgets/composer/typing_indicator.dart index e8e452b..9cacb9c 100644 --- a/lib/widgets/composer/typing_indicator.dart +++ b/lib/widgets/composer/typing_indicator.dart @@ -37,7 +37,7 @@ class const TypingIndicator(final String roomId, {super.key}) ) .value ?.displayName ?? - typingUserId.localpart!, + typingUserId.localpart, userId: typingUserId, roomId: roomId, recognizer: recognizers[index], diff --git a/lib/widgets/emoji/emoji_picker.dart b/lib/widgets/emoji/emoji_picker.dart index 086bd1a..fb834c9 100644 --- a/lib/widgets/emoji/emoji_picker.dart +++ b/lib/widgets/emoji/emoji_picker.dart @@ -45,7 +45,6 @@ class const EmojiPicker({ const .empty(); return upstream.EmojiPicker( - searchHint: "Search or send emoji...", onSelection: (emoji) async { final image = switch (emoji.data) { final PackImage image => image, diff --git a/lib/widgets/encryption/recovery_key_sheet.dart b/lib/widgets/encryption/recovery_key_sheet.dart index f4c2fea..36e4e09 100644 --- a/lib/widgets/encryption/recovery_key_sheet.dart +++ b/lib/widgets/encryption/recovery_key_sheet.dart @@ -6,7 +6,7 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client.dart"; -import "package:nexus/controllers/account_management.dart"; +import "package:nexus/controllers/client_state.dart"; import "package:nexus/helpers/launch_helper.dart"; import "package:nexus/models/gomuks_exception.dart"; import "package:nexus/models/recovery_key.dart"; @@ -41,10 +41,15 @@ class const RecoveryKeySheet( // Open the approval page straight away the first time. if (!needsApproval.value) { needsApproval.value = true; - final url = await ref - .read(AccountManagementController.provider.future) - .then((management) => management?.urlFor(.crossSigningReset)) - .onError((_, _) => null); + final homeserver = ref + .read(ClientStateController.provider) + ?.homeserverUrl; + final url = homeserver == null + ? null + : await ref + .read(ClientController.provider.notifier) + .getCrossSigningResetUrl(.parse(homeserver)) + .onError((_, _) => null); if (!context.mounted || url == null) return; approvalUrl.value = url; diff --git a/lib/widgets/html/html.dart b/lib/widgets/html/html.dart index 76b656e..9236e9a 100644 --- a/lib/widgets/html/html.dart +++ b/lib/widgets/html/html.dart @@ -8,7 +8,7 @@ import "package:nexus/helpers/launch_helper.dart"; import "package:nexus/helpers/mxc_image.dart"; import "package:nexus/widgets/common/expandable_image.dart"; import "package:nexus/widgets/html/mention_chip.dart"; -import "package:nexus/widgets/html/spoiler.dart"; +import "package:nexus/widgets/html/spoiler_text.dart"; import "package:nexus/widgets/html/code_block.dart"; import "package:nexus/widgets/html/quoted.dart"; @@ -29,11 +29,7 @@ class const Html( } if (element.attributes.keys.contains("data-mx-spoiler")) { - return InlineCustomWidget( - child: Spoiler( - Html(element.innerHtml, textStyle: textStyle, roomId: roomId), - ), - ); + return InlineCustomWidget(child: SpoilerText(element.text)); } final height = @@ -98,6 +94,7 @@ class const Html( alignment: .middle, child: ExpandableImage( .new(mxc: src), + downloadFilename: src.pathSegments.last, child: Image( image: MxcImage(ref, .new(mxc: src)), errorBuilder: (_, error, _) => Text( diff --git a/lib/widgets/html/spoiler.dart b/lib/widgets/html/spoiler_text.dart similarity index 64% rename from lib/widgets/html/spoiler.dart rename to lib/widgets/html/spoiler_text.dart index 7970bf3..e4a5977 100644 --- a/lib/widgets/html/spoiler.dart +++ b/lib/widgets/html/spoiler_text.dart @@ -1,7 +1,7 @@ import "package:material_ui/material_ui.dart"; import "package:flutter_hooks/flutter_hooks.dart"; -class const Spoiler(final Widget child, {super.key}) extends HookWidget { +class const SpoilerText(final String text, {super.key}) extends HookWidget { @override Widget build(BuildContext context) { final revealed = useState(false); @@ -10,15 +10,15 @@ class const Spoiler(final Widget child, {super.key}) extends HookWidget { onTap: () => revealed.value = !revealed.value, child: AnimatedContainer( duration: Durations.short2, + padding: const .symmetric(horizontal: 4, vertical: 2), decoration: BoxDecoration( - color: Colors.blueGrey.withValues(alpha: 0.3), - borderRadius: .circular(4), - ), - foregroundDecoration: BoxDecoration( color: revealed.value ? Colors.transparent : Colors.blueGrey, borderRadius: .circular(4), ), - child: IgnorePointer(ignoring: !revealed.value, child: child), + child: Text( + text, + style: .new(color: revealed.value ? null : Colors.transparent), + ), ), ); } diff --git a/lib/widgets/lazy_loading/message_avatar.dart b/lib/widgets/lazy_loading/message_avatar.dart index cb75f02..80a1101 100644 --- a/lib/widgets/lazy_loading/message_avatar.dart +++ b/lib/widgets/lazy_loading/message_avatar.dart @@ -19,10 +19,10 @@ class const MessageAvatar( context.showUserPopover(event.sender, roomId: event.roomId), child: AvatarOrHash( value.avatarUrl, - value.displayName ?? event.sender.localpart!, + value.displayName ?? event.sender.localpart, dimension: height, ), ), - _ => AvatarOrHash(null, event.sender.localpart!, dimension: height), + _ => AvatarOrHash(null, event.sender.localpart, dimension: height), }; } diff --git a/lib/widgets/lazy_loading/message_displayname.dart b/lib/widgets/lazy_loading/message_displayname.dart index b591935..0f68ac5 100644 --- a/lib/widgets/lazy_loading/message_displayname.dart +++ b/lib/widgets/lazy_loading/message_displayname.dart @@ -1,7 +1,6 @@ import "package:material_ui/material_ui.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/author.dart"; -import "package:nexus/controllers/user.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/show_user_popover.dart"; import "package:nexus/helpers/extensions/displayname_color.dart"; @@ -28,14 +27,14 @@ class const MessageDisplayname( : null, child: switch ([ Text( - value?.displayName ?? event.sender.localpart!, + value?.displayName ?? event.sender.localpart, style: style ?? .new(color: color, fontWeight: .bold), maxLines: 1, overflow: .ellipsis, ), if (event.pmp != null) Text( - "(${ref.watch(UserController.provider(.new(roomId: event.roomId, userId: event.sender))).value?.displayName ?? event.sender.localpart})", + "(via ${event.sender})", style: Theme.of(context).textTheme.labelSmall ?.copyWith(color: color, fontWeight: .bold), maxLines: 1, diff --git a/lib/widgets/pages/chat.dart b/lib/widgets/pages/chat.dart index 8e66b9e..c5d704f 100644 --- a/lib/widgets/pages/chat.dart +++ b/lib/widgets/pages/chat.dart @@ -4,7 +4,6 @@ import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/init_complete.dart"; import "package:nexus/controllers/link_request.dart"; -import "package:nexus/controllers/share_request.dart"; import "package:nexus/helpers/extensions/open_link_info.dart"; import "package:nexus/main.dart"; import "package:nexus/controllers/selected_room.dart"; @@ -13,7 +12,6 @@ import "package:nexus/widgets/common/appbar.dart"; import "package:nexus/widgets/sidebar/sidebar.dart"; import "package:nexus/widgets/common/sync_status_banner.dart"; import "package:nexus/widgets/room_chat/room_chat.dart"; -import "package:nexus/widgets/rooms/share_sheet.dart"; import "package:nexus/widgets/common/loading.dart"; class const ChatPage({super.key}) extends HookConsumerWidget { @@ -55,21 +53,6 @@ class const ChatPage({super.key}) extends HookConsumerWidget { return null; }, [linkRequest, initComplete]); - final shareRequest = ref.watch(ShareRequestController.provider); - - useEffect(() { - if (shareRequest == null || !initComplete) return null; - - WidgetsBinding.instance.addPostFrameCallback((_) { - ref.read(ShareRequestController.provider.notifier).consume(); - navigatorKey.currentState?.popUntil((route) => route.isFirst); - scaffoldKey.currentContext?.showAdaptiveSheet( - (_) => ShareSheet(shareRequest), - ); - }); - return null; - }, [shareRequest, initComplete]); - return LayoutBuilder( builder: (context, constraints) { final isDesktop = context.isDesktop; diff --git a/lib/widgets/players/video.dart b/lib/widgets/players/video.dart index 76c8641..053041a 100644 --- a/lib/widgets/players/video.dart +++ b/lib/widgets/players/video.dart @@ -1,8 +1,6 @@ import "dart:async"; -import "dart:io"; import "package:better_player/better_player.dart"; -import "package:flutter/services.dart"; import "package:material_ui/material_ui.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:nexus/controllers/client.dart"; @@ -12,7 +10,6 @@ import "package:nexus/models/info/video.dart"; import "package:nexus/widgets/common/error_dialog.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:nexus/widgets/players/player_controls.dart"; -import "package:window_manager/window_manager.dart"; class const VideoPlayer( final Uri uri, @@ -35,41 +32,6 @@ class const VideoPlayer( PlayerConfiguration( aspectRatio: aspectRatio, fit: .contain, - autoDetectFullscreenDeviceOrientation: true, - routePageBuilder: - (context, animation, secondaryAnimation, provider) => HookBuilder( - builder: (context) { - useEffect(() { - if (!(Platform.isLinux || - Platform.isMacOS || - Platform.isWindows)) { - return null; - } - final window = WindowManager.instance.getCurrent(); - if (window == null || window.isFullScreen) return null; - - window.isFullScreen = true; - return () => window.isFullScreen = false; - }, []); - - return Focus( - autofocus: true, - onKeyEvent: (_, event) { - if (event is KeyDownEvent && - event.logicalKey == .escape) { - provider.controller.exitFullScreen(); - return .handled; - } - return .ignored; - }, - child: Scaffold( - backgroundColor: Colors.black, - resizeToAvoidBottomInset: false, - body: SizedBox.expand(child: provider), - ), - ); - }, - ), controlsConfiguration: PlayerControlsConfiguration( playerTheme: .custom, customControlsBuilder: (controller, _) => HookBuilder( diff --git a/lib/widgets/reactions/reactions_popover.dart b/lib/widgets/reactions/reactions_popover.dart index cf4b717..44c455b 100644 --- a/lib/widgets/reactions/reactions_popover.dart +++ b/lib/widgets/reactions/reactions_popover.dart @@ -64,29 +64,25 @@ class const ReactionsPopover( controller: tabController, isScrollable: true, tabAlignment: .start, - labelPadding: .zero, tabs: keys.map((reaction) { void expand() => context.showImageViewer( ref, .new(mxc: Uri.parse(reaction)), + downloadFilename: reaction.split("/").last, ); final isImage = reaction.startsWith("mxc://"); return GestureDetector( - behavior: .opaque, onSecondaryTap: isImage ? expand : null, onLongPress: isImage ? expand : null, - child: Padding( - padding: kTabLabelPadding, - child: Tab( - child: Row( - mainAxisSize: .min, - spacing: 8, - children: [ - ReactionKey(reaction, height: 20), - Text(reactions[reaction]!.senders.length.toString()), - ], - ), + child: Tab( + child: Row( + mainAxisSize: .min, + spacing: 8, + children: [ + ReactionKey(reaction, height: 20), + Text(reactions[reaction]!.senders.length.toString()), + ], ), ), ); @@ -122,7 +118,7 @@ class const ReactionsPopover( return ListTile( leading: AvatarOrHash( member?.avatarUrl, - name!, + name, dimension: 40, ), title: Text(name, overflow: .ellipsis), diff --git a/lib/widgets/read_receipts/read_receipts_row.dart b/lib/widgets/read_receipts/read_receipts_row.dart index b23695d..156d3f8 100644 --- a/lib/widgets/read_receipts/read_receipts_row.dart +++ b/lib/widgets/read_receipts/read_receipts_row.dart @@ -73,7 +73,7 @@ class const ReadReceiptsRow( receipt.userId.localpart; return AvatarRing( - tooltip: name!, + tooltip: name, onTap: () => context.showUserPopover( receipt.userId, roomId: chat.roomId, diff --git a/lib/widgets/read_receipts/read_receipts_sheet.dart b/lib/widgets/read_receipts/read_receipts_sheet.dart index 9f8e537..3021102 100644 --- a/lib/widgets/read_receipts/read_receipts_sheet.dart +++ b/lib/widgets/read_receipts/read_receipts_sheet.dart @@ -38,7 +38,7 @@ class const ReadReceiptsSheet( final name = member?.displayName ?? receipt.userId.localpart; return ListTile( - leading: AvatarOrHash(member?.avatarUrl, name!, dimension: 40), + leading: AvatarOrHash(member?.avatarUrl, name, dimension: 40), title: Text(name, overflow: .ellipsis), subtitle: Text(receipt.userId, overflow: .ellipsis), onTap: () => context.showUserPopover( diff --git a/lib/widgets/renderers/diffs/pinned_events_diff.dart b/lib/widgets/renderers/diffs/pinned_events_diff.dart index b5e6434..41bd3a1 100644 --- a/lib/widgets/renderers/diffs/pinned_events_diff.dart +++ b/lib/widgets/renderers/diffs/pinned_events_diff.dart @@ -1,8 +1,13 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/event.dart"; +import "package:nexus/controllers/rooms.dart"; import "package:nexus/helpers/hooks/chat_scroll.dart"; import "package:nexus/helpers/extensions/success_scheme.dart"; -import "package:nexus/widgets/renderers/related_event_line.dart"; +import "package:nexus/models/content/message.dart"; +import "package:nexus/widgets/lazy_loading/message_displayname.dart"; +import "package:nexus/widgets/renderers/event.dart"; /// A line for each message a pinned events event pinned, in green, and each one /// it unpinned, in red and struck through. @@ -14,11 +19,11 @@ class const PinnedEventsDiff( /// If set, tapping a message jumps to it. final JumpToEvent? jumpToEvent, super.key, -}) extends StatelessWidget { +}) extends ConsumerWidget { static const maxShown = 5; @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); final style = theme.textTheme.labelMedium; final changes = [ @@ -38,12 +43,66 @@ class const PinnedEventsDiff( ? TextDecoration.lineThrough : null; - return RelatedEventLine( - roomId, - change.$1, - color: color, - decoration: decoration, - jumpToEvent: jumpToEvent, + return DefaultTextStyle.merge( + style: style?.copyWith( + color: color, + decoration: decoration, + decorationColor: color, + ), + child: switch (ref.watch( + EventController.provider( + .new(roomId: roomId, eventId: change.$1), + ), + )) { + // Keeps showing the event while it reloads + AsyncValue(value: final rowId?) => InkWell( + borderRadius: .circular(4), + hoverColor: color.withValues(alpha: 0.12), + onTap: jumpToEvent == null ? null : () => jumpToEvent!(rowId), + child: Row( + mainAxisSize: .min, + children: [ + // Other events already say who sent them + if (ref.watch( + RoomsController.provider.select( + (rooms) => rooms[roomId]?.events[rowId], + ), + ) + case final event? + when event.content is MessageContent) ...[ + MessageDisplayname( + event, + clickable: false, + shouldWrap: false, + style: .new( + color: color, + fontWeight: .bold, + decoration: decoration, + decorationColor: color, + ), + ), + Text(": "), + ], + Flexible( + child: IgnorePointer( + child: EventRenderer( + rowId, + roomId: roomId, + textOnly: true, + maxLines: 1, + ), + ), + ), + ], + ), + ), + AsyncLoading() => SizedBox.square( + dimension: 12, + child: CircularProgressIndicator(strokeWidth: 2, color: color), + ), + // Like if it was deleted, or the server won't share it + _ => Text("Message not found"), + }, ); }), if (changes.length > maxShown) diff --git a/lib/widgets/renderers/diffs/power_levels_diff.dart b/lib/widgets/renderers/diffs/power_levels_diff.dart index e6af7c5..f90c917 100644 --- a/lib/widgets/renderers/diffs/power_levels_diff.dart +++ b/lib/widgets/renderers/diffs/power_levels_diff.dart @@ -104,7 +104,7 @@ class const PowerLevelsDiff( ) .value ?.displayName ?? - change.$1.localpart!, + change.$1.localpart, style: style?.copyWith( fontWeight: .bold, color: ref.displaynameColorAt( diff --git a/lib/widgets/renderers/event.dart b/lib/widgets/renderers/event.dart index a9f2f92..228abf6 100644 --- a/lib/widgets/renderers/event.dart +++ b/lib/widgets/renderers/event.dart @@ -27,24 +27,18 @@ import "package:nexus/models/content/membership.dart"; import "package:nexus/models/content/name.dart"; import "package:nexus/models/content/pinned_events.dart"; import "package:nexus/models/content/poll_end.dart"; -import "package:nexus/models/content/message.dart"; -import "package:nexus/models/content/poll_response.dart"; import "package:nexus/models/content/power_levels.dart"; -import "package:nexus/models/content/reaction.dart"; -import "package:nexus/models/content/redaction.dart"; import "package:nexus/models/content/server_acl.dart"; import "package:nexus/models/content/tombstone.dart"; import "package:nexus/models/content/topic.dart"; import "package:nexus/models/event.dart"; import "package:nexus/widgets/common/error_dialog.dart"; import "package:nexus/widgets/renderers/message.dart"; -import "package:nexus/widgets/reactions/reaction_key.dart"; import "package:nexus/widgets/reactions/reaction_row.dart"; import "package:nexus/widgets/read_receipts/read_receipts_row.dart"; import "package:nexus/widgets/renderers/membership.dart"; import "package:nexus/widgets/renderers/diffs/change_line.dart"; import "package:nexus/widgets/renderers/generic_event.dart"; -import "package:nexus/widgets/renderers/related_event_line.dart"; import "package:nexus/widgets/renderers/diffs/join_rules_diff.dart"; import "package:nexus/widgets/renderers/diffs/power_levels_diff.dart"; import "package:nexus/widgets/renderers/diffs/pinned_events_diff.dart"; @@ -80,6 +74,7 @@ class const EventRenderer( Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); final colorScheme = theme.colorScheme; + final errorStyle = TextStyle(color: colorScheme.error); final focusNode = useFocusNode(); useListenable(focusNode); final senderRecognizer = useTapRecognizer(); @@ -109,12 +104,12 @@ class const EventRenderer( if (event == null) return SizedBox.shrink(); - final (hideMembershipEvents, showHiddenEvents) = ref + final (hideMembershipEvents, hideServerAclEvents) = ref .watch(SettingsController.provider) .maybeWhen( - orElse: () => (false, false), + orElse: () => (false, true), data: (settings) => - (settings.hideMembershipEvents, settings.showHiddenEvents), + (settings.hideMembershipEvents, settings.hideServerAclEvents), ); final isHidden = @@ -126,7 +121,7 @@ class const EventRenderer( (content) => content is MembershipContent && content.status == .knock, )) || - (!showHiddenEvents && event.content is ServerACLContent); + (hideServerAclEvents && event.content is ServerACLContent); if (isHidden && !textOnly) return SizedBox.shrink(); @@ -144,7 +139,6 @@ class const EventRenderer( GenericEventRenderer generic( IconData icon, String text, { - List spans = const [], List details = const [], }) => .new( icon, @@ -154,13 +148,9 @@ class const EventRenderer( [ UserSpan.sender(context, ref, event, recognizer: senderRecognizer), TextSpan(text: text), - ...spans, ], ); - Widget relatedLine(String eventId) => - RelatedEventLine(roomId, eventId, jumpToEvent: jumpToEvent); - // For rooms an upgrade links, i.e. the old and new rooms Widget roomLink(String label, String linkedRoomId) => InkWell( onTap: () => ref @@ -182,15 +172,8 @@ class const EventRenderer( ), ); - // Deleted messages still take their place in threads, and among hidden - // events, but other deleted events aren't messages - final isDeletedMessage = - event.redactedBy != null && - event.stateKey == null && - event.type != "m.reaction"; - final shown = - event.isShownAsMessage || - (isDeletedMessage && (isThreadRoot || textOnly || showHiddenEvents)) + final child = + event.isShownAsMessage || (isThreadRoot && event.redactedBy != null) ? MessageRenderer( event, onTapReply: jumpToEvent == null @@ -452,113 +435,6 @@ class const EventRenderer( _ => null, }; - final child = - shown ?? - (!textOnly && !showHiddenEvents - ? null - : event.redactedBy != null - ? generic( - Icons.delete, - "sent ${event.stateKey == null ? "a reaction" : "a state event"} that was deleted", - ) - : event.relationType == "m.replace" - ? generic( - Icons.edit, - "edited a message", - details: [ - if (event.relatesTo case final id?) relatedLine(id), - if (event.content case MessageContent(:final body?)) - ChangeLine( - added: [body].lock, - removedColor: removedColor, - addedColor: addedColor, - quoted: false, - ), - ], - ) - : switch (event.content) { - ReactionContent(:final key?, :final shortcode) => generic( - Icons.add_reaction, - "reacted with", - spans: [ - WidgetSpan( - alignment: .middle, - child: Tooltip( - message: shortcode ?? key, - child: ReactionKey(key, height: 20), - ), - ), - ], - details: [ - if (event.relatesTo case final id?) relatedLine(id), - ], - ), - ReactionContent() => generic( - Icons.add_reaction, - "reacted to a message", - details: [ - if (event.relatesTo case final id?) relatedLine(id), - ], - ), - RedactionContent(:final redacts, :final reason) => generic( - Icons.delete, - "deleted an event", - details: [ - if (redacts ?? event.relatesTo case final id?) - relatedLine(id), - if (reason != null && reason.isNotEmpty) - Text( - "Reason: $reason", - style: theme.textTheme.labelMedium, - ), - ], - ), - PollResponseContent(:final answers) => generic( - Icons.how_to_vote, - answers.isEmpty - ? "removed their vote in a poll" - : "voted in a poll", - details: [ - if (event.relatesTo case final id?) relatedLine(id), - ], - ), - MembershipContent(:final displayName, :final avatarUrl) => () { - final previous = switch (event.previousContent) { - final MembershipContent previous => previous, - _ => null, - }; - final nameChanged = previous?.displayName != displayName; - final avatarChanged = previous?.avatarUrl != avatarUrl; - - return generic( - Icons.person, - switch ((nameChanged, avatarChanged)) { - (true, true) => "changed their profile", - (true, false) when displayName == null => - "removed their display name", - (true, false) => "changed their display name", - (false, true) when avatarUrl == null => - "removed their avatar", - (false, true) => "changed their avatar", - (false, false) => "updated their membership", - }, - details: [ - if (nameChanged) - ChangeLine( - removed: [?previous?.displayName].lock, - added: [?displayName].lock, - removedColor: removedColor, - addedColor: addedColor, - ), - ], - ); - }(), - _ => generic( - Icons.code, - "sent ${event.stateKey == null ? "an event" : "a state event"} of type ${event.type}", - ), - }); - final contextMenuCallback = getEventOptions == null ? null : (PositionedGestureDetails details) => context.showAdaptiveMenu( @@ -686,6 +562,11 @@ class const EventRenderer( ), ), ] + else if (textOnly) + Text( + event.redactedBy == null ? "Unknown event type" : "Redacted event", + style: errorStyle, + ) else if (threadSummary != null) Padding(padding: .only(left: 4), child: threadSummary), diff --git a/lib/widgets/renderers/event_preview.dart b/lib/widgets/renderers/event_preview.dart index 4f5c2b3..53e10ac 100644 --- a/lib/widgets/renderers/event_preview.dart +++ b/lib/widgets/renderers/event_preview.dart @@ -18,8 +18,7 @@ class const EventPreview( ); if (event == null) return SizedBox.shrink(); - final showSender = - event.hasMessageContent && event.relationType != "m.replace"; + final showSender = event.hasMessageContent; return IgnorePointer( child: Padding( diff --git a/lib/widgets/renderers/membership.dart b/lib/widgets/renderers/membership.dart index 53f8f10..125ea64 100644 --- a/lib/widgets/renderers/membership.dart +++ b/lib/widgets/renderers/membership.dart @@ -34,7 +34,7 @@ class const MembershipRenderer( [ UserSpan( context, - content.displayName ?? event.stateKey!.localpart!, + content.displayName ?? event.stateKey!.localpart, userId: event.stateKey!, roomId: event.roomId, recognizer: targetRecognizer, diff --git a/lib/widgets/renderers/related_event_line.dart b/lib/widgets/renderers/related_event_line.dart deleted file mode 100644 index 191ad1e..0000000 --- a/lib/widgets/renderers/related_event_line.dart +++ /dev/null @@ -1,85 +0,0 @@ -import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:material_ui/material_ui.dart"; -import "package:nexus/controllers/event.dart"; -import "package:nexus/controllers/rooms.dart"; -import "package:nexus/helpers/hooks/chat_scroll.dart"; -import "package:nexus/helpers/extensions/is_shown_as_message.dart"; -import "package:nexus/widgets/lazy_loading/message_displayname.dart"; -import "package:nexus/widgets/renderers/event.dart"; - -/// A single line previewing another event, like the message a reaction is on, -/// with its sender if it's a message. -class const RelatedEventLine( - final String roomId, - final String eventId, { - final Color? color, - final TextDecoration? decoration, - - /// If set, tapping the event jumps to it. - final JumpToEvent? jumpToEvent, - super.key, -}) extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = Theme.of(context); - final color = this.color ?? theme.colorScheme.onSurfaceVariant; - - return DefaultTextStyle.merge( - style: theme.textTheme.labelMedium?.copyWith( - color: color, - decoration: decoration, - decorationColor: color, - ), - child: switch (ref.watch( - EventController.provider(.new(roomId: roomId, eventId: eventId)), - )) { - AsyncValue(value: final rowId?) => InkWell( - borderRadius: .circular(4), - hoverColor: color.withValues(alpha: 0.12), - onTap: jumpToEvent == null ? null : () => jumpToEvent!(rowId), - child: Row( - mainAxisSize: .min, - children: [ - if (ref.watch( - RoomsController.provider.select( - (rooms) => rooms[roomId]?.events[rowId], - ), - ) - case final event? - when event.hasMessageContent && - event.relationType != "m.replace") ...[ - MessageDisplayname( - event, - clickable: false, - shouldWrap: false, - style: .new( - color: color, - fontWeight: .bold, - decoration: decoration, - decorationColor: color, - ), - ), - Text(": "), - ], - Flexible( - child: IgnorePointer( - child: EventRenderer( - rowId, - roomId: roomId, - textOnly: true, - maxLines: 1, - ), - ), - ), - ], - ), - ), - AsyncLoading() => SizedBox.square( - dimension: 12, - child: CircularProgressIndicator(strokeWidth: 2, color: color), - ), - _ => Text("Message not found"), - }, - ); - } -} diff --git a/lib/widgets/room_chat/member_list.dart b/lib/widgets/room_chat/member_list.dart index fe887e1..a967075 100644 --- a/lib/widgets/room_chat/member_list.dart +++ b/lib/widgets/room_chat/member_list.dart @@ -140,7 +140,7 @@ class const MemberList(final String roomId, {super.key}) displayName ?? members[index] .stateKey! - .localpart!, + .localpart, overflow: .ellipsis, style: .new( color: ref.displaynameColor( @@ -162,7 +162,7 @@ class const MemberList(final String roomId, {super.key}) displayName ?? members[index] .stateKey! - .localpart!, + .localpart, ), ), ), diff --git a/lib/widgets/room_chat/room_chat.dart b/lib/widgets/room_chat/room_chat.dart index 8a149b3..8a29c38 100644 --- a/lib/widgets/room_chat/room_chat.dart +++ b/lib/widgets/room_chat/room_chat.dart @@ -1,5 +1,4 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:flutter/services.dart"; import "package:material_ui/material_ui.dart"; import "package:flutter_hooks/flutter_hooks.dart"; import "package:hooks_riverpod/hooks_riverpod.dart"; @@ -47,28 +46,6 @@ final class const RoomChat({ final thread = useState<({String root, int? event})?>(null); final threadScaffold = useMemoized(GlobalKey.new); - final searchScaffold = useMemoized(GlobalKey.new); - - useEffect(() { - bool openSearch(KeyEvent event) { - final keyboard = HardwareKeyboard.instance; - final search = searchScaffold.currentState; - if (event is! KeyDownEvent || - event.logicalKey != .keyF || - !(keyboard.isControlPressed || keyboard.isMetaPressed) || - search == null || - !context.mounted || - !(ModalRoute.of(context)?.isCurrent ?? true)) { - return false; - } - - search.openEndDrawer(); - return true; - } - - HardwareKeyboard.instance.addHandler(openSearch); - return () => HardwareKeyboard.instance.removeHandler(openSearch); - }, []); final userId = ref.watch(ClientStateController.provider)?.userId; final memberListOpened = ref @@ -200,7 +177,6 @@ final class const RoomChat({ null => null, }, body: Scaffold( - key: searchScaffold, endDrawerEnableOpenDragGesture: false, endDrawer: SearchDrawer( roomId, diff --git a/lib/widgets/rooms/room_menu_button.dart b/lib/widgets/rooms/room_menu_button.dart index 47d4d42..22d94f9 100644 --- a/lib/widgets/rooms/room_menu_button.dart +++ b/lib/widgets/rooms/room_menu_button.dart @@ -7,11 +7,9 @@ import "package:flutter/services.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/account_data.dart"; import "package:nexus/controllers/client.dart"; -import "package:nexus/controllers/power_level.dart"; import "package:nexus/models/room_notification_level.dart"; import "package:nexus/controllers/room_settings_sections.dart"; import "package:nexus/widgets/settings/settings_layout.dart"; -import "package:nexus/widgets/users/room_profile_sheet.dart"; import "package:nexus/controllers/via.dart"; import "package:nexus/models/room.dart"; import "package:flutter_hooks/flutter_hooks.dart"; @@ -101,92 +99,73 @@ final class const RoomMenuButton( title: Text("Copy Link"), ), ), - if (ref.read( - PowerLevelController.provider( - .membershipAction( - action: .invite, - roomId: room!.metadata!.id, - targetUser: "", - ), - ), - )) - PopupMenuItem( - onTap: () => context.showAdaptiveSheet( - (context) => HookBuilder( - builder: (context) { - final userIdController = useTextEditingController(); - final reasonController = useTextEditingController(); - final text = useValueListenable(userIdController).text - .trim(); - final valid = text.isValidUserId; - - void submit() { - if (!valid) return; - Navigator.of(context).pop(); - final reason = reasonController.text.trim(); - client - .setMembership( - .new( - userId: text, - roomId: room!.metadata!.id, - action: .invite, - reason: reason.isEmpty ? null : reason, - ), - ) - .onError(showError); - } - - return SheetLayout( - title: Text("Invite User"), - actions: [ - TextButton( - onPressed: Navigator.of(context).pop, - child: Text("Cancel"), - ), - TextButton( - onPressed: valid ? submit : null, - child: Text("Invite"), - ), - ], - children: [ - TextField( - controller: userIdController, - autofocus: true, - keyboardType: .emailAddress, - onSubmitted: (_) => submit(), - decoration: .new( - labelText: "User ID", - hintText: "@user:example.com", - errorText: text.isEmpty || valid - ? null - : "Enter a valid user ID", - ), - ), - TextField( - controller: reasonController, - textCapitalization: .sentences, - onSubmitted: (_) => submit(), - decoration: const .new( - labelText: "Invite reason (optional)", - ), - ), - ], - ); - }, - ), - ), - child: ListTile( - leading: Icon(Icons.person_add), - title: Text("Invite"), - ), - ), PopupMenuItem( onTap: () => context.showAdaptiveSheet( - (_) => RoomProfileSheet(room!.metadata!.id), + (context) => HookBuilder( + builder: (context) { + final userIdController = useTextEditingController(); + final reasonController = useTextEditingController(); + final text = useValueListenable(userIdController).text.trim(); + final valid = text.isValidUserId; + + void submit() { + if (!valid) return; + Navigator.of(context).pop(); + final reason = reasonController.text.trim(); + client + .setMembership( + .new( + userId: text, + roomId: room!.metadata!.id, + action: .invite, + reason: reason.isEmpty ? null : reason, + ), + ) + .onError(showError); + } + + return SheetLayout( + title: Text("Invite User"), + actions: [ + TextButton( + onPressed: Navigator.of(context).pop, + child: Text("Cancel"), + ), + TextButton( + onPressed: valid ? submit : null, + child: Text("Invite"), + ), + ], + children: [ + TextField( + controller: userIdController, + autofocus: true, + keyboardType: .emailAddress, + onSubmitted: (_) => submit(), + decoration: .new( + labelText: "User ID", + hintText: "@user:example.com", + errorText: text.isEmpty || valid + ? null + : "Enter a valid user ID", + ), + ), + TextField( + controller: reasonController, + textCapitalization: .sentences, + onSubmitted: (_) => submit(), + decoration: const .new( + labelText: "Invite reason (optional)", + ), + ), + ], + ); + }, + ), ), child: ListTile( - leading: Icon(Icons.manage_accounts), - title: Text("Room Profile"), + leading: Icon(Icons.person_add), + title: Text("Invite"), ), ), PopupMenuItem( diff --git a/lib/widgets/rooms/room_summary_sheet.dart b/lib/widgets/rooms/room_summary_sheet.dart index 54def51..2195101 100644 --- a/lib/widgets/rooms/room_summary_sheet.dart +++ b/lib/widgets/rooms/room_summary_sheet.dart @@ -141,7 +141,7 @@ class const RoomSummarySheet( ListTile( leading: AvatarOrHash( summary.inviterProfile?.avatarUrl, - summary.inviterProfile?.displayName ?? invitedBy.localpart!, + summary.inviterProfile?.displayName ?? invitedBy.localpart, ), title: Text( "${summary.isDirect ? "Direct message from" : "Invited by"} ${summary.inviterProfile?.displayName ?? invitedBy.localpart}", diff --git a/lib/widgets/rooms/share_sheet.dart b/lib/widgets/rooms/share_sheet.dart deleted file mode 100644 index d448194..0000000 --- a/lib/widgets/rooms/share_sheet.dart +++ /dev/null @@ -1,127 +0,0 @@ -import "package:better_share_handler/better_share_handler.dart"; -import "package:collection/collection.dart"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; -import "package:file_selector/file_selector.dart"; -import "package:flutter_hooks/flutter_hooks.dart"; -import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:material_ui/material_ui.dart"; -import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; -import "package:nexus/controllers/attachment.dart"; -import "package:nexus/controllers/composer_draft.dart"; -import "package:nexus/controllers/sidebar_page.dart"; -import "package:nexus/controllers/spaces.dart"; -import "package:nexus/helpers/extensions/focus_room.dart"; -import "package:nexus/helpers/extensions/get_all_child_rooms.dart"; -import "package:nexus/helpers/extensions/weighted_search.dart"; -import "package:nexus/main.dart"; -import "package:nexus/models/composer_params.dart"; -import "package:nexus/widgets/avatars/avatar_or_hash.dart"; - -class const ShareSheet(final SharedMedia media, {super.key}) - extends HookConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final controller = useTextEditingController(); - final query = useValueListenable(controller).text; - final spaces = ref.watch(SpacesController.provider).value ?? const .empty(); - - final rooms = - IMap.fromEntries( - spaces - .expand((space) => space.allChildRooms) - .map((room) => room.metadata) - .nonNulls - .map((room) => MapEntry(room.id, room)), - ).values - .sortedBy((room) => room.sortingTimestamp) - .reversed - .search( - query, - (room) => [(room.name, 2), (room.canonicalAlias, 1)], - ); - - final text = media.content ?? ""; - // The composer takes one attachment - final file = media.attachments?.nonNulls.firstOrNull; - - Future shareTo(String roomId) async { - final container = ProviderScope.containerOf(context); - Navigator.of(context).popUntil((route) => route.isFirst); - await container.focusRoom(roomId); - container.read(SidebarPageController.provider.notifier).set(.rooms); - - final ComposerParams composer = (roomId: roomId, threadRoot: null); - final draftProvider = ComposerDraftController.provider(composer); - // Shares go in a new message, not an edit - if (container.read(draftProvider).isEditing) { - container.read(draftProvider.notifier).dismiss(); - } - - if (text.isNotEmpty) { - container - .read(draftProvider.notifier) - .update( - (draft) => draft.copyWith( - text: draft.text.isEmpty ? text : "${draft.text}\n$text", - textReplacements: draft.textReplacements + 1, - ), - ); - } - - if (file != null) { - await container - .read( - AttachmentController.provider(( - composer: composer, - editingRowId: null, - )).notifier, - ) - .add(XFile(file.path)); - } - } - - return SheetLayout( - title: Text(switch ((file, text.isNotEmpty)) { - (_?, _) => "Share File", - (null, true) => "Share Text", - (null, false) => "Share", - }), - actions: [ - TextButton(onPressed: Navigator.of(context).pop, child: Text("Cancel")), - ], - children: [ - TextField( - controller: controller, - autofocus: true, - decoration: .new( - hintText: "Search rooms", - prefixIcon: Icon(Icons.search), - ), - ), - if (rooms.isEmpty) - Text("No rooms found") - else - Column( - children: rooms - .map( - (room) => ListTile( - leading: AvatarOrHash( - room.avatar, - room.name ?? "Unnamed Room", - fallback: room.dmUserId == null - ? Icon(Icons.numbers) - : null, - ), - title: Text( - room.name ?? "Unnamed Room", - overflow: .ellipsis, - ), - onTap: () => shareTo(room.id).onError(showError), - ), - ) - .toList(), - ), - ], - ); - } -} diff --git a/lib/widgets/settings/local_aliases_sheet.dart b/lib/widgets/settings/local_aliases_sheet.dart index 184238b..b51b7c3 100644 --- a/lib/widgets/settings/local_aliases_sheet.dart +++ b/lib/widgets/settings/local_aliases_sheet.dart @@ -5,7 +5,6 @@ import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/controllers/local_aliases.dart"; import "package:nexus/helpers/extensions/better_when.dart"; -import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/hooks/saving.dart"; import "package:nexus/main.dart"; import "package:nexus/models/gomuks_exception.dart"; @@ -25,7 +24,7 @@ class const LocalAliasesSheet( final localpart = useValueListenable(controller).text.trim(); final server = ref.watch( ClientStateController.provider.select( - (state) => state?.userId?.serverName, + (state) => state?.userId?.split(":").skip(1).join(":"), ), ); diff --git a/lib/widgets/settings/member_chooser.dart b/lib/widgets/settings/member_chooser.dart index 9845892..fbaaa8e 100644 --- a/lib/widgets/settings/member_chooser.dart +++ b/lib/widgets/settings/member_chooser.dart @@ -46,7 +46,7 @@ class const MemberChooser({ .nonNulls, ); - String nameOf(String id) => members[id]?.displayName ?? id.localpart!; + String nameOf(String id) => members[id]?.displayName ?? id.localpart; void add(String id) { if (excluded.contains(id)) { diff --git a/lib/widgets/settings/subprofile_sheet.dart b/lib/widgets/settings/subprofile_sheet.dart deleted file mode 100644 index fbfadcd..0000000 --- a/lib/widgets/settings/subprofile_sheet.dart +++ /dev/null @@ -1,140 +0,0 @@ -import "package:flutter_hooks/flutter_hooks.dart"; -import "package:hooks_riverpod/hooks_riverpod.dart"; -import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; -import "package:material_ui/material_ui.dart"; -import "package:nexus/controllers/account_data.dart"; -import "package:nexus/helpers/hooks/saving.dart"; -import "package:nexus/main.dart"; -import "package:nexus/models/per_message_profiles.dart"; -import "package:nexus/widgets/avatars/avatar_or_hash.dart"; -import "package:nexus/widgets/avatars/editable_avatar.dart"; - -class const SubprofileSheet({final StoredProfile? subprofile, super.key}) - extends HookConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final saving = Saving.use(); - final trigger = subprofile?.triggers.firstOrNull; - final nameController = useTextEditingController( - text: subprofile?.displayName, - ); - final prefixController = useTextEditingController(text: trigger?.prefix); - final suffixController = useTextEditingController(text: trigger?.suffix); - final avatar = useState(subprofile?.avatarUrl); - final name = useValueListenable(nameController).text.trim(); - - final accountData = ref.read(AccountDataController.provider.notifier); - PerMessageProfiles current() => - ref.read(AccountDataController.provider).perMessageProfiles; - - Future update(PerMessageProfiles profiles) async { - await saving.run(() => accountData.setPerMessageProfiles(profiles)); - if (context.mounted) Navigator.of(context).pop(); - } - - Future save() { - final prefix = prefixController.text; - final suffix = suffixController.text; - final edited = StoredProfile( - id: - subprofile?.id ?? - DateTime.now().microsecondsSinceEpoch.toRadixString(36), - displayName: name, - avatarUrl: avatar.value, - triggers: .new([ - if (prefix.isNotEmpty || suffix.isNotEmpty) - (trigger ?? const .new()).copyWith(prefix: prefix, suffix: suffix), - ...?subprofile?.triggers.skip(1), - ]), - ); - final profiles = current(); - - return update( - profiles.copyWith( - profiles: subprofile == null - ? profiles.profiles.add(edited) - : profiles.profiles.replaceFirstWhere( - (profile) => profile.id == subprofile!.id, - (_) => edited, - ), - ), - ).onError(showError); - } - - Future delete() { - final profiles = current(); - return update( - profiles.copyWith( - profiles: profiles.profiles.removeWhere( - (profile) => profile.id == subprofile!.id, - ), - defaultProfileId: profiles.defaultProfileId == subprofile!.id - ? null - : profiles.defaultProfileId, - ), - ).onError(showError); - } - - return SheetLayout( - title: Text(subprofile == null ? "Add Subprofile" : "Edit Subprofile"), - actions: [ - if (subprofile != null) - TextButton( - onPressed: saving.active ? null : delete, - style: TextButton.styleFrom( - foregroundColor: Theme.of(context).colorScheme.error, - ), - child: Text("Delete"), - ), - TextButton(onPressed: Navigator.of(context).pop, child: Text("Cancel")), - TextButton( - onPressed: name.isEmpty || saving.active ? null : save, - child: Text("Save"), - ), - ], - children: [ - Center( - child: EditableAvatar( - dimension: 120, - hasAvatar: avatar.value != null, - onChanged: (url) async => avatar.value = url, - child: AvatarOrHash( - avatar.value, - name.isEmpty ? "Subprofile" : name, - dimension: 120, - ), - ), - ), - TextField( - controller: nameController, - autofocus: subprofile == null, - textCapitalization: .words, - decoration: const .new(labelText: "Display name"), - ), - Text( - "Optionally, messages that start with the prefix *and* end with the suffix are sent as this subprofile, without them. Leave one empty to only need the other. Both are case-sensitive.", - ), - Row( - spacing: 8, - children: [ - Expanded( - child: TextField( - controller: prefixController, - decoration: const .new( - labelText: "Prefix", - hintText: "e.g. k:", - ), - ), - ), - Expanded( - child: TextField( - controller: suffixController, - decoration: const .new(labelText: "Suffix"), - ), - ), - ], - ), - ], - ); - } -} diff --git a/lib/widgets/sidebar/rooms_pane.dart b/lib/widgets/sidebar/rooms_pane.dart index 1540f11..aabebbb 100644 --- a/lib/widgets/sidebar/rooms_pane.dart +++ b/lib/widgets/sidebar/rooms_pane.dart @@ -94,48 +94,38 @@ class const RoomsPane({super.key}) extends ConsumerWidget { ), ], ), - ...selectedSpace.subSpaces - .map( - (subSpace) => NavigationRailM3ESection( - header: DividerWidget( - Row( - mainAxisSize: .min, - spacing: 8, - children: [ - if (subSpace.room.metadata?.avatar != null) - AvatarOrHash( - subSpace.room.metadata?.avatar, - subSpace.room.metadata?.name ?? "Unnamed Room", - dimension: 16, - ), - Flexible( - child: Text( - subSpace.room.metadata?.name ?? "Unnamed Space", - maxLines: 1, - overflow: .ellipsis, - ), - ), - ], + .new( + header: selectedSpace.room == null + ? null + : const DividerWidget(Text("Rooms")), + destinations: selectedSpace.children.toDestinations(isDm: isDm), + ), + ...selectedSpace.subSpaces.map( + (subSpace) => NavigationRailM3ESection( + header: DividerWidget( + Row( + mainAxisSize: .min, + spacing: 8, + children: [ + if (subSpace.room.metadata?.avatar != null) + AvatarOrHash( + subSpace.room.metadata?.avatar, + subSpace.room.metadata?.name ?? "Unnamed Room", + dimension: 16, + ), + Flexible( + child: Text( + subSpace.room.metadata?.name ?? "Unnamed Space", + maxLines: 1, + overflow: .ellipsis, + ), ), - ), - destinations: subSpace.children.toDestinations( - isDm: isDm, - ), + ], ), - ) - .toIList() - // Sorted among the subspaces, matching allChildRooms - .insertAll(selectedSpace.childrenIndex, [ - if (selectedSpace.children.isNotEmpty) - NavigationRailM3ESection( - header: selectedSpace.room == null - ? null - : const DividerWidget(Text("Rooms")), - destinations: selectedSpace.children.toDestinations( - isDm: isDm, - ), - ), - ]), + ), + destinations: subSpace.children.toDestinations(isDm: isDm), + ), + ), ], onDestinationSelected: (value) { ref diff --git a/lib/widgets/sidebar/spaces_rail.dart b/lib/widgets/sidebar/spaces_rail.dart index 5dda4a4..d84a40a 100644 --- a/lib/widgets/sidebar/spaces_rail.dart +++ b/lib/widgets/sidebar/spaces_rail.dart @@ -44,7 +44,7 @@ class const SpacesRail({super.key}) extends ConsumerWidget { .set(spaces[value].id); ref .read(KeyController.provider(KeyController.roomKey).notifier) - .set(spaces[value].allChildRooms.firstOrNull?.metadata?.id); + .set(spaces[value].children.firstOrNull?.metadata?.id); }, sections: [ .new( diff --git a/lib/widgets/users/room_profile_sheet.dart b/lib/widgets/users/room_profile_sheet.dart deleted file mode 100644 index 68390a5..0000000 --- a/lib/widgets/users/room_profile_sheet.dart +++ /dev/null @@ -1,77 +0,0 @@ -import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:material_ui/material_ui.dart"; -import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; -import "package:nexus/controllers/client_state.dart"; -import "package:nexus/controllers/room_profile.dart"; -import "package:nexus/helpers/extensions/better_when.dart"; -import "package:nexus/helpers/extensions/get_localpart.dart"; -import "package:nexus/main.dart"; -import "package:nexus/models/profile_response.dart"; -import "package:nexus/widgets/avatars/avatar_or_hash.dart"; -import "package:nexus/widgets/avatars/editable_avatar.dart"; -import "package:nexus/widgets/settings/inline_text_field.dart"; - -/// Edits the avatar and display name the current user has in [roomId]. -class const RoomProfileSheet(final String roomId, {super.key}) - extends ConsumerWidget { - @override - Widget build(BuildContext context, WidgetRef ref) { - final userId = ref.watch(ClientStateController.provider)?.userId ?? ""; - final controller = ref.read( - RoomProfileController.provider(roomId).notifier, - ); - Future setField(String field, Object? value) => - controller.setFields(.new({field: value})).onError(showError); - - return SheetLayout( - title: Text("Room Profile"), - actions: [ - TextButton( - onPressed: () => controller.reset().onError(showError), - child: Text("Use Global Profile"), - ), - TextButton(onPressed: Navigator.of(context).pop, child: Text("Done")), - ], - children: [ - Text( - "Your avatar and display name in this room only. Changing your global profile may replace them.", - ), - ref - .watch(RoomProfileController.provider(roomId)) - .betterWhen( - skipLoadingOnReload: true, - data: (member) { - final name = member?.displayName ?? userId.localpart ?? userId; - - return Column( - spacing: 8, - children: [ - EditableAvatar( - hasAvatar: member?.avatarUrl != null, - onChanged: (url) => - setField(Profile.avatarUrlKey, url?.toString()), - child: AvatarOrHash( - member?.avatarUrl, - name, - dimension: 200, - ), - ), - InlineTextField( - value: member?.displayName, - hint: userId.localpart ?? userId, - style: Theme.of(context).textTheme.headlineLarge, - onChanged: member == null - ? null - : (value) => setField( - Profile.displayNameKey, - value.isEmpty ? null : value, - ), - ), - ], - ); - }, - ), - ], - ); - } -} diff --git a/lib/widgets/users/user_bottom_sheet.dart b/lib/widgets/users/user_bottom_sheet.dart index b9bccff..12e0e24 100644 --- a/lib/widgets/users/user_bottom_sheet.dart +++ b/lib/widgets/users/user_bottom_sheet.dart @@ -76,7 +76,7 @@ final class const UserBottomSheet( downloadFilename: member.displayName ?? userId.localpart, child: AvatarOrHash( member.avatarUrl, - member.displayName ?? userId.localpart!, + member.displayName ?? userId.localpart, dimension: 200, ), ); @@ -231,7 +231,7 @@ final class const UserBottomSheet( if (editable) InlineTextField( value: profile?.displayName, - hint: userId.localpart!, + hint: userId.localpart, style: textTheme.headlineLarge, onChanged: profile == null ? null @@ -240,7 +240,7 @@ final class const UserBottomSheet( ) else SelectableText( - member.displayName ?? userId.localpart!, + member.displayName ?? userId.localpart, style: textTheme.headlineLarge, textAlign: .center, ), @@ -404,7 +404,7 @@ final class const UserBottomSheet( if (hasDm) { context.startDirectMessage( userId, - name: name!, + name: name, ); } else if (await context .showAdaptiveSheet( diff --git a/lib/widgets/users/user_span.dart b/lib/widgets/users/user_span.dart index 0371fcc..d8a305c 100644 --- a/lib/widgets/users/user_span.dart +++ b/lib/widgets/users/user_span.dart @@ -3,12 +3,15 @@ import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:material_ui/material_ui.dart"; import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; import "package:nexus/controllers/author.dart"; -import "package:nexus/controllers/user.dart"; import "package:nexus/helpers/extensions/displayname_color.dart"; import "package:nexus/helpers/extensions/get_localpart.dart"; import "package:nexus/helpers/extensions/show_user_popover.dart"; import "package:nexus/models/event.dart"; +/// A user's [name] in text, opening their popover when tapped. Unlike a widget +/// in text, it wraps and ellipsizes with the rest of it. + +// Can't be const, since it sets the recognizer's onTapUp // ignore: prefer_const_constructors_in_immutables class UserSpan( BuildContext context, @@ -44,11 +47,8 @@ class UserSpan( return UserSpan( context, - ref - .watch(AuthorController.provider(.fromEvent(event))) - .value - ?.displayName ?? - event.sender.localpart!, + ref.watch(AuthorController.provider(.fromEvent(event))).value?.displayName ?? + event.sender.localpart, userId: event.sender, roomId: event.roomId, recognizer: recognizer, @@ -56,8 +56,7 @@ class UserSpan( children: [ if (event.pmp != null) TextSpan( - text: - "(${ref.watch(UserController.provider(.new(roomId: event.roomId, userId: event.sender))).value?.displayName ?? event.sender.localpart})", + text: " (via ${event.sender})", recognizer: recognizer, style: Theme.of(context).textTheme.labelSmall ?.copyWith(color: color, fontWeight: .bold), diff --git a/linux/nix/default.nix b/linux/nix/default.nix index aa8e46d..8f09dbc 100644 --- a/linux/nix/default.nix +++ b/linux/nix/default.nix @@ -18,34 +18,10 @@ packages = let - unpatched = pkgs.callPackage ./pkg { + default = pkgs.callPackage ./pkg { src = self; commit = self.shortRev or self.dirtyShortRev; }; - - # Without this, GTK3 can't create a GL context on Mesa builds without GLES 1 - # (Flathub's since 26.2.8). Drop once nixpkgs has a GTK3 release with it. - # Swapped into the finished closure, as an overlay would rebuild half of nixpkgs - withPatchedGtk = - drv: - pkgs.replaceDependencies { - inherit drv; - replacements = [ - { - oldDependency = pkgs.gtk3; - newDependency = pkgs.gtk3.overrideAttrs (old: { - patches = old.patches or [ ] ++ [ ./patches/gtk3-egl-renderable-type.patch ]; - # So the flatpak gets text-input-v3 (and with it the OSK) without our immodules.cache - mesonFlags = old.mesonFlags or [ ] ++ [ "-Dbuiltin_immodules=wayland" ]; - }); - } - ]; - } - // { - inherit (drv) pname version meta; - }; - - default = withPatchedGtk unpatched; in { inherit default; @@ -56,33 +32,13 @@ appId = "nexus.federated.nexus"; # The runtime's GStreamer gets loaded instead of ours, and it can't # load our plugins, so keep wrapGAppsHook from pointing it at them - package = withPatchedGtk ( - unpatched.overrideAttrs (old: { - postInstall = '' - unset GST_PLUGIN_SYSTEM_PATH_1_0 - '' - + old.postInstall; - # Our GTK's default immodules.cache path isn't in the flatpak; use the runtime's - preFixup = old.preFixup or "" + '' - gappsWrapperArgs+=(--set-default GTK_IM_MODULE_FILE /usr/lib/${pkgs.stdenv.hostPlatform.uname.processor}-linux-gnu/gtk-3.0/3.0.0/immodules.cache) - ''; - # nix2flatpak swaps dropped RUNPATH entries for the runtime's libdir in place, - # which would put it ahead of our patched GTK, so move GTK to the front - postFixup = old.postFixup or "" + '' - bin=$out/app/nexus/nexus - ${lib.getExe pkgs.patchelf} --set-rpath \ - "${lib.getLib pkgs.gtk3}/lib:$(${lib.getExe pkgs.patchelf} --print-rpath $bin)" $bin - ''; - }) - ); + package = default.overrideAttrs (old: { + postInstall = '' + unset GST_PLUGIN_SYSTEM_PATH_1_0 + '' + + old.postInstall; + }); runtime = "org.gnome.Platform/51"; - # Hide the runtime's GTK3 from nix2flatpak, so it bundles our patched one - runtimeIndex = - pkgs.runCommand "runtime-index.json" { nativeBuildInputs = [ pkgs.jq ]; } - '' - jq 'del(.sonames["libgtk-3.so.0", "libgdk-3.so.0", "libgailutil-3.so.0"])' \ - ${inputs.nix2flatpak}/runtimes/org.gnome.Platform/51/runtime-index.json > $out - ''; permissions = { share = [ "network" ]; sockets = [ diff --git a/linux/nix/patches/gtk3-egl-renderable-type.patch b/linux/nix/patches/gtk3-egl-renderable-type.patch deleted file mode 100644 index 6711e39..0000000 --- a/linux/nix/patches/gtk3-egl-renderable-type.patch +++ /dev/null @@ -1,60 +0,0 @@ -From 386e7cb0ad85660cde7124ebd5b70d6f948e311f Mon Sep 17 00:00:00 2001 -From: YummierGravy <48499148+YummierGravy@users.noreply.github.com> -Date: Fri, 20 Nov 2026 00:20:31 +0100 -Subject: [PATCH] wayland: Set EGL_RENDERABLE_TYPE when choosing an EGLConfig - -eglChooseConfig() defaults EGL_RENDERABLE_TYPE to EGL_OPENGL_ES_BIT -(OpenGL ES 1.x), which GDK never uses. Since Mesa 26.3, builds without -GLES 1 support no longer set that bit on their configs, so no config -matches and creating a GL context fails - -Part-of: ---- - gdk/wayland/gdkglcontext-wayland.c | 10 +++++++++- - 1 file changed, 9 insertions(+), 1 deletion(-) - -diff --git a/gdk/wayland/gdkglcontext-wayland.c b/gdk/wayland/gdkglcontext-wayland.c -index d73e6e68d71..622b43ed1fb 100644 ---- a/gdk/wayland/gdkglcontext-wayland.c -+++ b/gdk/wayland/gdkglcontext-wayland.c -@@ -372,6 +372,7 @@ gdk_wayland_display_init_gl (GdkDisplay *display, - - static gboolean - find_eglconfig_for_window (GdkWindow *window, -+ gboolean use_es, - EGLConfig *egl_config_out, - EGLint *min_swap_interval_out, - GError **error) -@@ -389,6 +390,9 @@ find_eglconfig_for_window (GdkWindow *window, - attrs[i++] = EGL_SURFACE_TYPE; - attrs[i++] = EGL_WINDOW_BIT; - -+ attrs[i++] = EGL_RENDERABLE_TYPE; -+ attrs[i++] = use_es ? EGL_OPENGL_ES2_BIT : EGL_OPENGL_BIT; -+ - attrs[i++] = EGL_COLOR_BUFFER_TYPE; - attrs[i++] = EGL_RGB_BUFFER; - -@@ -464,6 +468,7 @@ gdk_wayland_window_create_gl_context (GdkWindow *window, - GdkWaylandDisplay *display_wayland = GDK_WAYLAND_DISPLAY (display); - GdkWaylandGLContext *context; - EGLConfig config; -+ gboolean use_es; - - if (!gdk_wayland_display_init_gl (display, share)) - { -@@ -481,7 +486,10 @@ gdk_wayland_window_create_gl_context (GdkWindow *window, - return NULL; - } - -- if (!find_eglconfig_for_window (window, &config, -+ use_es = (_gdk_gl_flags & GDK_GL_GLES) != 0 || -+ (share != NULL && gdk_gl_context_get_use_es (share)); -+ -+ if (!find_eglconfig_for_window (window, use_es, &config, - &display_wayland->egl_min_swap_interval, - error)) - return NULL; --- -GitLab - diff --git a/linux/nix/pkg/default.nix b/linux/nix/pkg/default.nix index d9545c5..3fbe98f 100644 --- a/linux/nix/pkg/default.nix +++ b/linux/nix/pkg/default.nix @@ -28,7 +28,6 @@ flutter347.buildFlutterApplication { inherit src; preBuild = '' - export PATH=${callPackage ./hook_pkg_config.nix { }}/bin:$PATH cp ${callPackage ./gomuks.nix { inherit src; }}/lib/* . packageRunCustom nexus generate source/scripts test packageRun build_runner build @@ -38,6 +37,8 @@ flutter347.buildFlutterApplication { "--dart-define=GIT_COMMIT=${commit}" ]; + nativeBuildInputs = [ (callPackage ./hook_pkg_config.nix { }) ]; + buildInputs = [ # audioplayers plays audio through GStreamer, and wrapGAppsHook adds # these plugins to the wrapper's GST_PLUGIN_SYSTEM_PATH_1_0 @@ -60,7 +61,7 @@ flutter347.buildFlutterApplication { linkify = "sha256-TpMD6+0zyY6i9l+6d8ErnVufmepCv362rCtnbOht/z4="; location = "sha256-RL+l46pBhv75xP7ASJuazyYoi9vI35TSYAV11mkjAwY="; fab_m3e = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI="; - fluttertagger = "sha256-AYsV0qjFgnlQxGiRBYJ2xrfHNnKKh5OhvzPT7bdm5Yw="; + fluttertagger = "sha256-tHUNU2+fBPkq5UK5YRi3SWs1zF2PIPz6RgSbwignU/I="; m3e_design = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI="; navigation_rail_m3e = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI="; unifiedpush_linux = "sha256-KQKyBPL2ORK9O89C4K3RHGve/lvFaU1vIjSDnj6+bj4="; diff --git a/pubspec.lock b/pubspec.lock index 7b445a7..644480c 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -225,14 +225,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.5.1" - better_share_handler: - dependency: "direct main" - description: - name: better_share_handler - sha256: "20af88c551b5c76fdaadb053a8cffe2cc0d5da56c8e7b847642a512c4f6ae293" - url: "https://pub.dev" - source: hosted - version: "1.1.1" boolean_selector: dependency: transitive description: @@ -744,7 +736,7 @@ packages: description: path: "." ref: HEAD - resolved-ref: a631052fd7e36e20f605099df6831e17ae80568b + resolved-ref: "78a5099499728917e7595f738f3b369b47804dc5" url: "https://github.com/Henry-Hiles/fluttertagger" source: git version: "2.3.2" diff --git a/pubspec.yaml b/pubspec.yaml index 3407eae..daf702e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -120,7 +120,6 @@ dependencies: path: packages/location better_player: 1.38.0 audioplayers: 6.8.1 - better_share_handler: 1.1.1 dev_dependencies: flutter_test: sdk: flutter