diff --git a/.vscode/settings.json b/.vscode/settings.json
index 2d6d7e3..29d0986 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -15,6 +15,8 @@
"underride",
"unifiedpush",
"unredact",
- "webpush"
+ "webpush",
+ "subprofile",
+ "subprofiles"
]
}
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 7638ad6..cfba062 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -47,6 +47,12 @@
+
+
+
+
+
+
main(List args) => build(args, (input, output) async {
libFileName = "libgomuks.dylib";
final iosConfig = codeConfig.iOS;
iosSdk = iosConfig.targetSdk;
- final minVersion = iosConfig.targetVersion;
+ final minVersion = iosConfig.deploymentVersion.major;
iosSdkPath = await getXCodeTool(sdkType: iosSdk.type);
final archTriple = switch (targetArch) {
@@ -53,7 +53,8 @@ Future main(List args) => build(args, (input, output) async {
libFileName = "libgomuks.dylib";
extraEnv = {
"SDKROOT": await getXCodeTool(),
- "MACOSX_DEPLOYMENT_TARGET": codeConfig.macOS.targetVersion.toString(),
+ "MACOSX_DEPLOYMENT_TARGET": codeConfig.macOS.deploymentVersion.major
+ .toString(),
};
break;
case OS.windows:
diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj
index 1612bb0..0fe5f5c 100644
--- a/ios/Runner.xcodeproj/project.pbxproj
+++ b/ios/Runner.xcodeproj/project.pbxproj
@@ -16,6 +16,10 @@
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 */
@@ -26,6 +30,13 @@
remoteGlobalIDString = 97C146ED1CF9000F007C117D;
remoteInfo = Runner;
};
+ 5A4E00000000000000000012 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = 97C146E61CF9000F007C117D /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = 5A4E0000000000000000000D;
+ remoteInfo = ShareExtension;
+ };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -39,6 +50,17 @@
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 */
@@ -59,6 +81,12 @@
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 */
@@ -77,6 +105,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ 5A4E0000000000000000000F /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 5A4E0000000000000000000B /* better-share-handler-models in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -107,6 +143,7 @@
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
331C8082294A63A400263BE5 /* RunnerTests */,
+ 5A4E0000000000000000000C /* ShareExtension */,
);
sourceTree = "";
};
@@ -115,6 +152,7 @@
children = (
97C146EE1CF9000F007C117D /* Runner.app */,
331C8081294A63A400263BE5 /* RunnerTests.xctest */,
+ 5A4E00000000000000000005 /* ShareExtension.appex */,
);
name = Products;
sourceTree = "";
@@ -131,10 +169,22 @@
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 */
@@ -165,11 +215,13 @@
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
+ 5A4E00000000000000000011 /* Embed App Extensions */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
);
buildRules = (
);
dependencies = (
+ 5A4E00000000000000000013 /* PBXTargetDependency */,
);
name = Runner;
packageProductDependencies = (
@@ -179,6 +231,26 @@
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 */
@@ -197,6 +269,9 @@
CreatedOnToolsVersion = 7.3.1;
LastSwiftMigration = 1100;
};
+ 5A4E0000000000000000000D = {
+ CreatedOnToolsVersion = 15.0;
+ };
};
};
buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
@@ -210,6 +285,7 @@
mainGroup = 97C146E51CF9000F007C117D;
packageReferences = (
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */,
+ 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "better_share_handler" */,
);
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
projectDirPath = "";
@@ -217,6 +293,7 @@
targets = (
97C146ED1CF9000F007C117D /* Runner */,
331C8080294A63A400263BE5 /* RunnerTests */,
+ 5A4E0000000000000000000D /* ShareExtension */,
);
};
/* End PBXProject section */
@@ -240,6 +317,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ 5A4E00000000000000000010 /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 5A4E00000000000000000009 /* MainInterface.storyboard in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
@@ -295,6 +380,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ 5A4E0000000000000000000E /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 5A4E00000000000000000008 /* ShareViewController.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
@@ -303,6 +396,11 @@
target = 97C146ED1CF9000F007C117D /* Runner */;
targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */;
};
+ 5A4E00000000000000000013 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = 5A4E0000000000000000000D /* ShareExtension */;
+ targetProxy = 5A4E00000000000000000012 /* PBXContainerItemProxy */;
+ };
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
@@ -322,6 +420,14 @@
name = LaunchScreen.storyboard;
sourceTree = "";
};
+ 5A4E00000000000000000007 /* MainInterface.storyboard */ = {
+ isa = PBXVariantGroup;
+ children = (
+ 5A4E00000000000000000002 /* Base */,
+ );
+ name = MainInterface.storyboard;
+ sourceTree = "";
+ };
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
@@ -368,7 +474,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
- IPHONEOS_DEPLOYMENT_TARGET = 13.0;
+ IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
@@ -386,6 +492,7 @@
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)",
@@ -495,7 +602,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
- IPHONEOS_DEPLOYMENT_TARGET = 13.0;
+ IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -546,7 +653,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
- IPHONEOS_DEPLOYMENT_TARGET = 13.0;
+ IPHONEOS_DEPLOYMENT_TARGET = 14.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
@@ -566,6 +673,7 @@
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)",
@@ -589,6 +697,7 @@
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,6 +711,87 @@
};
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 */
@@ -635,6 +825,16 @@
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 */
@@ -642,6 +842,10 @@
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 */
@@ -649,6 +853,11 @@
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 7deed9e..a26f7b5 100644
--- a/ios/Runner/Info.plist
+++ b/ios/Runner/Info.plist
@@ -31,6 +31,15 @@
matrix
+
+
+ CFBundleTypeRole
+ Editor
+ CFBundleURLSchemes
+
+ ShareMedia-$(PRODUCT_BUNDLE_IDENTIFIER)
+
+
CFBundleVersion
$(FLUTTER_BUILD_NUMBER)
diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements
new file mode 100644
index 0000000..23cb05e
--- /dev/null
+++ b/ios/Runner/Runner.entitlements
@@ -0,0 +1,10 @@
+
+
+
+
+ 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
new file mode 100644
index 0000000..286a508
--- /dev/null
+++ b/ios/ShareExtension/Base.lproj/MainInterface.storyboard
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ios/ShareExtension/Info.plist b/ios/ShareExtension/Info.plist
new file mode 100644
index 0000000..76d4a29
--- /dev/null
+++ b/ios/ShareExtension/Info.plist
@@ -0,0 +1,41 @@
+
+
+
+
+ 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
new file mode 100644
index 0000000..23cb05e
--- /dev/null
+++ b/ios/ShareExtension/ShareExtension.entitlements
@@ -0,0 +1,10 @@
+
+
+
+
+ com.apple.security.application-groups
+
+ group.nexus.federated.nexus
+
+
+
diff --git a/ios/ShareExtension/ShareViewController.swift b/ios/ShareExtension/ShareViewController.swift
new file mode 100644
index 0000000..76f4931
--- /dev/null
+++ b/ios/ShareExtension/ShareViewController.swift
@@ -0,0 +1,5 @@
+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 62997b5..debad12 100644
--- a/lib/controllers/account_data.dart
+++ b/lib/controllers/account_data.dart
@@ -5,6 +5,9 @@ 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";
@@ -73,6 +76,45 @@ 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
new file mode 100644
index 0000000..172ff5a
--- /dev/null
+++ b/lib/controllers/account_management.dart
@@ -0,0 +1,24 @@
+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 04c2152..c97d07f 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 49dc414..887c874 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 3a1ac6c..b7b8ffd 100644
--- a/lib/controllers/client.dart
+++ b/lib/controllers/client.dart
@@ -36,6 +36,8 @@ 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";
@@ -280,24 +282,19 @@ class ClientController(final String? accountId) extends AsyncNotifier {
Future resetEncryption(RecoveryKey key) =>
sendCommand("reset_encryption", key.toJson());
- 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 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 joinRoom(JoinRoomRequest request) async =>
(await sendCommand("join_room", request.toJson()))["room_id"];
@@ -336,15 +333,50 @@ 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 sendCommand("get_specific_room_state", request.toJson()))
- as List? ??
- [])
- .map((event) => .fromJson(event)),
+ (await getSpecificRoomStateJson(request)).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 {
@@ -414,17 +446,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 25ed273..65eb3cb 100644
--- a/lib/controllers/composer_draft.dart
+++ b/lib/controllers/composer_draft.dart
@@ -1,8 +1,11 @@
+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";
@@ -49,8 +52,10 @@ class ComposerDraftController(final ComposerParams composer)
},
);
+ final tagged = _restoreTags(text);
state = ComposerDraft(
- text: text,
+ text: tagged.text,
+ tags: tagged.tags,
textCommands: commands,
relatedEvent: rowId,
relationType: .edit,
@@ -76,6 +81,52 @@ 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
new file mode 100644
index 0000000..b4303b8
--- /dev/null
+++ b/lib/controllers/launch_scope.dart
@@ -0,0 +1,10 @@
+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 e8a5dff..618d849 100644
--- a/lib/controllers/notification.dart
+++ b/lib/controllers/notification.dart
@@ -2,11 +2,15 @@ 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";
@@ -26,7 +30,17 @@ class NotificationController
Future build() async {
final notifications = FlutterLocalNotificationsPlugin();
- if (!Platform.isLinux) {
+ if (Platform.isLinux) {
+ const MethodChannel("nexus/notifications")
+ .setMethodCallHandler((call) async {
+ if (call case MethodCall(
+ method: "notificationClicked",
+ arguments: final String payload,
+ )) {
+ _open(payload);
+ }
+ });
+ } else {
final darwin = DarwinInitializationSettings();
await notifications.initialize(
@@ -44,26 +58,89 @@ 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);
+ }
+ }
}
- if (Platform.isLinux) {
- const notificationChannel = MethodChannel("nexus/notifications");
+ // 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;
- notificationChannel.setMethodCallHandler((call) async {
- if (call.method != "notificationClicked") {
- return;
- }
-
- if (call.arguments case final String payload) _open(payload);
- });
+ final accountId = ref.read(ActiveAccountController.provider);
+ dismiss(
+ newlyRead.map((roomId) => threadIdFor(accountId, roomId)).toISet(),
+ ).onError(showError);
+ },
+ fireImmediately: true,
+ );
}
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
@@ -72,9 +149,6 @@ 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(
@@ -84,73 +158,50 @@ 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;
- 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;
+ 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;
}
/// Whether notifications can currently be shown, without prompting
Future permissionsGranted() async {
- if (Platform.isLinux) {
- return true;
- }
-
final controller = await future;
- 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;
+ return (await controller
+ .resolvePlatformSpecificImplementation<
+ IOSFlutterLocalNotificationsPlugin
+ >()
+ ?.checkPermissions())
+ ?.isEnabled ??
+ (await controller
+ .resolvePlatformSpecificImplementation<
+ MacOSFlutterLocalNotificationsPlugin
+ >()
+ ?.checkPermissions())
+ ?.isEnabled ??
+ await controller
+ .resolvePlatformSpecificImplementation<
+ AndroidFlutterLocalNotificationsPlugin
+ >()
+ ?.areNotificationsEnabled() ??
+ true;
}
/// Passing [message] shows it as a chat message in the conversation for
@@ -173,6 +224,7 @@ 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);
@@ -199,6 +251,7 @@ class NotificationController
// ),
],
);
+ if (threadId != null) await shown.add(threadId, id);
return;
}
@@ -214,6 +267,7 @@ class NotificationController
.onError((_, _) => null)
: null;
+ final largeIcon = icon == null ? null : FilePathAndroidBitmap(icon.path);
final darwin = DarwinNotificationDetails(
subtitle: subtitle,
presentSound: sound,
@@ -230,24 +284,24 @@ class NotificationController
? .new(
"general",
"General",
+ groupKey: _androidGroup,
subText: subtitle,
silent: !sound,
when: timestamp?.millisecondsSinceEpoch,
- largeIcon: icon == null
- ? null
- : FilePathAndroidBitmap(icon.path),
+ largeIcon: largeIcon,
styleInformation: BigTextStyleInformation(body),
)
: .new(
- "messages",
+ _messagesChannel,
"Messages",
+ importance: .high,
+ priority: .high,
+ groupKey: _androidGroup,
subText: subtitle,
silent: !sound,
when: timestamp?.millisecondsSinceEpoch,
category: .message,
- largeIcon: icon == null
- ? null
- : FilePathAndroidBitmap(icon.path),
+ largeIcon: largeIcon,
styleInformation: MessagingStyleInformation(
.new(key: message.self.id, name: message.self.name),
conversationTitle: message.isDm ? null : title,
@@ -260,11 +314,12 @@ class NotificationController
.new(
key: message.sender.id,
name: message.sender.name,
- icon: message.senderAvatar == null
- ? null
- : BitmapFilePathAndroidIcon(
- message.senderAvatar!.path,
- ),
+ icon: switch (message.senderAvatar) {
+ final avatar? => BitmapFilePathAndroidIcon(
+ avatar.path,
+ ),
+ null => null,
+ },
),
),
],
@@ -281,6 +336,28 @@ 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
new file mode 100644
index 0000000..1e7b9b0
--- /dev/null
+++ b/lib/controllers/pending_subprofiles.dart
@@ -0,0 +1,45 @@
+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 2a53a0d..e0a6765 100644
--- a/lib/controllers/room_chat.dart
+++ b/lib/controllers/room_chat.dart
@@ -7,6 +7,8 @@ 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";
@@ -399,6 +401,7 @@ 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
@@ -437,6 +440,7 @@ 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,
@@ -458,6 +462,24 @@ 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?) {
@@ -614,6 +636,7 @@ 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
new file mode 100644
index 0000000..e42129d
--- /dev/null
+++ b/lib/controllers/room_profile.dart
@@ -0,0 +1,101 @@
+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 66ffa3b..91d8093 100644
--- a/lib/controllers/rooms.dart
+++ b/lib/controllers/rooms.dart
@@ -189,6 +189,7 @@ 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 075fcdd..a48a340 100644
--- a/lib/controllers/selected_room.dart
+++ b/lib/controllers/selected_room.dart
@@ -22,9 +22,16 @@ class SelectedRoomController extends Notifier {
.addAll([?space.room?.metadata?.id]),
),
);
- if (roomIds == null) return roomId;
+ if (roomIds == null || roomIds.contains(roomId)) return roomId;
- return roomIds.contains(roomId) ? roomId : roomIds.firstOrNull;
+ final fallback = roomIds.firstOrNull;
+ Future.microtask(() {
+ if (!ref.mounted) return;
+ ref
+ .read(KeyController.provider(KeyController.roomKey).notifier)
+ .set(fallback);
+ });
+ return fallback;
}
static final provider = NotifierProvider(
diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart
index 999fea6..5121d6b 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,6 +24,7 @@ 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";
@@ -42,6 +43,7 @@ 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";
@@ -50,6 +52,40 @@ 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);
@@ -256,7 +292,7 @@ class SettingsSectionsController
),
.new(
title: "Room Ordering",
- description: "Sort rooms by recent activity, optionally showing mentioned and unread rooms first.",
+ description: "Sort rooms and subspaces by recent activity or the order their space sets, optionally showing mentioned and unread ones first.",
icon: Icons.sort,
builder: (title, description, icon) => DialogListTile(
icon: Icon(icon),
@@ -265,8 +301,11 @@ class SettingsSectionsController
value: settings.roomOrder,
options: RoomOrder.values,
getName: (option) => switch (option) {
- .unreadFirst => "Mentioned, then unread",
+ .unreadFirst => "Mentioned, then unread, then recent",
+ .unreadFirstSpaceOrder =>
+ "Mentioned, then unread, then space order",
.recentActivity => "Recent activity only",
+ .spaceOrder => "Space order only",
},
onChanged: (value) => ref
.read(SettingsController.provider.notifier)
@@ -339,17 +378,17 @@ class SettingsSectionsController
),
),
.new(
- title: "Hide Server ACL Events",
- description: "Hides server ACL (server ban list) changes from appearing in conversations.",
- icon: Icons.dns,
+ title: "Show Hidden Events",
+ description: "Shows events that are usually hidden, like reactions, edits, deletions and server ACL changes, in conversations.",
+ icon: Icons.visibility,
builder: (title, description, icon) => SwitchListTile(
title: Text(title),
subtitle: Text(description),
secondary: Icon(icon),
- value: settings.hideServerAclEvents,
+ value: settings.showHiddenEvents,
onChanged: (value) => ref
.read(SettingsController.provider.notifier)
- .set(settings.copyWith(hideServerAclEvents: value))
+ .set(settings.copyWith(showHiddenEvents: value))
.onError(showError),
),
),
@@ -408,6 +447,116 @@ 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,
@@ -756,7 +905,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(
@@ -790,24 +939,47 @@ class SettingsSectionsController
]),
),
.new(
- title: "Other",
- icon: Icons.key,
+ title: "Account Management",
+ icon: Icons.manage_accounts,
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) => M3EButton.icon(
- onPressed: () => context.showAdaptiveSheet(
+ builder: (context) => ListTile(
+ leading: Icon(icon),
+ title: Text(title),
+ subtitle: Text(description),
+ trailing: Icon(Icons.chevron_right),
+ onTap: () => 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
new file mode 100644
index 0000000..ce7a9ca
--- /dev/null
+++ b/lib/controllers/share_request.dart
@@ -0,0 +1,33 @@
+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 4d6dffe..07e1fd7 100644
--- a/lib/controllers/spaces.dart
+++ b/lib/controllers/spaces.dart
@@ -10,8 +10,11 @@ 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 {
@@ -20,9 +23,27 @@ 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) =>
- MapEntry(spaceId, edges.map((edge) => edge.childId).toList()),
+ (spaceId, edges) => .new(
+ spaceId,
+ edges.sort(compareEdges).map((edge) => edge.childId).toList(),
+ ),
);
/// Everything under [spaceId], however deep, skipping any already
@@ -60,6 +81,7 @@ class SpacesController extends AsyncNotifier> {
room: room,
children: .new(
collectDescendants(childId)
+ .where((id) => !childrenById.containsKey(id))
.map((id) => rooms[id])
.nonNulls,
),
@@ -69,6 +91,10 @@ class SpacesController extends AsyncNotifier> {
)
.nonNulls,
),
+ childrenIndex: directChildrenIds
+ .where(rooms.containsKey)
+ .takeWhile(childrenById.containsKey)
+ .length,
);
}
@@ -138,31 +164,67 @@ class SpacesController extends AsyncNotifier> {
SettingsController.provider.selectAsync((data) => data.roomOrder),
);
- // Mentioned -> Unread -> Other
- int unreadPriority(Room room) => switch (room.metadata) {
+ int priority(Room? room) => switch (room?.metadata) {
+ _ when !roomOrder.byUnread => 0,
RoomMetadata(unreadHighlights: > 0) => 0,
RoomMetadata(unreadNotifications: > 0) ||
RoomMetadata(unreadMessages: > 0) => 1,
_ => 2,
};
+ DateTime activity(Room room) => room.metadata?.sortingTimestamp ?? .new(0);
- 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;
- }
+ 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,
+ };
- // Most recent activity first
- return (b.metadata?.sortingTimestamp ?? DateTime(0)).compareTo(
- a.metadata?.sortingTimestamp ?? DateTime(0),
- );
- }),
+ _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),
+ ),
+ ),
),
- )
- .toIList();
+ childrenIndex: subSpaces
+ .where((entry) => compare(entry.key, childrenKey) < 0)
+ .length,
+ );
+ }),
+ );
}
static final provider = AsyncNotifierProvider>(
diff --git a/lib/controllers/subprofiles.dart b/lib/controllers/subprofiles.dart
new file mode 100644
index 0000000..21b1a0d
--- /dev/null
+++ b/lib/controllers/subprofiles.dart
@@ -0,0 +1,68 @@
+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 25675e2..d6f3777 100644
--- a/lib/controllers/unified_push.dart
+++ b/lib/controllers/unified_push.dart
@@ -121,18 +121,20 @@ class UnifiedPushController extends AsyncNotifier {
final icon = notification.roomAvatar == null
? null
- : await client.downloadMedia(
- .new(mxc: notification.roomAvatar!, isAvatar: true),
- );
+ : await client
+ .downloadMedia(.new(mxc: notification.roomAvatar!))
+ .then((file) => file)
+ .onError((_, _) => null);
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, isAvatar: true),
- );
+ : await client
+ .downloadMedia(.new(mxc: senderAvatarUrl))
+ .then((file) => file)
+ .onError((_, _) => null);
await ref
.read(NotificationController.provider.notifier)
@@ -143,7 +145,10 @@ class UnifiedPushController extends AsyncNotifier {
"$accountId/${Platform.isAndroid ? notification.roomId : notification.eventId}"
.hashCode &
0x7fffffff,
- threadId: "$accountId/${notification.roomId}",
+ threadId: NotificationController.threadIdFor(
+ accountId,
+ notification.roomId,
+ ),
title: notification.roomName,
subtitle: hasOtherAccounts ? notification.self.id : null,
body: notification.text,
@@ -220,7 +225,8 @@ class UnifiedPushController extends AsyncNotifier {
CapabilitiesController.provider.future,
);
- if (capabilities.webpush?.vapid == null) {
+ final vapid = capabilities.webPushVapid;
+ if (vapid == null) {
throw UnsupportedError(
"Your homeserver does not support MSC4174 (Web Push), and therefore cannot send notifications to Nexus.",
);
@@ -238,7 +244,7 @@ class UnifiedPushController extends AsyncNotifier {
await Future.wait([
UnifiedPush.register(
instance: deviceId,
- vapid: capabilities.webpush?.vapid,
+ vapid: vapid,
),
endpoint.future,
], eagerError: true);
diff --git a/lib/controllers/unified_push_allowed.dart b/lib/controllers/unified_push_allowed.dart
index 6dd1cf7..978f4ab 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.webpush?.vapid == null) {
+ if (capabilities.webPushVapid == 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 7a17eec..c2fbfaa 100644
--- a/lib/helpers/extensions/get_all_child_rooms.dart
+++ b/lib/helpers/extensions/get_all_child_rooms.dart
@@ -3,6 +3,10 @@ import "package:nexus/models/room.dart";
import "package:nexus/models/space.dart";
extension GetAllChildRooms on Space {
- IList get allChildRooms =>
- children.addAll(subSpaces.expand((s) => s.children));
+ IList get allChildRooms => subSpaces
+ .map((subspace) => subspace.children)
+ .toIList()
+ .insert(childrenIndex, children)
+ .expand((rooms) => rooms)
+ .toIList();
}
diff --git a/lib/helpers/extensions/get_localpart.dart b/lib/helpers/extensions/get_localpart.dart
index 200d2d0..d0ad620 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 : "?";
+ String? get localpart => length > 1 ? substring(1).split(":").first : null;
/// 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 9be95b8..366d1e2 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.
///
- /// If [downloadFilename] is set, a download button is shown, suggesting it.
+ /// The download button suggests [downloadFilename], falling back to the media ID.
void showImageViewer(
WidgetRef ref,
DownloadMediaRequest request, {
@@ -58,16 +58,15 @@ extension ShowImageViewer on BuildContext {
mainAxisSize: .min,
spacing: 8,
children: [
- if (downloadFilename != null)
- M3EButton(
- onPressed: () => context.saveAttachment(
- ref,
- request.mxc,
- encrypted: request.encrypted,
- filename: downloadFilename,
- ),
- child: Icon(Icons.download),
+ M3EButton(
+ onPressed: () => context.saveAttachment(
+ ref,
+ request.mxc,
+ encrypted: request.encrypted,
+ filename: downloadFilename,
),
+ 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
new file mode 100644
index 0000000..17d3975
--- /dev/null
+++ b/lib/helpers/shown_notifications_helper.dart
@@ -0,0 +1,52 @@
+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 51176cd..94149f3 100644
--- a/lib/models/account_data.dart
+++ b/lib/models/account_data.dart
@@ -1,5 +1,6 @@
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";
@@ -27,6 +28,8 @@ 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";
@@ -35,6 +38,7 @@ 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
new file mode 100644
index 0000000..8bc8d1c
--- /dev/null
+++ b/lib/models/account_management.dart
@@ -0,0 +1,19 @@
+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 cdf86b7..9224cf5 100644
--- a/lib/models/capabilities.dart
+++ b/lib/models/capabilities.dart
@@ -10,6 +10,14 @@ 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 ea72f30..44e34ab 100644
--- a/lib/models/composer_draft.dart
+++ b/lib/models/composer_draft.dart
@@ -24,6 +24,10 @@ 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 1467750..c9c88cd 100644
--- a/lib/models/event.dart
+++ b/lib/models/event.dart
@@ -65,14 +65,15 @@ class const Event({
}
}
- factory Event.fromJson(Map json) =>
- _$EventFromJson(json).copyWith(
+ factory Event.fromJson(Map json) => _$EventFromJson(json)
+ .copyWith(
replyTo: replyToFromJson(getContentFromJson(json)),
- pmp: json["content"]?["com.beeper.per_message_profile"] == null
- ? null
- : .fromJsonWithCatch(
- json["content"]?["com.beeper.per_message_profile"],
- ),
+ pmp: switch (getContentFromJson(
+ json,
+ )["com.beeper.per_message_profile"]) {
+ null => null,
+ final pmp => .fromJsonWithCatch(pmp),
+ },
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
new file mode 100644
index 0000000..9d4c386
--- /dev/null
+++ b/lib/models/per_message_profiles.dart
@@ -0,0 +1,53 @@
+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 c9751f8..8d9b21b 100644
--- a/lib/models/requests/download_media.dart
+++ b/lib/models/requests/download_media.dart
@@ -8,8 +8,6 @@ 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 b809a23..f93b261 100644
--- a/lib/models/room.dart
+++ b/lib/models/room.dart
@@ -45,10 +45,12 @@ 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) =>
@@ -61,6 +63,15 @@ 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 c0b5166..b9cf46c 100644
--- a/lib/models/room_order.dart
+++ b/lib/models/room_order.dart
@@ -1 +1,6 @@
-enum RoomOrder { unreadFirst, recentActivity }
+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),
+}
diff --git a/lib/models/room_subprofiles.dart b/lib/models/room_subprofiles.dart
new file mode 100644
index 0000000..073536c
--- /dev/null
+++ b/lib/models/room_subprofiles.dart
@@ -0,0 +1,37 @@
+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 79c3d64..6e08a0e 100644
--- a/lib/models/settings.dart
+++ b/lib/models/settings.dart
@@ -18,10 +18,13 @@ class const Settings({
final bool showMinimizeButton = false,
final bool swipeToReply = false,
final bool hideMembershipEvents = false,
- final bool hideServerAclEvents = true,
+ final bool showHiddenEvents = false,
+ @JsonKey(unknownEnumValue: RoomOrder.unreadFirst)
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 97efe7a..dec86a7 100644
--- a/lib/models/space.dart
+++ b/lib/models/space.dart
@@ -14,4 +14,5 @@ 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 ea74130..41aea2f 100644
--- a/lib/models/space_edge.dart
+++ b/lib/models/space_edge.dart
@@ -7,6 +7,8 @@ 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 ff8db09..12badd5 100644
--- a/lib/widgets/account_scope.dart
+++ b/lib/widgets/account_scope.dart
@@ -3,6 +3,7 @@ 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
@@ -23,6 +24,7 @@ class const AccountScope({
accountId: initialAccountId,
notificationRowId: null,
));
+ final isLaunch = useState(true);
return ProviderScope(
key: ValueKey(active.value.accountId),
@@ -30,14 +32,17 @@ class const AccountScope({
observers: observers,
overrides: [
ActiveAccountController.provider.overrideWith(
- () => ActiveAccountController(
- active.value.accountId,
- (next) => active.value = next,
- ),
+ () => ActiveAccountController(active.value.accountId, (next) {
+ isLaunch.value = false;
+ 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 bb14c78..7945035 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!, isAvatar: true)),
+ image: MxcImage(ref, .new(mxc: avatar!)),
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 5640342..63461c5 100644
--- a/lib/widgets/avatars/editable_avatar.dart
+++ b/lib/widgets/avatars/editable_avatar.dart
@@ -55,6 +55,10 @@ 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 34a1f76..d034b62 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,
- /// If set, a download button is shown, suggesting this filename
+ /// Suggested filename when downloading, falling back to the media ID
final String? downloadFilename,
final int? size,
super.key,
diff --git a/lib/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart
index 3b722e0..f251838 100644
--- a/lib/widgets/composer/composer.dart
+++ b/lib/widgets/composer/composer.dart
@@ -3,6 +3,7 @@ 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";
@@ -26,6 +27,9 @@ 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";
@@ -94,6 +98,7 @@ class const Composer(
:poll,
:location,
:textCommands,
+ :textReplacements,
) = ref.watch(
draftProvider.select(
(draft) => (
@@ -104,6 +109,7 @@ class const Composer(
poll: draft.poll,
location: draft.location,
textCommands: draft.textCommands,
+ textReplacements: draft.textReplacements,
),
),
);
@@ -145,7 +151,7 @@ class const Composer(
];
},
);
- }, [composer, editingEvent, hasReplacement]);
+ }, [composer, editingEvent, hasReplacement, textReplacements]);
useEffect(
// After the frame, as FlutterTagger and TextField still use it until then
() =>
@@ -430,6 +436,32 @@ 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,
@@ -477,513 +509,539 @@ class const Composer(
fontWeight: .bold,
);
- return 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(),
+ 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),
),
- 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),
+ 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),
- },
+ _ => 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),
+ ),
+ )
+ ? [
+ 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...",
+ ),
+ ),
+ ),
+ ],
+ ),
),
],
),
),
- 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 c95db16..0c2fed9 100644
--- a/lib/widgets/composer/overlays/room_overlay.dart
+++ b/lib/widgets/composer/overlays/room_overlay.dart
@@ -2,6 +2,7 @@ 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";
@@ -41,15 +42,15 @@ class const RoomOverlay(
? null
: Text(room.metadata!.topic!, maxLines: 1),
onTap: () {
- final vias = ref.watch(ViaController.provider(room)).viaQuery;
+ final alias = room.metadata?.canonicalAlias;
addTag(
- id: "[#$name](matrix:roomid/${room.metadata?.id.substring(1)}$vias)",
+ id: alias == null
+ ? "[#$name](matrix:roomid/${room.metadata?.id.substring(1)}${ref.read(ViaController.provider(room)).viaQuery})"
+ : "[#$name](matrix:r/${alias.substring(1)})",
name:
- (room.metadata?.canonicalAlias ?? room.metadata?.id)
- ?.substring(1)
- .split(":")
- .first ??
- "",
+ room.metadata?.canonicalAlias?.localpart ??
+ room.metadata?.id ??
+ "Unknown Room",
);
},
);
diff --git a/lib/widgets/composer/overlays/tagger_overlay.dart b/lib/widgets/composer/overlays/tagger_overlay.dart
index e32a328..264ed8c 100644
--- a/lib/widgets/composer/overlays/tagger_overlay.dart
+++ b/lib/widgets/composer/overlays/tagger_overlay.dart
@@ -16,27 +16,30 @@ class const TaggerOverlay(
}) extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
- 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,
- ),
+ // 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,
+ ),
- _ => Loading(),
- },
+ _ => Loading(),
+ },
+ ),
),
),
),
diff --git a/lib/widgets/composer/overlays/user_overlay.dart b/lib/widgets/composer/overlays/user_overlay.dart
index 845fb3a..40cb028 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
new file mode 100644
index 0000000..dc54b97
--- /dev/null
+++ b/lib/widgets/composer/subprofile_button.dart
@@ -0,0 +1,53 @@
+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
new file mode 100644
index 0000000..425038e
--- /dev/null
+++ b/lib/widgets/composer/subprofile_picker.dart
@@ -0,0 +1,101 @@
+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 9cacb9c..e8e452b 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 fb834c9..086bd1a 100644
--- a/lib/widgets/emoji/emoji_picker.dart
+++ b/lib/widgets/emoji/emoji_picker.dart
@@ -45,6 +45,7 @@ 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 36e4e09..f4c2fea 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/client_state.dart";
+import "package:nexus/controllers/account_management.dart";
import "package:nexus/helpers/launch_helper.dart";
import "package:nexus/models/gomuks_exception.dart";
import "package:nexus/models/recovery_key.dart";
@@ -41,15 +41,10 @@ class const RecoveryKeySheet(
// Open the approval page straight away the first time.
if (!needsApproval.value) {
needsApproval.value = true;
- final homeserver = ref
- .read(ClientStateController.provider)
- ?.homeserverUrl;
- final url = homeserver == null
- ? null
- : await ref
- .read(ClientController.provider.notifier)
- .getCrossSigningResetUrl(.parse(homeserver))
- .onError((_, _) => null);
+ final url = await ref
+ .read(AccountManagementController.provider.future)
+ .then((management) => management?.urlFor(.crossSigningReset))
+ .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 9236e9a..76b656e 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_text.dart";
+import "package:nexus/widgets/html/spoiler.dart";
import "package:nexus/widgets/html/code_block.dart";
import "package:nexus/widgets/html/quoted.dart";
@@ -29,7 +29,11 @@ class const Html(
}
if (element.attributes.keys.contains("data-mx-spoiler")) {
- return InlineCustomWidget(child: SpoilerText(element.text));
+ return InlineCustomWidget(
+ child: Spoiler(
+ Html(element.innerHtml, textStyle: textStyle, roomId: roomId),
+ ),
+ );
}
final height =
@@ -94,7 +98,6 @@ 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_text.dart b/lib/widgets/html/spoiler.dart
similarity index 64%
rename from lib/widgets/html/spoiler_text.dart
rename to lib/widgets/html/spoiler.dart
index e4a5977..7970bf3 100644
--- a/lib/widgets/html/spoiler_text.dart
+++ b/lib/widgets/html/spoiler.dart
@@ -1,7 +1,7 @@
import "package:material_ui/material_ui.dart";
import "package:flutter_hooks/flutter_hooks.dart";
-class const SpoilerText(final String text, {super.key}) extends HookWidget {
+class const Spoiler(final Widget child, {super.key}) extends HookWidget {
@override
Widget build(BuildContext context) {
final revealed = useState(false);
@@ -10,15 +10,15 @@ class const SpoilerText(final String text, {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: Text(
- text,
- style: .new(color: revealed.value ? null : Colors.transparent),
- ),
+ child: IgnorePointer(ignoring: !revealed.value, child: child),
),
);
}
diff --git a/lib/widgets/lazy_loading/message_avatar.dart b/lib/widgets/lazy_loading/message_avatar.dart
index 80a1101..cb75f02 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 0f68ac5..b591935 100644
--- a/lib/widgets/lazy_loading/message_displayname.dart
+++ b/lib/widgets/lazy_loading/message_displayname.dart
@@ -1,6 +1,7 @@
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";
@@ -27,14 +28,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(
- "(via ${event.sender})",
+ "(${ref.watch(UserController.provider(.new(roomId: event.roomId, userId: event.sender))).value?.displayName ?? event.sender.localpart})",
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 c5d704f..8e66b9e 100644
--- a/lib/widgets/pages/chat.dart
+++ b/lib/widgets/pages/chat.dart
@@ -4,6 +4,7 @@ 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";
@@ -12,6 +13,7 @@ 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 {
@@ -53,6 +55,21 @@ 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 053041a..76c8641 100644
--- a/lib/widgets/players/video.dart
+++ b/lib/widgets/players/video.dart
@@ -1,6 +1,8 @@
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";
@@ -10,6 +12,7 @@ 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,
@@ -32,6 +35,41 @@ 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 44c455b..cf4b717 100644
--- a/lib/widgets/reactions/reactions_popover.dart
+++ b/lib/widgets/reactions/reactions_popover.dart
@@ -64,25 +64,29 @@ 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: Tab(
- child: Row(
- mainAxisSize: .min,
- spacing: 8,
- children: [
- ReactionKey(reaction, height: 20),
- Text(reactions[reaction]!.senders.length.toString()),
- ],
+ child: Padding(
+ padding: kTabLabelPadding,
+ child: Tab(
+ child: Row(
+ mainAxisSize: .min,
+ spacing: 8,
+ children: [
+ ReactionKey(reaction, height: 20),
+ Text(reactions[reaction]!.senders.length.toString()),
+ ],
+ ),
),
),
);
@@ -118,7 +122,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 156d3f8..b23695d 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 3021102..9f8e537 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 41bd3a1..b5e6434 100644
--- a/lib/widgets/renderers/diffs/pinned_events_diff.dart
+++ b/lib/widgets/renderers/diffs/pinned_events_diff.dart
@@ -1,13 +1,8 @@
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/models/content/message.dart";
-import "package:nexus/widgets/lazy_loading/message_displayname.dart";
-import "package:nexus/widgets/renderers/event.dart";
+import "package:nexus/widgets/renderers/related_event_line.dart";
/// A line for each message a pinned events event pinned, in green, and each one
/// it unpinned, in red and struck through.
@@ -19,11 +14,11 @@ class const PinnedEventsDiff(
/// If set, tapping a message jumps to it.
final JumpToEvent? jumpToEvent,
super.key,
-}) extends ConsumerWidget {
+}) extends StatelessWidget {
static const maxShown = 5;
@override
- Widget build(BuildContext context, WidgetRef ref) {
+ Widget build(BuildContext context) {
final theme = Theme.of(context);
final style = theme.textTheme.labelMedium;
final changes = [
@@ -43,66 +38,12 @@ class const PinnedEventsDiff(
? TextDecoration.lineThrough
: null;
- 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"),
- },
+ return RelatedEventLine(
+ roomId,
+ change.$1,
+ color: color,
+ decoration: decoration,
+ jumpToEvent: jumpToEvent,
);
}),
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 f90c917..e6af7c5 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 228abf6..a9f2f92 100644
--- a/lib/widgets/renderers/event.dart
+++ b/lib/widgets/renderers/event.dart
@@ -27,18 +27,24 @@ 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";
@@ -74,7 +80,6 @@ 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();
@@ -104,12 +109,12 @@ class const EventRenderer(
if (event == null) return SizedBox.shrink();
- final (hideMembershipEvents, hideServerAclEvents) = ref
+ final (hideMembershipEvents, showHiddenEvents) = ref
.watch(SettingsController.provider)
.maybeWhen(
- orElse: () => (false, true),
+ orElse: () => (false, false),
data: (settings) =>
- (settings.hideMembershipEvents, settings.hideServerAclEvents),
+ (settings.hideMembershipEvents, settings.showHiddenEvents),
);
final isHidden =
@@ -121,7 +126,7 @@ class const EventRenderer(
(content) =>
content is MembershipContent && content.status == .knock,
)) ||
- (hideServerAclEvents && event.content is ServerACLContent);
+ (!showHiddenEvents && event.content is ServerACLContent);
if (isHidden && !textOnly) return SizedBox.shrink();
@@ -139,6 +144,7 @@ class const EventRenderer(
GenericEventRenderer generic(
IconData icon,
String text, {
+ List spans = const [],
List details = const [],
}) => .new(
icon,
@@ -148,9 +154,13 @@ 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
@@ -172,8 +182,15 @@ class const EventRenderer(
),
);
- final child =
- event.isShownAsMessage || (isThreadRoot && event.redactedBy != null)
+ // 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))
? MessageRenderer(
event,
onTapReply: jumpToEvent == null
@@ -435,6 +452,113 @@ 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(
@@ -562,11 +686,6 @@ 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 53e10ac..4f5c2b3 100644
--- a/lib/widgets/renderers/event_preview.dart
+++ b/lib/widgets/renderers/event_preview.dart
@@ -18,7 +18,8 @@ class const EventPreview(
);
if (event == null) return SizedBox.shrink();
- final showSender = event.hasMessageContent;
+ final showSender =
+ event.hasMessageContent && event.relationType != "m.replace";
return IgnorePointer(
child: Padding(
diff --git a/lib/widgets/renderers/membership.dart b/lib/widgets/renderers/membership.dart
index 125ea64..53f8f10 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
new file mode 100644
index 0000000..191ad1e
--- /dev/null
+++ b/lib/widgets/renderers/related_event_line.dart
@@ -0,0 +1,85 @@
+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 a967075..fe887e1 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 8a29c38..8a149b3 100644
--- a/lib/widgets/room_chat/room_chat.dart
+++ b/lib/widgets/room_chat/room_chat.dart
@@ -1,4 +1,5 @@
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";
@@ -46,6 +47,28 @@ 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
@@ -177,6 +200,7 @@ 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 22d94f9..47d4d42 100644
--- a/lib/widgets/rooms/room_menu_button.dart
+++ b/lib/widgets/rooms/room_menu_button.dart
@@ -7,9 +7,11 @@ 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";
@@ -99,73 +101,92 @@ final class const RoomMenuButton(
title: Text("Copy Link"),
),
),
- 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)",
- ),
- ),
- ],
- );
- },
+ 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),
+ ),
child: ListTile(
- leading: Icon(Icons.person_add),
- title: Text("Invite"),
+ leading: Icon(Icons.manage_accounts),
+ title: Text("Room Profile"),
),
),
PopupMenuItem(
diff --git a/lib/widgets/rooms/room_summary_sheet.dart b/lib/widgets/rooms/room_summary_sheet.dart
index 2195101..54def51 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
new file mode 100644
index 0000000..d448194
--- /dev/null
+++ b/lib/widgets/rooms/share_sheet.dart
@@ -0,0 +1,127 @@
+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 b51b7c3..184238b 100644
--- a/lib/widgets/settings/local_aliases_sheet.dart
+++ b/lib/widgets/settings/local_aliases_sheet.dart
@@ -5,6 +5,7 @@ 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";
@@ -24,7 +25,7 @@ class const LocalAliasesSheet(
final localpart = useValueListenable(controller).text.trim();
final server = ref.watch(
ClientStateController.provider.select(
- (state) => state?.userId?.split(":").skip(1).join(":"),
+ (state) => state?.userId?.serverName,
),
);
diff --git a/lib/widgets/settings/member_chooser.dart b/lib/widgets/settings/member_chooser.dart
index fbaaa8e..9845892 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
new file mode 100644
index 0000000..fbfadcd
--- /dev/null
+++ b/lib/widgets/settings/subprofile_sheet.dart
@@ -0,0 +1,140 @@
+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 aabebbb..1540f11 100644
--- a/lib/widgets/sidebar/rooms_pane.dart
+++ b/lib/widgets/sidebar/rooms_pane.dart
@@ -94,38 +94,48 @@ class const RoomsPane({super.key}) extends ConsumerWidget {
),
],
),
- .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,
- ),
+ ...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,
+ ),
),
- ),
- 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,
+ ),
+ ),
+ ]),
],
onDestinationSelected: (value) {
ref
diff --git a/lib/widgets/sidebar/spaces_rail.dart b/lib/widgets/sidebar/spaces_rail.dart
index d84a40a..5dda4a4 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].children.firstOrNull?.metadata?.id);
+ .set(spaces[value].allChildRooms.firstOrNull?.metadata?.id);
},
sections: [
.new(
diff --git a/lib/widgets/users/room_profile_sheet.dart b/lib/widgets/users/room_profile_sheet.dart
new file mode 100644
index 0000000..68390a5
--- /dev/null
+++ b/lib/widgets/users/room_profile_sheet.dart
@@ -0,0 +1,77 @@
+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 12e0e24..b9bccff 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 d8a305c..0371fcc 100644
--- a/lib/widgets/users/user_span.dart
+++ b/lib/widgets/users/user_span.dart
@@ -3,15 +3,12 @@ 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,
@@ -47,8 +44,11 @@ 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,7 +56,8 @@ class UserSpan(
children: [
if (event.pmp != null)
TextSpan(
- text: " (via ${event.sender})",
+ text:
+ "(${ref.watch(UserController.provider(.new(roomId: event.roomId, userId: event.sender))).value?.displayName ?? event.sender.localpart})",
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 8f09dbc..aa8e46d 100644
--- a/linux/nix/default.nix
+++ b/linux/nix/default.nix
@@ -18,10 +18,34 @@
packages =
let
- default = pkgs.callPackage ./pkg {
+ unpatched = 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;
@@ -32,13 +56,33 @@
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 = default.overrideAttrs (old: {
- postInstall = ''
- unset GST_PLUGIN_SYSTEM_PATH_1_0
- ''
- + old.postInstall;
- });
+ 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
+ '';
+ })
+ );
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
new file mode 100644
index 0000000..6711e39
--- /dev/null
+++ b/linux/nix/patches/gtk3-egl-renderable-type.patch
@@ -0,0 +1,60 @@
+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 3fbe98f..d9545c5 100644
--- a/linux/nix/pkg/default.nix
+++ b/linux/nix/pkg/default.nix
@@ -28,6 +28,7 @@ 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
@@ -37,8 +38,6 @@ 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
@@ -61,7 +60,7 @@ flutter347.buildFlutterApplication {
linkify = "sha256-TpMD6+0zyY6i9l+6d8ErnVufmepCv362rCtnbOht/z4=";
location = "sha256-RL+l46pBhv75xP7ASJuazyYoi9vI35TSYAV11mkjAwY=";
fab_m3e = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI=";
- fluttertagger = "sha256-tHUNU2+fBPkq5UK5YRi3SWs1zF2PIPz6RgSbwignU/I=";
+ fluttertagger = "sha256-AYsV0qjFgnlQxGiRBYJ2xrfHNnKKh5OhvzPT7bdm5Yw=";
m3e_design = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI=";
navigation_rail_m3e = "sha256-5V9m6yY0jimx2gh7lQHYg4HDKQ4Wrl0ATmBhw5DkQMI=";
unifiedpush_linux = "sha256-KQKyBPL2ORK9O89C4K3RHGve/lvFaU1vIjSDnj6+bj4=";
diff --git a/pubspec.lock b/pubspec.lock
index 644480c..7b445a7 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -225,6 +225,14 @@ 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:
@@ -736,7 +744,7 @@ packages:
description:
path: "."
ref: HEAD
- resolved-ref: "78a5099499728917e7595f738f3b369b47804dc5"
+ resolved-ref: a631052fd7e36e20f605099df6831e17ae80568b
url: "https://github.com/Henry-Hiles/fluttertagger"
source: git
version: "2.3.2"
diff --git a/pubspec.yaml b/pubspec.yaml
index daf702e..3407eae 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -120,6 +120,7 @@ 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