From 720e538dbc106f6207673290c31c1615c5c1caa7 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Mon, 23 Nov 2026 14:23:00 -0500 Subject: [PATCH 01/53] unfocus textfield when outside tap on mobile --- lib/widgets/composer/composer.dart | 1023 +++++++++-------- .../composer/overlays/tagger_overlay.dart | 43 +- 2 files changed, 547 insertions(+), 519 deletions(-) diff --git a/lib/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index 3b722e0..d4aaa9f 100644 --- a/lib/widgets/composer/composer.dart +++ b/lib/widgets/composer/composer.dart @@ -477,513 +477,538 @@ 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), + ), + ) + ? [ + 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/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(), + }, + ), ), ), ), From b0d22e55708270ee3a49d8cfbdd4130e7d4c2799 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 24 Nov 2026 12:57:19 -0500 Subject: [PATCH 02/53] fix issue when mentioning room with invalid canonical aliases --- lib/controllers/bot_argument_suggestions.dart | 2 +- lib/controllers/bot_commands.dart | 2 +- lib/controllers/settings_sections.dart | 2 +- lib/helpers/extensions/get_localpart.dart | 2 +- lib/widgets/composer/overlays/room_overlay.dart | 9 ++++----- lib/widgets/composer/overlays/user_overlay.dart | 6 +++--- lib/widgets/composer/typing_indicator.dart | 2 +- lib/widgets/lazy_loading/message_avatar.dart | 4 ++-- lib/widgets/lazy_loading/message_displayname.dart | 2 +- lib/widgets/reactions/reactions_popover.dart | 2 +- lib/widgets/read_receipts/read_receipts_row.dart | 2 +- lib/widgets/read_receipts/read_receipts_sheet.dart | 2 +- lib/widgets/renderers/diffs/power_levels_diff.dart | 2 +- lib/widgets/renderers/membership.dart | 2 +- lib/widgets/room_chat/member_list.dart | 4 ++-- lib/widgets/rooms/room_summary_sheet.dart | 2 +- lib/widgets/settings/local_aliases_sheet.dart | 3 ++- lib/widgets/settings/member_chooser.dart | 2 +- lib/widgets/users/user_bottom_sheet.dart | 8 ++++---- lib/widgets/users/user_span.dart | 7 +++++-- 20 files changed, 35 insertions(+), 32 deletions(-) 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/settings_sections.dart b/lib/controllers/settings_sections.dart index 999fea6..efe8cf5 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -756,7 +756,7 @@ class SettingsSectionsController return ListTile( enabled: !saving.active, - leading: AvatarOrHash(profile?.avatarUrl, name), + leading: AvatarOrHash(profile?.avatarUrl, name!), title: Text(name, overflow: .ellipsis), subtitle: Text(userId, overflow: .ellipsis), onTap: () => context.showAdaptiveSheet( 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/widgets/composer/overlays/room_overlay.dart b/lib/widgets/composer/overlays/room_overlay.dart index c95db16..f6b4bed 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"; @@ -45,11 +46,9 @@ class const RoomOverlay( addTag( id: "[#$name](matrix:roomid/${room.metadata?.id.substring(1)}$vias)", 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/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/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/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..c3fffcd 100644 --- a/lib/widgets/lazy_loading/message_displayname.dart +++ b/lib/widgets/lazy_loading/message_displayname.dart @@ -27,7 +27,7 @@ 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, diff --git a/lib/widgets/reactions/reactions_popover.dart b/lib/widgets/reactions/reactions_popover.dart index 44c455b..c1200c3 100644 --- a/lib/widgets/reactions/reactions_popover.dart +++ b/lib/widgets/reactions/reactions_popover.dart @@ -118,7 +118,7 @@ class const ReactionsPopover( return ListTile( leading: AvatarOrHash( member?.avatarUrl, - name, + name!, dimension: 40, ), title: Text(name, overflow: .ellipsis), diff --git a/lib/widgets/read_receipts/read_receipts_row.dart b/lib/widgets/read_receipts/read_receipts_row.dart index 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/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/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/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/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/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/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..d12469c 100644 --- a/lib/widgets/users/user_span.dart +++ b/lib/widgets/users/user_span.dart @@ -47,8 +47,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, From be69358ea46c2d37681ae1ff5ba4afe1e10d2278 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 24 Nov 2026 13:05:57 -0500 Subject: [PATCH 03/53] hide room header when empty --- lib/widgets/sidebar/rooms_pane.dart | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/widgets/sidebar/rooms_pane.dart b/lib/widgets/sidebar/rooms_pane.dart index aabebbb..0c63428 100644 --- a/lib/widgets/sidebar/rooms_pane.dart +++ b/lib/widgets/sidebar/rooms_pane.dart @@ -94,12 +94,15 @@ class const RoomsPane({super.key}) extends ConsumerWidget { ), ], ), - .new( - header: selectedSpace.room == null - ? null - : const DividerWidget(Text("Rooms")), - destinations: selectedSpace.children.toDestinations(isDm: isDm), - ), + if (selectedSpace.children.isNotEmpty) + .new( + header: selectedSpace.room == null + ? null + : const DividerWidget(Text("Rooms")), + destinations: selectedSpace.children.toDestinations( + isDm: isDm, + ), + ), ...selectedSpace.subSpaces.map( (subSpace) => NavigationRailM3ESection( header: DividerWidget( From 812183cc00aa63ebaffa93439a85b65f155796e5 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 24 Nov 2026 13:07:33 -0500 Subject: [PATCH 04/53] fix subsubspaces showing as regular rooms --- lib/controllers/spaces.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/controllers/spaces.dart b/lib/controllers/spaces.dart index 4d6dffe..b4a0a22 100644 --- a/lib/controllers/spaces.dart +++ b/lib/controllers/spaces.dart @@ -60,6 +60,7 @@ class SpacesController extends AsyncNotifier> { room: room, children: .new( collectDescendants(childId) + .where((id) => !childrenById.containsKey(id)) .map((id) => rooms[id]) .nonNulls, ), From 7391a5a50cced4fc17f9923a48395031b1f73282 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 14:37:57 -0500 Subject: [PATCH 05/53] fix deprecation warning --- hook/build.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hook/build.dart b/hook/build.dart index 2181e8a..c4af12e 100644 --- a/hook/build.dart +++ b/hook/build.dart @@ -28,7 +28,7 @@ Future 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) { From b680add183a51c0624316516f99664c69eb52180 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 14:41:24 -0500 Subject: [PATCH 06/53] try to fix android group issues --- lib/controllers/notification.dart | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lib/controllers/notification.dart b/lib/controllers/notification.dart index e8a5dff..fd3d0c1 100644 --- a/lib/controllers/notification.dart +++ b/lib/controllers/notification.dart @@ -63,7 +63,16 @@ class NotificationController static String payloadFor(String accountId, int rowId) => "$accountId:$rowId"; + static const _androidGroup = "nexus.federated.nexus.MESSAGES"; + static const _summaryPayload = "summary"; + void _open(String payload) { + if (payload == _summaryPayload) { + navigatorKey.currentState?.popUntil((route) => route.isFirst); + ref.read(SidebarPageController.provider.notifier).set(.notifications); + return; + } + final (accountId, rowId) = switch (payload.split(":")) { [final accountId, final rowId] => (accountId, int.tryParse(rowId)), // From before notifications were per account @@ -230,6 +239,7 @@ class NotificationController ? .new( "general", "General", + groupKey: _androidGroup, subText: subtitle, silent: !sound, when: timestamp?.millisecondsSinceEpoch, @@ -241,6 +251,7 @@ class NotificationController : .new( "messages", "Messages", + groupKey: _androidGroup, subText: subtitle, silent: !sound, when: timestamp?.millisecondsSinceEpoch, @@ -281,6 +292,25 @@ class NotificationController ), ), ); + + if (Platform.isAndroid) { + await controller.show( + id: 0, + title: "Nexus", + payload: _summaryPayload, + notificationDetails: const .new( + android: .new( + "messages", + "Messages", + groupKey: _androidGroup, + setAsGroupSummary: true, + groupAlertBehavior: .children, + onlyAlertOnce: true, + silent: true, + ), + ), + ); + } } static final provider = From 322217fc20560b60e0d656d9d1fa7517418f3f85 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 15:14:52 -0500 Subject: [PATCH 07/53] try to dismiss notifications when read --- lib/controllers/notification.dart | 86 +++++++++++++++++++++++++++++++ lib/controllers/unified_push.dart | 5 +- 2 files changed, 90 insertions(+), 1 deletion(-) diff --git a/lib/controllers/notification.dart b/lib/controllers/notification.dart index fd3d0c1..eff818c 100644 --- a/lib/controllers/notification.dart +++ b/lib/controllers/notification.dart @@ -2,10 +2,14 @@ import "dart:async"; import "dart:convert"; import "dart:io"; +import "package:collection/collection.dart"; +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/portal.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/controllers/shared_prefs.dart"; import "package:nexus/controllers/sidebar_page.dart"; import "package:nexus/main.dart"; import "package:flutter_local_notifications/flutter_local_notifications.dart"; @@ -58,13 +62,92 @@ class NotificationController }); } + // 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; + + final accountId = ref.read(ActiveAccountController.provider); + dismiss(newlyRead.map((roomId) => threadIdFor(accountId, roomId))) + .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 _androidGroup = "nexus.federated.nexus.MESSAGES"; static const _summaryPayload = "summary"; + static const _shownKey = "shownNotifications"; + + /// IDs of the notifications shown, by thread. Stored, since they're often + /// shown by a background instance. + Future>> _shown() async => IMap( + json.decode( + await ref.read(SharedPrefsController.provider).getString(_shownKey) ?? + "{}", + ), + ).map((threadId, ids) => .new(threadId, IList((ids as List).cast()))); + + Future _setShown(IMap> shown) => ref + .read(SharedPrefsController.provider) + .setString( + _shownKey, + json.encode( + shown.map((threadId, ids) => .new(threadId, ids.unlock)).unlock, + ), + ); + + Future _track(String threadId, int id) async { + final shown = await _shown(); + final ids = shown[threadId] ?? const IListConst([]); + if (!ids.contains(id)) await _setShown(shown.add(threadId, ids.add(id))); + } + + /// Dismisses the notifications shown for [threadIds]. + Future dismiss(Iterable threadIds) async { + final shown = await _shown(); + final ids = threadIds.map((threadId) => shown[threadId]).nonNulls.flattened; + if (ids.isEmpty) return; + + await _setShown( + shown.removeWhere((threadId, _) => threadIds.contains(threadId)), + ); + + 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) { if (payload == _summaryPayload) { @@ -208,6 +291,7 @@ class NotificationController // ), ], ); + if (threadId != null) await _track(threadId, id); return; } @@ -293,6 +377,8 @@ class NotificationController ), ); + if (threadId != null) await _track(threadId, id); + if (Platform.isAndroid) { await controller.show( id: 0, diff --git a/lib/controllers/unified_push.dart b/lib/controllers/unified_push.dart index 25675e2..ec1e7e1 100644 --- a/lib/controllers/unified_push.dart +++ b/lib/controllers/unified_push.dart @@ -143,7 +143,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, From 23d77ddc60d137732271771a82345e939f292323 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 15:18:07 -0500 Subject: [PATCH 08/53] high importance and high priority for notifications --- lib/controllers/notification.dart | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/controllers/notification.dart b/lib/controllers/notification.dart index eff818c..b8b2e2c 100644 --- a/lib/controllers/notification.dart +++ b/lib/controllers/notification.dart @@ -48,6 +48,12 @@ class NotificationController if (details.payload case final payload?) _open(payload); }, ); + + await notifications + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin + >() + ?.deleteNotificationChannel(channelId: "messages"); } if (Platform.isLinux) { @@ -93,6 +99,8 @@ class NotificationController static const _androidGroup = "nexus.federated.nexus.MESSAGES"; static const _summaryPayload = "summary"; + + static const _messagesChannel = "messages_v2"; static const _shownKey = "shownNotifications"; /// IDs of the notifications shown, by thread. Stored, since they're often @@ -333,8 +341,10 @@ class NotificationController styleInformation: BigTextStyleInformation(body), ) : .new( - "messages", + _messagesChannel, "Messages", + importance: .high, + priority: .high, groupKey: _androidGroup, subText: subtitle, silent: !sound, @@ -386,8 +396,9 @@ class NotificationController payload: _summaryPayload, notificationDetails: const .new( android: .new( - "messages", + _messagesChannel, "Messages", + importance: .high, groupKey: _androidGroup, setAsGroupSummary: true, groupAlertBehavior: .children, From c3b39a629432cf7b3c8f96e7a9081fc55ce41ee6 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 15:23:26 -0500 Subject: [PATCH 09/53] refactor notif code --- lib/controllers/notification.dart | 197 +++++++------------- lib/helpers/shown_notifications_helper.dart | 52 ++++++ 2 files changed, 121 insertions(+), 128 deletions(-) create mode 100644 lib/helpers/shown_notifications_helper.dart diff --git a/lib/controllers/notification.dart b/lib/controllers/notification.dart index b8b2e2c..940ff2a 100644 --- a/lib/controllers/notification.dart +++ b/lib/controllers/notification.dart @@ -2,15 +2,14 @@ import "dart:async"; import "dart:convert"; import "dart:io"; -import "package:collection/collection.dart"; 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/portal.dart"; import "package:nexus/controllers/rooms.dart"; -import "package:nexus/controllers/shared_prefs.dart"; import "package:nexus/controllers/sidebar_page.dart"; +import "package:nexus/helpers/shown_notifications_helper.dart"; import "package:nexus/main.dart"; import "package:flutter_local_notifications/flutter_local_notifications.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; @@ -30,7 +29,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( @@ -56,18 +65,6 @@ class NotificationController ?.deleteNotificationChannel(channelId: "messages"); } - if (Platform.isLinux) { - const notificationChannel = MethodChannel("nexus/notifications"); - - notificationChannel.setMethodCallHandler((call) async { - if (call.method != "notificationClicked") { - return; - } - - if (call.arguments case final String payload) _open(payload); - }); - } - // Reading a room, here or on another client, dismisses its notifications if (!isInBackground) { ref.listen( @@ -82,8 +79,9 @@ class NotificationController if (newlyRead.isEmpty) return; final accountId = ref.read(ActiveAccountController.provider); - dismiss(newlyRead.map((roomId) => threadIdFor(accountId, roomId))) - .onError(showError); + dismiss( + newlyRead.map((roomId) => threadIdFor(accountId, roomId)).toISet(), + ).onError(showError); }, fireImmediately: true, ); @@ -101,42 +99,14 @@ class NotificationController static const _summaryPayload = "summary"; static const _messagesChannel = "messages_v2"; - static const _shownKey = "shownNotifications"; - - /// IDs of the notifications shown, by thread. Stored, since they're often - /// shown by a background instance. - Future>> _shown() async => IMap( - json.decode( - await ref.read(SharedPrefsController.provider).getString(_shownKey) ?? - "{}", - ), - ).map((threadId, ids) => .new(threadId, IList((ids as List).cast()))); - - Future _setShown(IMap> shown) => ref - .read(SharedPrefsController.provider) - .setString( - _shownKey, - json.encode( - shown.map((threadId, ids) => .new(threadId, ids.unlock)).unlock, - ), - ); - - Future _track(String threadId, int id) async { - final shown = await _shown(); - final ids = shown[threadId] ?? const IListConst([]); - if (!ids.contains(id)) await _setShown(shown.add(threadId, ids.add(id))); - } /// Dismisses the notifications shown for [threadIds]. - Future dismiss(Iterable threadIds) async { - final shown = await _shown(); - final ids = threadIds.map((threadId) => shown[threadId]).nonNulls.flattened; + Future dismiss(ISet threadIds) async { + final ids = await ref + .read(ShownNotificationsHelper.provider) + .remove(threadIds); if (ids.isEmpty) return; - await _setShown( - shown.removeWhere((threadId, _) => threadIds.contains(threadId)), - ); - if (Platform.isLinux) { final portal = await ref.read(PortalController.provider.future); await Future.wait( @@ -158,12 +128,10 @@ class NotificationController } void _open(String payload) { - if (payload == _summaryPayload) { - navigatorKey.currentState?.popUntil((route) => route.isFirst); - ref.read(SidebarPageController.provider.notifier).set(.notifications); - return; - } + navigatorKey.currentState?.popUntil((route) => route.isFirst); + ref.read(SidebarPageController.provider.notifier).set(.notifications); + // The summary's payload has no row, so it only opens the notifications final (accountId, rowId) = switch (payload.split(":")) { [final accountId, final rowId] => (accountId, int.tryParse(rowId)), // From before notifications were per account @@ -172,9 +140,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( @@ -184,73 +149,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 @@ -273,6 +215,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); @@ -299,7 +242,7 @@ class NotificationController // ), ], ); - if (threadId != null) await _track(threadId, id); + if (threadId != null) await shown.add(threadId, id); return; } @@ -315,6 +258,7 @@ class NotificationController .onError((_, _) => null) : null; + final largeIcon = icon == null ? null : FilePathAndroidBitmap(icon.path); final darwin = DarwinNotificationDetails( subtitle: subtitle, presentSound: sound, @@ -335,9 +279,7 @@ class NotificationController subText: subtitle, silent: !sound, when: timestamp?.millisecondsSinceEpoch, - largeIcon: icon == null - ? null - : FilePathAndroidBitmap(icon.path), + largeIcon: largeIcon, styleInformation: BigTextStyleInformation(body), ) : .new( @@ -350,9 +292,7 @@ class NotificationController 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, @@ -365,11 +305,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, + }, ), ), ], @@ -387,7 +328,7 @@ class NotificationController ), ); - if (threadId != null) await _track(threadId, id); + if (threadId != null) await shown.add(threadId, id); if (Platform.isAndroid) { await controller.show( diff --git a/lib/helpers/shown_notifications_helper.dart b/lib/helpers/shown_notifications_helper.dart new file mode 100644 index 0000000..2957fdf --- /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) => ISet.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: () => ISet({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, + ); +} From 2c1ccc4728ecaaae87c8f41e99bc1ef461489628 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 15:28:51 -0500 Subject: [PATCH 10/53] use dot shorthands where possible in notif code --- lib/helpers/shown_notifications_helper.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/helpers/shown_notifications_helper.dart b/lib/helpers/shown_notifications_helper.dart index 2957fdf..17d3975 100644 --- a/lib/helpers/shown_notifications_helper.dart +++ b/lib/helpers/shown_notifications_helper.dart @@ -16,7 +16,7 @@ class ShownNotificationsHelper(final Ref ref) { final shown = IMap>.fromJson( json.decode(await prefs.getString(_key) ?? "{}"), (threadId) => threadId as String, - (ids) => ISet.fromJson(ids, (id) => id as int), + (ids) => .fromJson(ids, (id) => id as int), ); await prefs.setString( @@ -33,7 +33,7 @@ class ShownNotificationsHelper(final Ref ref) { (shown) => shown.update( threadId, (ids) => ids.add(id), - ifAbsent: () => ISet({id}), + ifAbsent: () => .new({id}), ), ); From 36a43a7a3676c164cf18ec5dce03fb1482984bdf Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 15:48:40 -0500 Subject: [PATCH 11/53] Restore tags on edit Fixes #182 --- lib/controllers/composer_draft.dart | 46 ++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/lib/controllers/composer_draft.dart b/lib/controllers/composer_draft.dart index 25ed273..79aa8db 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,45 @@ class ComposerDraftController(final ComposerParams composer) _botCommand.clear(); } + static final _tagPattern = RegExp( + r"\[@[^\]]*\]\(matrix:u/([^)\s]+)\)" + r"|\[#[^\]]*\]\(matrix:roomid/([^)?\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])) { + (final userId?, _, _) => Tag( + id: match[0]!, + text: userId.split(":").first, + triggerCharacter: "@", + ), + (_, final roomId?, _) => Tag( + id: match[0]!, + text: + rooms["!$roomId"]?.metadata?.canonicalAlias?.localpart ?? + "!$roomId", + triggerCharacter: "#", + ), + (_, _, final shortcode) => Tag( + 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); From 3ba258d6b488d921b1f1f0fb84a1b51d0b3ed634 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 15:50:59 -0500 Subject: [PATCH 12/53] Clearer revealed spoilers Fixes #184 --- lib/controllers/composer_draft.dart | 6 +++--- lib/widgets/html/spoiler_text.dart | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/controllers/composer_draft.dart b/lib/controllers/composer_draft.dart index 79aa8db..c6e8e78 100644 --- a/lib/controllers/composer_draft.dart +++ b/lib/controllers/composer_draft.dart @@ -92,19 +92,19 @@ class ComposerDraftController(final ComposerParams composer) ({String text, IList tags}) _restoreTags(String text) { final rooms = ref.read(RoomsController.provider); Tag tagOf(Match match) => switch ((match[1], match[2], match[3])) { - (final userId?, _, _) => Tag( + (final userId?, _, _) => .new( id: match[0]!, text: userId.split(":").first, triggerCharacter: "@", ), - (_, final roomId?, _) => Tag( + (_, final roomId?, _) => .new( id: match[0]!, text: rooms["!$roomId"]?.metadata?.canonicalAlias?.localpart ?? "!$roomId", triggerCharacter: "#", ), - (_, _, final shortcode) => Tag( + (_, _, final shortcode) => .new( id: match[0]!, text: shortcode!, triggerCharacter: ":", diff --git a/lib/widgets/html/spoiler_text.dart b/lib/widgets/html/spoiler_text.dart index e4a5977..8094f9d 100644 --- a/lib/widgets/html/spoiler_text.dart +++ b/lib/widgets/html/spoiler_text.dart @@ -10,9 +10,10 @@ 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: revealed.value ? Colors.transparent : Colors.blueGrey, + color: revealed.value + ? Colors.blueGrey.withValues(alpha: 0.3) + : Colors.blueGrey, borderRadius: .circular(4), ), child: Text( From f2494db2eee83ca0ade47f3027c8fc237c0828b1 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 15:52:17 -0500 Subject: [PATCH 13/53] add ctrl+f shortcut for room search Fixes #179 --- lib/widgets/room_chat/room_chat.dart | 119 +++++++++++++++------------ 1 file changed, 67 insertions(+), 52 deletions(-) diff --git a/lib/widgets/room_chat/room_chat.dart b/lib/widgets/room_chat/room_chat.dart index 8a29c38..bb218a8 100644 --- a/lib/widgets/room_chat/room_chat.dart +++ b/lib/widgets/room_chat/room_chat.dart @@ -184,62 +184,77 @@ final class const RoomChat({ jumpToEvent: jumpToEvent, ), body: Builder( - builder: (searchContext) => Scaffold( - endDrawerEnableOpenDragGesture: false, - endDrawer: ThreadsDrawer(roomId, onOpenThread: openThread), - body: Builder( - builder: (threadsContext) => Scaffold( - endDrawerEnableOpenDragGesture: false, - endDrawer: PinnedEventsDrawer( - roomId, - getEventOptions: getEventOptions, - jumpToEvent: jumpToEvent, - ), - body: Builder( - builder: (middleContext) => Scaffold( - endDrawer: showMembersByDefault ? null : MemberList(roomId), - appBar: RoomAppbar( - roomId: roomId, - isDesktop: isDesktop, - onOpenDrawer: Scaffold.of(context).openDrawer, - onOpenMemberList: (thisContext) { - if (!showMembersByDefault) { - return Scaffold.of(thisContext).openEndDrawer(); - } + builder: (searchContext) => CallbackShortcuts( + bindings: { + const SingleActivator(.keyF, control: true): Scaffold.of( + searchContext, + ).openEndDrawer, + const SingleActivator(.keyF, meta: true): Scaffold.of( + searchContext, + ).openEndDrawer, + }, + child: Scaffold( + endDrawerEnableOpenDragGesture: false, + endDrawer: ThreadsDrawer(roomId, onOpenThread: openThread), + body: Builder( + builder: (threadsContext) => Scaffold( + endDrawerEnableOpenDragGesture: false, + endDrawer: PinnedEventsDrawer( + roomId, + getEventOptions: getEventOptions, + jumpToEvent: jumpToEvent, + ), + body: Builder( + builder: (middleContext) => Scaffold( + endDrawer: showMembersByDefault + ? null + : MemberList(roomId), + appBar: RoomAppbar( + roomId: roomId, + isDesktop: isDesktop, + onOpenDrawer: Scaffold.of(context).openDrawer, + onOpenMemberList: (thisContext) { + if (!showMembersByDefault) { + return Scaffold.of(thisContext).openEndDrawer(); + } - ref - .read(MemberListOpenedController.provider.notifier) - .set(!memberListOpened) - .onError(showError); - }, - onOpenPinnedMessagesList: Scaffold.of(middleContext) - .openEndDrawer, - onOpenSearch: Scaffold.of(searchContext).openEndDrawer, - onOpenThreads: Scaffold.of(threadsContext).openEndDrawer, - ), - body: Column( - children: [ - const SyncStatusBanner(), - Expanded( - child: Row( - children: [ - Expanded( - child: ChatBody( - chat: chat, - scroll: scroll, - jumpToEvent: jumpToEvent, - getEventOptions: getEventOptions, - composer: composer, - onOpenThread: openThread, + ref + .read( + MemberListOpenedController.provider.notifier, + ) + .set(!memberListOpened) + .onError(showError); + }, + onOpenPinnedMessagesList: Scaffold.of(middleContext) + .openEndDrawer, + onOpenSearch: Scaffold.of(searchContext).openEndDrawer, + onOpenThreads: Scaffold.of(threadsContext) + .openEndDrawer, + ), + body: Column( + children: [ + const SyncStatusBanner(), + Expanded( + child: Row( + children: [ + Expanded( + child: ChatBody( + chat: chat, + scroll: scroll, + jumpToEvent: jumpToEvent, + getEventOptions: getEventOptions, + composer: composer, + onOpenThread: openThread, + ), ), - ), - if (memberListOpened && showMembersByDefault) - MemberList(roomId), - ], + if (memberListOpened && showMembersByDefault) + MemberList(roomId), + ], + ), ), - ), - ], + ], + ), ), ), ), From 5df7c2c00a081d773694bfe999de64252c25f6db Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 15:58:43 -0500 Subject: [PATCH 14/53] improve ctrl+f handling --- lib/widgets/room_chat/room_chat.dart | 143 ++++++++++++++------------- 1 file changed, 76 insertions(+), 67 deletions(-) diff --git a/lib/widgets/room_chat/room_chat.dart b/lib/widgets/room_chat/room_chat.dart index bb218a8..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, @@ -184,77 +208,62 @@ final class const RoomChat({ jumpToEvent: jumpToEvent, ), body: Builder( - builder: (searchContext) => CallbackShortcuts( - bindings: { - const SingleActivator(.keyF, control: true): Scaffold.of( - searchContext, - ).openEndDrawer, - const SingleActivator(.keyF, meta: true): Scaffold.of( - searchContext, - ).openEndDrawer, - }, - child: Scaffold( - endDrawerEnableOpenDragGesture: false, - endDrawer: ThreadsDrawer(roomId, onOpenThread: openThread), - body: Builder( - builder: (threadsContext) => Scaffold( - endDrawerEnableOpenDragGesture: false, - endDrawer: PinnedEventsDrawer( - roomId, - getEventOptions: getEventOptions, - jumpToEvent: jumpToEvent, - ), - body: Builder( - builder: (middleContext) => Scaffold( - endDrawer: showMembersByDefault - ? null - : MemberList(roomId), - appBar: RoomAppbar( - roomId: roomId, - isDesktop: isDesktop, - onOpenDrawer: Scaffold.of(context).openDrawer, - onOpenMemberList: (thisContext) { - if (!showMembersByDefault) { - return Scaffold.of(thisContext).openEndDrawer(); - } + builder: (searchContext) => Scaffold( + endDrawerEnableOpenDragGesture: false, + endDrawer: ThreadsDrawer(roomId, onOpenThread: openThread), + body: Builder( + builder: (threadsContext) => Scaffold( + endDrawerEnableOpenDragGesture: false, + endDrawer: PinnedEventsDrawer( + roomId, + getEventOptions: getEventOptions, + jumpToEvent: jumpToEvent, + ), + body: Builder( + builder: (middleContext) => Scaffold( + endDrawer: showMembersByDefault ? null : MemberList(roomId), + appBar: RoomAppbar( + roomId: roomId, + isDesktop: isDesktop, + onOpenDrawer: Scaffold.of(context).openDrawer, + onOpenMemberList: (thisContext) { + if (!showMembersByDefault) { + return Scaffold.of(thisContext).openEndDrawer(); + } - ref - .read( - MemberListOpenedController.provider.notifier, - ) - .set(!memberListOpened) - .onError(showError); - }, - onOpenPinnedMessagesList: Scaffold.of(middleContext) - .openEndDrawer, - onOpenSearch: Scaffold.of(searchContext).openEndDrawer, - onOpenThreads: Scaffold.of(threadsContext) - .openEndDrawer, - ), - body: Column( - children: [ - const SyncStatusBanner(), - Expanded( - child: Row( - children: [ - Expanded( - child: ChatBody( - chat: chat, - scroll: scroll, - jumpToEvent: jumpToEvent, - getEventOptions: getEventOptions, - composer: composer, - onOpenThread: openThread, - ), + ref + .read(MemberListOpenedController.provider.notifier) + .set(!memberListOpened) + .onError(showError); + }, + onOpenPinnedMessagesList: Scaffold.of(middleContext) + .openEndDrawer, + onOpenSearch: Scaffold.of(searchContext).openEndDrawer, + onOpenThreads: Scaffold.of(threadsContext).openEndDrawer, + ), + body: Column( + children: [ + const SyncStatusBanner(), + Expanded( + child: Row( + children: [ + Expanded( + child: ChatBody( + chat: chat, + scroll: scroll, + jumpToEvent: jumpToEvent, + getEventOptions: getEventOptions, + composer: composer, + onOpenThread: openThread, ), + ), - if (memberListOpened && showMembersByDefault) - MemberList(roomId), - ], - ), + if (memberListOpened && showMembersByDefault) + MemberList(roomId), + ], ), - ], - ), + ), + ], ), ), ), From b63fcc30b765ef341e1c20001f1d31c8481242ef Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 16:15:42 -0500 Subject: [PATCH 15/53] Video handling improvements Fixes #181 --- lib/widgets/players/video.dart | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) 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( From 432064e11182f8ea6834c0ab43110738a94a96cf Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 16:29:09 -0500 Subject: [PATCH 16/53] subspace sorting Fixes #183 --- lib/controllers/settings_sections.dart | 3 +- lib/controllers/spaces.dart | 70 ++++++++++++------ .../extensions/get_all_child_rooms.dart | 8 +- lib/models/room_order.dart | 2 +- lib/models/space.dart | 1 + lib/widgets/sidebar/rooms_pane.dart | 73 ++++++++++--------- 6 files changed, 98 insertions(+), 59 deletions(-) diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index efe8cf5..1bd7e3a 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -256,7 +256,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, optionally showing mentioned or unread ones first.", icon: Icons.sort, builder: (title, description, icon) => DialogListTile( icon: Icon(icon), @@ -266,6 +266,7 @@ class SettingsSectionsController options: RoomOrder.values, getName: (option) => switch (option) { .unreadFirst => "Mentioned, then unread", + .mentionedFirst => "Mentioned only", .recentActivity => "Recent activity only", }, onChanged: (value) => ref diff --git a/lib/controllers/spaces.dart b/lib/controllers/spaces.dart index b4a0a22..1591625 100644 --- a/lib/controllers/spaces.dart +++ b/lib/controllers/spaces.dart @@ -139,31 +139,57 @@ class SpacesController extends AsyncNotifier> { SettingsController.provider.selectAsync((data) => data.roomOrder), ); - // Mentioned -> Unread -> Other - int unreadPriority(Room room) => switch (room.metadata) { - RoomMetadata(unreadHighlights: > 0) => 0, - RoomMetadata(unreadNotifications: > 0) || - RoomMetadata(unreadMessages: > 0) => 1, - _ => 2, + int priority(Room room) => switch ((roomOrder, room.metadata)) { + (.recentActivity, _) => 0, + (_, RoomMetadata(unreadHighlights: > 0)) => 0, + (.mentionedFirst, _) => 1, + (.unreadFirst, RoomMetadata(unreadNotifications: > 0)) || + (.unreadFirst, RoomMetadata(unreadMessages: > 0)) => 1, + (.unreadFirst, _) => 2, + }; + DateTime activity(Room room) => room.metadata?.sortingTimestamp ?? .new(0); + + // Higher priority first, then most recent activity first + int compare( + ({int priority, DateTime activity}) a, + ({int priority, DateTime activity}) b, + ) => switch (a.priority.compareTo(b.priority)) { + 0 => b.activity.compareTo(a.activity), + final byPriority => byPriority, }; - return allSpaces - .map( - (space) => space.copyWith( - children: space.children.sort((a, b) { - if (roomOrder == .unreadFirst) { - final byUnread = unreadPriority(a).compareTo(unreadPriority(b)); - if (byUnread != 0) return byUnread; - } + ({int priority, DateTime activity}) roomKey(Room room) => + (priority: priority(room), activity: activity(room)); - // Most recent activity first - return (b.metadata?.sortingTimestamp ?? DateTime(0)).compareTo( - a.metadata?.sortingTimestamp ?? DateTime(0), - ); - }), - ), - ) - .toIList(); + ({int priority, DateTime activity}) groupKey(IList rooms) => ( + priority: rooms.map(priority).minOrNull ?? 2, + activity: rooms.map(activity).maxOrNull ?? .new(0), + ); + + IList sortRooms(IList rooms) => + rooms.sort((a, b) => compare(roomKey(a), roomKey(b))); + + return allSpaces.map((space) { + final subSpaces = space.subSpaces + .map( + (subspace) => + subspace.copyWith(children: sortRooms(subspace.children)), + ) + .toIList() + .sort((a, b) => compare(groupKey(a.children), groupKey(b.children))); + + final childrenKey = groupKey(space.children); + return space.copyWith( + children: sortRooms(space.children), + subSpaces: subSpaces, + childrenIndex: subSpaces + .where( + (subspace) => + compare(groupKey(subspace.children), childrenKey) < 0, + ) + .length, + ); + }).toIList(); } static final provider = AsyncNotifierProvider>( 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/models/room_order.dart b/lib/models/room_order.dart index c0b5166..b75dab1 100644 --- a/lib/models/room_order.dart +++ b/lib/models/room_order.dart @@ -1 +1 @@ -enum RoomOrder { unreadFirst, recentActivity } +enum RoomOrder { unreadFirst, mentionedFirst, recentActivity } 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/widgets/sidebar/rooms_pane.dart b/lib/widgets/sidebar/rooms_pane.dart index 0c63428..1540f11 100644 --- a/lib/widgets/sidebar/rooms_pane.dart +++ b/lib/widgets/sidebar/rooms_pane.dart @@ -94,41 +94,48 @@ class const RoomsPane({super.key}) extends ConsumerWidget { ), ], ), - if (selectedSpace.children.isNotEmpty) - .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 From 78c6b2ef462d8722f7ef6d5212d1839b8bc9ca5a Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 25 Nov 2026 16:57:33 -0500 Subject: [PATCH 17/53] add sharing support needs more testing --- android/app/src/main/AndroidManifest.xml | 6 + ios/Runner.xcodeproj/project.pbxproj | 209 ++++++++++++++++++ ios/Runner/Info.plist | 9 + ios/Runner/Runner.entitlements | 10 + .../Base.lproj/MainInterface.storyboard | 24 ++ ios/ShareExtension/Info.plist | 41 ++++ .../ShareExtension.entitlements | 10 + ios/ShareExtension/ShareViewController.swift | 5 + lib/controllers/share_request.dart | 39 ++++ lib/models/composer_draft.dart | 4 + lib/widgets/composer/composer.dart | 4 +- lib/widgets/pages/chat.dart | 17 ++ lib/widgets/rooms/share_sheet.dart | 131 +++++++++++ pubspec.lock | 8 + pubspec.yaml | 1 + 15 files changed, 517 insertions(+), 1 deletion(-) create mode 100644 ios/Runner/Runner.entitlements create mode 100644 ios/ShareExtension/Base.lproj/MainInterface.storyboard create mode 100644 ios/ShareExtension/Info.plist create mode 100644 ios/ShareExtension/ShareExtension.entitlements create mode 100644 ios/ShareExtension/ShareViewController.swift create mode 100644 lib/controllers/share_request.dart create mode 100644 lib/widgets/rooms/share_sheet.dart 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 @@ + + + + + + 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..40809ea --- /dev/null +++ b/ios/ShareExtension/ShareViewController.swift @@ -0,0 +1,5 @@ +import receive_sharing_intent + +// Saves what was shared to the App Group, then opens Nexus, which asks which +// room to send it to. See ShareRequestController. +class ShareViewController: RSIShareViewController {} diff --git a/lib/controllers/share_request.dart b/lib/controllers/share_request.dart new file mode 100644 index 0000000..6919167 --- /dev/null +++ b/lib/controllers/share_request.dart @@ -0,0 +1,39 @@ +import "dart:io"; + +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:receive_sharing_intent/receive_sharing_intent.dart"; + +class ShareRequestController extends Notifier?> { + @override + IList? build() { + if (!(Platform.isAndroid || Platform.isIOS)) return null; + + void receive(List files) { + final shared = files + // Android reports opened Matrix links as URLs too, which + // LinkRequestController handles + .where((file) => !(Platform.isAndroid && file.type == .url)) + .toIList(); + if (shared.isNotEmpty) state = shared; + } + + final sharing = ReceiveSharingIntent.instance; + final subscription = sharing.getMediaStream().listen(receive); + ref.onDispose(subscription.cancel); + sharing.getInitialMedia().then(receive).ignore(); + + return null; + } + + void consume() { + state = null; + // So the same share isn't received again once the app is reopened + ReceiveSharingIntent.instance.reset().ignore(); + } + + static final provider = + NotifierProvider?>( + ShareRequestController.new, + ); +} 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/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index d4aaa9f..5f34e35 100644 --- a/lib/widgets/composer/composer.dart +++ b/lib/widgets/composer/composer.dart @@ -94,6 +94,7 @@ class const Composer( :poll, :location, :textCommands, + :textReplacements, ) = ref.watch( draftProvider.select( (draft) => ( @@ -104,6 +105,7 @@ class const Composer( poll: draft.poll, location: draft.location, textCommands: draft.textCommands, + textReplacements: draft.textReplacements, ), ), ); @@ -145,7 +147,7 @@ class const Composer( ]; }, ); - }, [composer, editingEvent, hasReplacement]); + }, [composer, editingEvent, hasReplacement, textReplacements]); useEffect( // After the frame, as FlutterTagger and TextField still use it until then () => 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/rooms/share_sheet.dart b/lib/widgets/rooms/share_sheet.dart new file mode 100644 index 0000000..d0eef1b --- /dev/null +++ b/lib/widgets/rooms/share_sheet.dart @@ -0,0 +1,131 @@ +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"; +import "package:receive_sharing_intent/receive_sharing_intent.dart"; + +class const ShareSheet(final IList files, {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 = files + .where((file) => file.type == .text || file.type == .url) + .map((file) => file.path) + .join("\n"); + final file = files.firstWhereOrNull( + (file) => file.type != .text && file.type != .url, + ); + + 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/pubspec.lock b/pubspec.lock index 644480c..ee3b70e 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1394,6 +1394,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.2.2" + receive_sharing_intent: + dependency: "direct main" + description: + name: receive_sharing_intent + sha256: "72f229a38f2910029c11d840770c173b27072e348ef3376130b37514bc4556f6" + url: "https://pub.dev" + source: hosted + version: "1.9.0" record_use: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index daf702e..464f300 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -120,6 +120,7 @@ dependencies: path: packages/location better_player: 1.38.0 audioplayers: 6.8.1 + receive_sharing_intent: 1.9.0 dev_dependencies: flutter_test: sdk: flutter From 1c533b53305f7c0e17ae1ae5dd367457471cd326 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 00:41:05 -0500 Subject: [PATCH 18/53] notif fixups --- lib/controllers/client.dart | 10 +++++----- lib/controllers/launch_scope.dart | 10 ++++++++++ lib/controllers/notification.dart | 19 ++++++++++++++----- lib/widgets/account_scope.dart | 13 +++++++++---- 4 files changed, 38 insertions(+), 14 deletions(-) create mode 100644 lib/controllers/launch_scope.dart diff --git a/lib/controllers/client.dart b/lib/controllers/client.dart index 3a1ac6c..3ac1d61 100644 --- a/lib/controllers/client.dart +++ b/lib/controllers/client.dart @@ -414,17 +414,17 @@ class ClientController(final String? accountId) extends AsyncNotifier { Future registerPusher(RegisterPusherRequest request) => sendCommand("register_homeserver_push", request.toJson()); - Future deregisterPusher(DeregisterPusherRequest request) => - sendCommand("register_homeserver_push", { - ...request.toJson(), - "kind": null, - }); + Future deregisterPusher(DeregisterPusherRequest request) => sendCommand( + "register_homeserver_push", + {...request.toJson(), "kind": null}, + ); Future uploadMedia(UploadMediaRequest request) async => .fromJson(await sendCommand("upload_media", request.toJson())); Future downloadMedia(DownloadMediaRequest request) async { if (accountId == null && + !isInBackground && ref.read(ClientStateController.provider)?.isLoggedIn != true) { throw StateError("Can't download media while logged out"); } diff --git a/lib/controllers/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 940ff2a..618d849 100644 --- a/lib/controllers/notification.dart +++ b/lib/controllers/notification.dart @@ -6,6 +6,7 @@ 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"; @@ -63,6 +64,17 @@ class NotificationController AndroidFlutterLocalNotificationsPlugin >() ?.deleteNotificationChannel(channelId: "messages"); + + // Taps that launched the app don't reach the callback above + if (!isInBackground && ref.read(LaunchScopeController.provider)) { + if (await notifications.getNotificationAppLaunchDetails() + case NotificationAppLaunchDetails( + didNotificationLaunchApp: true, + notificationResponse: NotificationResponse(:final payload?), + )) { + _open(payload); + } + } } // Reading a room, here or on another client, dismisses its notifications @@ -95,10 +107,8 @@ class NotificationController static String payloadFor(String accountId, int rowId) => "$accountId:$rowId"; - static const _androidGroup = "nexus.federated.nexus.MESSAGES"; - static const _summaryPayload = "summary"; - static const _messagesChannel = "messages_v2"; + static const _androidGroup = "nexus.federated.nexus.MESSAGES"; /// Dismisses the notifications shown for [threadIds]. Future dismiss(ISet threadIds) async { @@ -131,7 +141,6 @@ class NotificationController navigatorKey.currentState?.popUntil((route) => route.isFirst); ref.read(SidebarPageController.provider.notifier).set(.notifications); - // The summary's payload has no row, so it only opens the notifications final (accountId, rowId) = switch (payload.split(":")) { [final accountId, final rowId] => (accountId, int.tryParse(rowId)), // From before notifications were per account @@ -334,7 +343,7 @@ class NotificationController await controller.show( id: 0, title: "Nexus", - payload: _summaryPayload, + payload: payload, notificationDetails: const .new( android: .new( _messagesChannel, 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, From 09f9b56e34594088ce3d479b469abdc1288fa75a Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 00:49:07 -0500 Subject: [PATCH 19/53] fix ios build (hopefully) --- ios/Runner.xcodeproj/project.pbxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index e90cdf3..ebe6013 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -844,7 +844,7 @@ }; 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "receive_sharing_intent" */ = { isa = XCLocalSwiftPackageReference; - relativePath = Flutter/ephemeral/Packages/.packages/receive_sharing_intent; + relativePath = "Flutter/ephemeral/Packages/.packages/receive_sharing_intent-1.9.0"; }; /* End XCLocalSwiftPackageReference section */ From 7bae610c05783c1af38fcd75d3f5381d9d76202b Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 00:55:00 -0500 Subject: [PATCH 20/53] fixup android sharing --- lib/widgets/rooms/share_sheet.dart | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/lib/widgets/rooms/share_sheet.dart b/lib/widgets/rooms/share_sheet.dart index d0eef1b..ecd2df6 100644 --- a/lib/widgets/rooms/share_sheet.dart +++ b/lib/widgets/rooms/share_sheet.dart @@ -1,3 +1,5 @@ +import "dart:io"; + import "package:collection/collection.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:file_selector/file_selector.dart"; @@ -40,13 +42,12 @@ class const ShareSheet(final IList files, {super.key}) (room) => [(room.name, 2), (room.canonicalAlias, 1)], ); - final text = files - .where((file) => file.type == .text || file.type == .url) - .map((file) => file.path) - .join("\n"); - final file = files.firstWhereOrNull( - (file) => file.type != .text && file.type != .url, - ); + bool isText(SharedMediaFile file) => + file.type == .url || + (file.type == .text && !File(file.path).existsSync()); + + final text = files.where(isText).map((file) => file.path).join("\n"); + final file = files.firstWhereOrNull((file) => !isText(file)); Future shareTo(String roomId) async { final container = ProviderScope.containerOf(context); From 77f06005e5cbce5b789cfce67046f63c86aec92f Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 01:06:47 -0500 Subject: [PATCH 21/53] swap sharing library, simplify code --- ios/Runner.xcodeproj/project.pbxproj | 30 ++++++++++---------- ios/ShareExtension/ShareViewController.swift | 4 +-- lib/controllers/share_request.dart | 30 ++++++++------------ lib/widgets/rooms/share_sheet.dart | 15 ++++------ pubspec.lock | 16 +++++------ pubspec.yaml | 2 +- 6 files changed, 43 insertions(+), 54 deletions(-) diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index ebe6013..0fe5f5c 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -19,7 +19,7 @@ 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 /* receive-sharing-intent in Frameworks */ = {isa = PBXBuildFile; productRef = 5A4E00000000000000000015 /* receive-sharing-intent */; }; + 5A4E0000000000000000000B /* better-share-handler-models in Frameworks */ = {isa = PBXBuildFile; productRef = 5A4E00000000000000000015 /* better-share-handler-models */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -109,7 +109,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5A4E0000000000000000000B /* receive-sharing-intent in Frameworks */, + 5A4E0000000000000000000B /* better-share-handler-models in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -245,7 +245,7 @@ ); name = ShareExtension; packageProductDependencies = ( - 5A4E00000000000000000015 /* receive-sharing-intent */, + 5A4E00000000000000000015 /* better-share-handler-models */, ); productName = ShareExtension; productReference = 5A4E00000000000000000005 /* ShareExtension.appex */; @@ -285,7 +285,7 @@ mainGroup = 97C146E51CF9000F007C117D; packageReferences = ( 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, - 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "receive_sharing_intent" */, + 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "better_share_handler" */, ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; @@ -474,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; @@ -602,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; @@ -653,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; @@ -721,7 +721,7 @@ DEVELOPMENT_TEAM = PK66NJM372; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = ShareExtension/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -748,7 +748,7 @@ DEVELOPMENT_TEAM = PK66NJM372; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = ShareExtension/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -775,7 +775,7 @@ DEVELOPMENT_TEAM = PK66NJM372; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = ShareExtension/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -842,9 +842,9 @@ isa = XCLocalSwiftPackageReference; relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; }; - 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "receive_sharing_intent" */ = { + 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "better_share_handler" */ = { isa = XCLocalSwiftPackageReference; - relativePath = "Flutter/ephemeral/Packages/.packages/receive_sharing_intent-1.9.0"; + relativePath = "Flutter/ephemeral/Packages/.packages/better_share_handler-1.1.1"; }; /* End XCLocalSwiftPackageReference section */ @@ -853,10 +853,10 @@ isa = XCSwiftPackageProductDependency; productName = FlutterGeneratedPluginSwiftPackage; }; - 5A4E00000000000000000015 /* receive-sharing-intent */ = { + 5A4E00000000000000000015 /* better-share-handler-models */ = { isa = XCSwiftPackageProductDependency; - package = 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "receive_sharing_intent" */; - productName = "receive-sharing-intent"; + package = 5A4E00000000000000000014 /* XCLocalSwiftPackageReference "better_share_handler" */; + productName = "better-share-handler-models"; }; /* End XCSwiftPackageProductDependency section */ }; diff --git a/ios/ShareExtension/ShareViewController.swift b/ios/ShareExtension/ShareViewController.swift index 40809ea..76f4931 100644 --- a/ios/ShareExtension/ShareViewController.swift +++ b/ios/ShareExtension/ShareViewController.swift @@ -1,5 +1,5 @@ -import receive_sharing_intent +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: RSIShareViewController {} +class ShareViewController: ShareHandlerIosViewController {} diff --git a/lib/controllers/share_request.dart b/lib/controllers/share_request.dart index 6919167..ce7a9ca 100644 --- a/lib/controllers/share_request.dart +++ b/lib/controllers/share_request.dart @@ -1,27 +1,21 @@ import "dart:io"; -import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:better_share_handler/better_share_handler.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; -import "package:receive_sharing_intent/receive_sharing_intent.dart"; -class ShareRequestController extends Notifier?> { +class ShareRequestController extends Notifier { @override - IList? build() { + SharedMedia? build() { if (!(Platform.isAndroid || Platform.isIOS)) return null; - void receive(List files) { - final shared = files - // Android reports opened Matrix links as URLs too, which - // LinkRequestController handles - .where((file) => !(Platform.isAndroid && file.type == .url)) - .toIList(); - if (shared.isNotEmpty) state = shared; - } - - final sharing = ReceiveSharingIntent.instance; - final subscription = sharing.getMediaStream().listen(receive); + final sharing = ShareHandler.instance; + final subscription = sharing.sharedMediaStream.listen( + (media) => state = media, + ); ref.onDispose(subscription.cancel); - sharing.getInitialMedia().then(receive).ignore(); + sharing.getInitialSharedMedia().then((media) { + if (media != null) state = media; + }).ignore(); return null; } @@ -29,11 +23,11 @@ class ShareRequestController extends Notifier?> { void consume() { state = null; // So the same share isn't received again once the app is reopened - ReceiveSharingIntent.instance.reset().ignore(); + ShareHandler.instance.resetInitialSharedMedia().ignore(); } static final provider = - NotifierProvider?>( + NotifierProvider( ShareRequestController.new, ); } diff --git a/lib/widgets/rooms/share_sheet.dart b/lib/widgets/rooms/share_sheet.dart index ecd2df6..d448194 100644 --- a/lib/widgets/rooms/share_sheet.dart +++ b/lib/widgets/rooms/share_sheet.dart @@ -1,5 +1,4 @@ -import "dart:io"; - +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"; @@ -17,9 +16,8 @@ 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"; -import "package:receive_sharing_intent/receive_sharing_intent.dart"; -class const ShareSheet(final IList files, {super.key}) +class const ShareSheet(final SharedMedia media, {super.key}) extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { @@ -42,12 +40,9 @@ class const ShareSheet(final IList files, {super.key}) (room) => [(room.name, 2), (room.canonicalAlias, 1)], ); - bool isText(SharedMediaFile file) => - file.type == .url || - (file.type == .text && !File(file.path).existsSync()); - - final text = files.where(isText).map((file) => file.path).join("\n"); - final file = files.firstWhereOrNull((file) => !isText(file)); + 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); diff --git a/pubspec.lock b/pubspec.lock index ee3b70e..a9cf736 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: @@ -1394,14 +1402,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.2.2" - receive_sharing_intent: - dependency: "direct main" - description: - name: receive_sharing_intent - sha256: "72f229a38f2910029c11d840770c173b27072e348ef3376130b37514bc4556f6" - url: "https://pub.dev" - source: hosted - version: "1.9.0" record_use: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 464f300..3407eae 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -120,7 +120,7 @@ dependencies: path: packages/location better_player: 1.38.0 audioplayers: 6.8.1 - receive_sharing_intent: 1.9.0 + better_share_handler: 1.1.1 dev_dependencies: flutter_test: sdk: flutter From cba13aa6c723f36b1bb309e8a65b5d2298313bd6 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 10:53:00 -0500 Subject: [PATCH 22/53] fixup room selected fallbacks --- lib/controllers/selected_room.dart | 11 +++++++++-- lib/widgets/sidebar/spaces_rail.dart | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) 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/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( From 1e25cbf822077edb4556e70fcfd8327ddf046a81 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 11:29:21 -0500 Subject: [PATCH 23/53] adjust emoji search placeholder --- lib/widgets/emoji/emoji_picker.dart | 1 + 1 file changed, 1 insertion(+) 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, From dcb160556eaa11250aa84921b5bc94736c0ff181 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 11:38:04 -0500 Subject: [PATCH 24/53] add space order option to room ordering Fixes #185 --- lib/controllers/settings_sections.dart | 3 +- lib/controllers/spaces.dart | 89 ++++++++++++++------------ lib/models/room_order.dart | 2 +- lib/models/space_edge.dart | 2 + 4 files changed, 54 insertions(+), 42 deletions(-) diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index 1bd7e3a..3d61cae 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -256,7 +256,7 @@ class SettingsSectionsController ), .new( title: "Room Ordering", - description: "Sort rooms and subspaces by recent activity, optionally showing mentioned or unread ones first.", + description: "Sort rooms by recent activity, optionally showing mentioned or unread ones first, or keep the order their space sets.", icon: Icons.sort, builder: (title, description, icon) => DialogListTile( icon: Icon(icon), @@ -268,6 +268,7 @@ class SettingsSectionsController .unreadFirst => "Mentioned, then unread", .mentionedFirst => "Mentioned only", .recentActivity => "Recent activity only", + .spaceOrder => "Space order", }, onChanged: (value) => ref .read(SettingsController.provider.notifier) diff --git a/lib/controllers/spaces.dart b/lib/controllers/spaces.dart index 1591625..72a4205 100644 --- a/lib/controllers/spaces.dart +++ b/lib/controllers/spaces.dart @@ -10,6 +10,7 @@ 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"; class SpacesController extends AsyncNotifier> { @@ -20,9 +21,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 @@ -70,6 +89,10 @@ class SpacesController extends AsyncNotifier> { ) .nonNulls, ), + childrenIndex: directChildrenIds + .where(rooms.containsKey) + .takeWhile(childrenById.containsKey) + .length, ); } @@ -140,7 +163,7 @@ class SpacesController extends AsyncNotifier> { ); int priority(Room room) => switch ((roomOrder, room.metadata)) { - (.recentActivity, _) => 0, + (.recentActivity || .spaceOrder, _) => 0, (_, RoomMetadata(unreadHighlights: > 0)) => 0, (.mentionedFirst, _) => 1, (.unreadFirst, RoomMetadata(unreadNotifications: > 0)) || @@ -150,46 +173,32 @@ class SpacesController extends AsyncNotifier> { DateTime activity(Room room) => room.metadata?.sortingTimestamp ?? .new(0); // Higher priority first, then most recent activity first - int compare( - ({int priority, DateTime activity}) a, - ({int priority, DateTime activity}) b, - ) => switch (a.priority.compareTo(b.priority)) { - 0 => b.activity.compareTo(a.activity), - final byPriority => byPriority, - }; - - ({int priority, DateTime activity}) roomKey(Room room) => - (priority: priority(room), activity: activity(room)); - - ({int priority, DateTime activity}) groupKey(IList rooms) => ( - priority: rooms.map(priority).minOrNull ?? 2, - activity: rooms.map(activity).maxOrNull ?? .new(0), + IList sortRooms(IList rooms) => rooms.sort( + (a, b) => switch (priority(a).compareTo(priority(b))) { + 0 => activity(b).compareTo(activity(a)), + final byPriority => byPriority, + }, ); - IList sortRooms(IList rooms) => - rooms.sort((a, b) => compare(roomKey(a), roomKey(b))); + IList orderRooms(Space space, IList rooms) => + roomOrder == .spaceOrder && space.room != null + ? rooms + : sortRooms(rooms); - return allSpaces.map((space) { - final subSpaces = space.subSpaces - .map( - (subspace) => - subspace.copyWith(children: sortRooms(subspace.children)), - ) - .toIList() - .sort((a, b) => compare(groupKey(a.children), groupKey(b.children))); - - final childrenKey = groupKey(space.children); - return space.copyWith( - children: sortRooms(space.children), - subSpaces: subSpaces, - childrenIndex: subSpaces - .where( - (subspace) => - compare(groupKey(subspace.children), childrenKey) < 0, - ) - .length, - ); - }).toIList(); + return .new( + allSpaces.map( + (space) => space.copyWith( + children: orderRooms(space, space.children), + subSpaces: .new( + space.subSpaces.map( + (subspace) => subspace.copyWith( + children: orderRooms(space, subspace.children), + ), + ), + ), + ), + ), + ); } static final provider = AsyncNotifierProvider>( diff --git a/lib/models/room_order.dart b/lib/models/room_order.dart index b75dab1..dc371f6 100644 --- a/lib/models/room_order.dart +++ b/lib/models/room_order.dart @@ -1 +1 @@ -enum RoomOrder { unreadFirst, mentionedFirst, recentActivity } +enum RoomOrder { unreadFirst, mentionedFirst, recentActivity, spaceOrder } 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); From 701024b5f6831e71859dd66abf65b82f84c53673 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 11:49:33 -0500 Subject: [PATCH 25/53] fixup subspace ordering --- lib/controllers/settings_sections.dart | 2 +- lib/controllers/spaces.dart | 55 +++++++++++++++++--------- 2 files changed, 38 insertions(+), 19 deletions(-) diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index 3d61cae..6ad29c7 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -256,7 +256,7 @@ class SettingsSectionsController ), .new( title: "Room Ordering", - description: "Sort rooms by recent activity, optionally showing mentioned or unread ones first, or keep the order their space sets.", + description: "Sort rooms and subspaces by recent activity, optionally showing mentioned or unread ones first, or keep the order their space sets.", icon: Icons.sort, builder: (title, description, icon) => DialogListTile( icon: Icon(icon), diff --git a/lib/controllers/spaces.dart b/lib/controllers/spaces.dart index 72a4205..d0b2b23 100644 --- a/lib/controllers/spaces.dart +++ b/lib/controllers/spaces.dart @@ -173,31 +173,50 @@ class SpacesController extends AsyncNotifier> { DateTime activity(Room room) => room.metadata?.sortingTimestamp ?? .new(0); // Higher priority first, then most recent activity first - IList sortRooms(IList rooms) => rooms.sort( - (a, b) => switch (priority(a).compareTo(priority(b))) { - 0 => activity(b).compareTo(activity(a)), - final byPriority => byPriority, - }, + int compare( + ({int priority, DateTime activity}) a, + ({int priority, DateTime activity}) b, + ) => switch (a.priority.compareTo(b.priority)) { + 0 => b.activity.compareTo(a.activity), + final byPriority => byPriority, + }; + + ({int priority, DateTime activity}) roomKey(Room room) => + (priority: priority(room), activity: activity(room)); + + ({int priority, DateTime activity}) groupKey(IList rooms) => ( + priority: rooms.map(priority).minOrNull ?? 2, + activity: rooms.map(activity).maxOrNull ?? .new(0), ); - IList orderRooms(Space space, IList rooms) => - roomOrder == .spaceOrder && space.room != null - ? rooms - : sortRooms(rooms); + IList sortRooms(IList rooms) => + rooms.sort((a, b) => compare(roomKey(a), roomKey(b))); return .new( - allSpaces.map( - (space) => space.copyWith( - children: orderRooms(space, space.children), + allSpaces.map((space) { + if (roomOrder == .spaceOrder && space.room != null) return space; + + final subSpaces = space.subSpaces.sort( + (a, b) => compare(groupKey(a.children), groupKey(b.children)), + ); + + final childrenKey = groupKey(space.children); + return space.copyWith( + children: sortRooms(space.children), subSpaces: .new( - space.subSpaces.map( - (subspace) => subspace.copyWith( - children: orderRooms(space, subspace.children), - ), + subSpaces.map( + (subspace) => + subspace.copyWith(children: sortRooms(subspace.children)), ), ), - ), - ), + childrenIndex: subSpaces + .where( + (subspace) => + compare(groupKey(subspace.children), childrenKey) < 0, + ) + .length, + ); + }), ); } From f6b9deee86eea3483fda6e75fbb2bb5d2d154319 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 12:54:16 -0500 Subject: [PATCH 26/53] update ordering settings --- lib/controllers/settings_sections.dart | 9 +-- lib/controllers/spaces.dart | 81 ++++++++++++++------------ lib/models/room_order.dart | 7 ++- lib/models/settings.dart | 1 + 4 files changed, 56 insertions(+), 42 deletions(-) diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index 6ad29c7..092d49c 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -256,7 +256,7 @@ class SettingsSectionsController ), .new( title: "Room Ordering", - description: "Sort rooms and subspaces by recent activity, optionally showing mentioned or unread ones first, or keep the order their space sets.", + 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,10 +265,11 @@ class SettingsSectionsController value: settings.roomOrder, options: RoomOrder.values, getName: (option) => switch (option) { - .unreadFirst => "Mentioned, then unread", - .mentionedFirst => "Mentioned only", + .unreadFirst => "Mentioned, then unread, then recent", + .unreadFirstSpaceOrder => + "Mentioned, then unread, then space order", .recentActivity => "Recent activity only", - .spaceOrder => "Space order", + .spaceOrder => "Space order only", }, onChanged: (value) => ref .read(SettingsController.provider.notifier) diff --git a/lib/controllers/spaces.dart b/lib/controllers/spaces.dart index d0b2b23..07e1fd7 100644 --- a/lib/controllers/spaces.dart +++ b/lib/controllers/spaces.dart @@ -13,6 +13,8 @@ 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 { @@ -162,58 +164,63 @@ class SpacesController extends AsyncNotifier> { SettingsController.provider.selectAsync((data) => data.roomOrder), ); - int priority(Room room) => switch ((roomOrder, room.metadata)) { - (.recentActivity || .spaceOrder, _) => 0, - (_, RoomMetadata(unreadHighlights: > 0)) => 0, - (.mentionedFirst, _) => 1, - (.unreadFirst, RoomMetadata(unreadNotifications: > 0)) || - (.unreadFirst, RoomMetadata(unreadMessages: > 0)) => 1, - (.unreadFirst, _) => 2, + 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); - // Higher priority first, then most recent activity first - int compare( - ({int priority, DateTime activity}) a, - ({int priority, DateTime activity}) b, - ) => switch (a.priority.compareTo(b.priority)) { - 0 => b.activity.compareTo(a.activity), - final byPriority => byPriority, - }; - - ({int priority, DateTime activity}) roomKey(Room room) => - (priority: priority(room), activity: activity(room)); - - ({int priority, DateTime activity}) groupKey(IList rooms) => ( - priority: rooms.map(priority).minOrNull ?? 2, - activity: rooms.map(activity).maxOrNull ?? .new(0), - ); - - IList sortRooms(IList rooms) => - rooms.sort((a, b) => compare(roomKey(a), roomKey(b))); - return .new( allSpaces.map((space) { - if (roomOrder == .spaceOrder && space.room != null) return 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, + }; - final subSpaces = space.subSpaces.sort( - (a, b) => compare(groupKey(a.children), groupKey(b.children)), + _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, ); - final childrenKey = groupKey(space.children); + 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( - (subspace) => - subspace.copyWith(children: sortRooms(subspace.children)), + (entry) => entry.subspace.copyWith( + children: sortRooms(entry.subspace.children), + ), ), ), childrenIndex: subSpaces - .where( - (subspace) => - compare(groupKey(subspace.children), childrenKey) < 0, - ) + .where((entry) => compare(entry.key, childrenKey) < 0) .length, ); }), diff --git a/lib/models/room_order.dart b/lib/models/room_order.dart index dc371f6..b9cf46c 100644 --- a/lib/models/room_order.dart +++ b/lib/models/room_order.dart @@ -1 +1,6 @@ -enum RoomOrder { unreadFirst, mentionedFirst, recentActivity, spaceOrder } +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/settings.dart b/lib/models/settings.dart index 79c3d64..4b34fd5 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -19,6 +19,7 @@ class const Settings({ final bool swipeToReply = false, final bool hideMembershipEvents = false, final bool hideServerAclEvents = true, + @JsonKey(unknownEnumValue: RoomOrder.unreadFirst) final RoomOrder roomOrder = .unreadFirst, final NameColor nameColor = .powerLevel, final ShowAndSend typingIndicators = .showAndSend, From 69f175babe00f5f272413f660ff922a0f3e8760e Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 13:50:20 -0500 Subject: [PATCH 27/53] replace deprecated field in build hook --- hook/build.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hook/build.dart b/hook/build.dart index c4af12e..9b25cac 100644 --- a/hook/build.dart +++ b/hook/build.dart @@ -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: From 8d4745cc1230d842a788d2cf524e497bdf526db5 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 14:31:24 -0500 Subject: [PATCH 28/53] add the ability to change your profile per-room Fixes #177 --- lib/controllers/client.dart | 44 +++++++++- lib/controllers/room_profile.dart | 101 ++++++++++++++++++++++ lib/widgets/avatars/editable_avatar.dart | 4 + lib/widgets/rooms/room_menu_button.dart | 10 +++ lib/widgets/users/room_profile_sheet.dart | 77 +++++++++++++++++ 5 files changed, 232 insertions(+), 4 deletions(-) create mode 100644 lib/controllers/room_profile.dart create mode 100644 lib/widgets/users/room_profile_sheet.dart diff --git a/lib/controllers/client.dart b/lib/controllers/client.dart index 3ac1d61..f391ce5 100644 --- a/lib/controllers/client.dart +++ b/lib/controllers/client.dart @@ -36,6 +36,7 @@ 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/requests/get_space_hierarchy.dart"; import "package:nexus/models/requests/get_room_directory.dart"; import "package:nexus/models/requests/get_threads.dart"; @@ -336,15 +337,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 { 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/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/rooms/room_menu_button.dart b/lib/widgets/rooms/room_menu_button.dart index 22d94f9..4bfa840 100644 --- a/lib/widgets/rooms/room_menu_button.dart +++ b/lib/widgets/rooms/room_menu_button.dart @@ -10,6 +10,7 @@ import "package:nexus/controllers/client.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"; @@ -168,6 +169,15 @@ final class const RoomMenuButton( title: Text("Invite"), ), ), + PopupMenuItem( + onTap: () => context.showAdaptiveSheet( + (_) => RoomProfileSheet(room!.metadata!.id), + ), + child: ListTile( + leading: Icon(Icons.manage_accounts), + title: Text("Room Profile"), + ), + ), PopupMenuItem( onTap: () => showDialog( context: context, 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, + ), + ), + ], + ); + }, + ), + ], + ); + } +} From 79d556a8303cf6458a6a7675222933799a98609c Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 14:41:58 -0500 Subject: [PATCH 29/53] add account management page Fixes #176 --- lib/controllers/account_management.dart | 24 +++++++ lib/controllers/client.dart | 32 +++++----- lib/controllers/settings_sections.dart | 62 ++++++++++++++++++- lib/models/account_management.dart | 19 ++++++ .../encryption/recovery_key_sheet.dart | 15 ++--- 5 files changed, 122 insertions(+), 30 deletions(-) create mode 100644 lib/controllers/account_management.dart create mode 100644 lib/models/account_management.dart 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/client.dart b/lib/controllers/client.dart index f391ce5..b7b8ffd 100644 --- a/lib/controllers/client.dart +++ b/lib/controllers/client.dart @@ -37,6 +37,7 @@ 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"; @@ -281,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"]; diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index 092d49c..56bc4c6 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -9,6 +9,7 @@ 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 +25,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"; @@ -50,6 +52,40 @@ class SettingsSectionsController @override Future>> build() async { final settings = await ref.watch(SettingsController.provider.future); + // 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 colorScheme = Theme.of(context).colorScheme; + return M3EButton.icon( + onPressed: () => ref.read(LaunchHelper.provider).launchUrl(url), + label: Text(title), + icon: Icon(icon), + tooltip: description, + decoration: danger + ? .styleFrom( + backgroundColor: colorScheme.error, + foregroundColor: colorScheme.onError, + ) + : null, + ); + }, + ), + ); // Loads the enabled packs' state, so they can be shown ref.watch(EnabledImagePacksController.provider); @@ -793,9 +829,23 @@ 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.", @@ -811,6 +861,14 @@ class SettingsSectionsController ), 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/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/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; From 6e3bc596fd0cd6257965cbb6cde856677b9ed66d Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 15:00:51 -0500 Subject: [PATCH 30/53] clean up account management settings --- lib/controllers/settings_sections.dart | 33 ++++++++++++-------------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index 56bc4c6..f55a228 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -5,7 +5,6 @@ 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"; @@ -70,18 +69,15 @@ class SettingsSectionsController icon: icon, builder: (title, description, icon) => Builder( builder: (context) { - final colorScheme = Theme.of(context).colorScheme; - return M3EButton.icon( - onPressed: () => ref.read(LaunchHelper.provider).launchUrl(url), - label: Text(title), - icon: Icon(icon), - tooltip: description, - decoration: danger - ? .styleFrom( - backgroundColor: colorScheme.error, - foregroundColor: colorScheme.onError, - ) - : null, + 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), ); }, ), @@ -850,13 +846,14 @@ class SettingsSectionsController 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, From f80ceb0736b9e438aad7bfca705f83b90913de69 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 15:10:08 -0500 Subject: [PATCH 31/53] don't pass `is_avatar` for avatars This is because Gomuks will not give AVIFs back for avatars./ --- lib/controllers/unified_push.dart | 14 ++++++++------ lib/models/requests/download_media.dart | 2 -- lib/widgets/avatars/avatar_or_hash.dart | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/controllers/unified_push.dart b/lib/controllers/unified_push.dart index ec1e7e1..1fa3a2e 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) 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/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, From 3b7a4c0cd4b771ca5b0e2ef4c04427efd7acc0d5 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 15:31:38 -0500 Subject: [PATCH 32/53] add PMP support Fixes #175 --- lib/controllers/account_data.dart | 36 ++++++ lib/controllers/personas.dart | 56 +++++++++ lib/controllers/rooms.dart | 1 + lib/controllers/settings_sections.dart | 97 ++++++++++++++++ lib/models/account_data.dart | 4 + lib/models/per_message_profiles.dart | 48 ++++++++ lib/models/room.dart | 13 ++- lib/models/settings.dart | 1 + lib/widgets/composer/composer.dart | 2 + lib/widgets/composer/persona_button.dart | 74 ++++++++++++ lib/widgets/settings/persona_sheet.dart | 138 +++++++++++++++++++++++ 11 files changed, 469 insertions(+), 1 deletion(-) create mode 100644 lib/controllers/personas.dart create mode 100644 lib/models/per_message_profiles.dart create mode 100644 lib/widgets/composer/persona_button.dart create mode 100644 lib/widgets/settings/persona_sheet.dart diff --git a/lib/controllers/account_data.dart b/lib/controllers/account_data.dart index 62997b5..13b5d81 100644 --- a/lib/controllers/account_data.dart +++ b/lib/controllers/account_data.dart @@ -5,6 +5,8 @@ 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/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 +75,40 @@ 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) async { + const type = AccountData.perMessageProfilesKey; + final current = ref + .read(RoomsController.provider)[roomId] + ?.accountData[type]; + + await ref + .read(ClientController.provider.notifier) + .setAccountData( + .new( + type: type, + roomId: roomId, + content: {...?current, "default_profile_id": profileId}, + ), + ); + await ref + .read(RoomsController.provider.notifier) + .awaitRooms( + (rooms) => + rooms[roomId]?.accountData[type]?["default_profile_id"] == + 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/personas.dart b/lib/controllers/personas.dart new file mode 100644 index 0000000..bc3073f --- /dev/null +++ b/lib/controllers/personas.dart @@ -0,0 +1,56 @@ +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/rooms.dart"; +import "package:nexus/models/account_data.dart"; +import "package:nexus/models/per_message_profiles.dart"; + +typedef RoomPersonas = ({ + IList profiles, + StoredProfile? current, +}); + +class PersonasController(final String roomId) extends Notifier { + @override + RoomPersonas 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), + ), + ); + + final currentId = room?.defaultProfileId ?? global.defaultProfileId; + return ( + profiles: profiles, + current: currentId == null || currentId.isEmpty + ? null + : profiles.firstWhereOrNull((profile) => profile.id == currentId), + ); + } + + static final provider = NotifierProvider.autoDispose + .family(PersonasController.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/settings_sections.dart b/lib/controllers/settings_sections.dart index f55a228..e2ea8a1 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -43,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/persona_sheet.dart"; import "package:nexus/widgets/users/user_bottom_sheet.dart"; import "package:nexus/widgets/encryption/reset_encryption_sheet.dart"; @@ -51,6 +52,9 @@ class SettingsSectionsController @override Future>> build() async { final settings = await ref.watch(SettingsController.provider.future); + final personas = 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) @@ -443,6 +447,99 @@ class SettingsSectionsController ), ]), ), + .new( + title: "Personas", + icon: Icons.groups, + settings: .new([ + .new( + title: "Enable Personas", + 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.personas, + onChanged: (value) => ref + .read(SettingsController.provider.notifier) + .set(settings.copyWith(personas: value)) + .onError(showError), + ), + ), + if (settings.personas) ...[ + if (personas.profiles.isNotEmpty) + .new( + title: "Default Persona", + description: "Who you send as in rooms you haven't chosen a persona for.", + icon: Icons.person_pin, + builder: (title, description, icon) => + DialogListTile( + icon: Icon(icon), + title: title, + subtitle: Text(description), + value: personas.defaultProfileId ?? "", + options: [ + "", + ...personas.profiles.map((profile) => profile.id), + ], + getName: (id) => switch (personas.byId(id)) { + final profile? => profile.displayName ?? id, + null => "Yourself", + }, + onChanged: (id) => accountData + .setPerMessageProfiles( + personas.copyWith( + defaultProfileId: id.isEmpty ? null : id, + ), + ) + .onError(showError), + ), + ), + header( + "Personas", + "The names and avatars you can send messages as.", + Icons.groups, + ), + ...personas.profiles.map( + (persona) => Setting( + title: persona.displayName ?? persona.id, + description: "A persona.", + icon: Icons.person, + builder: (title, _, _) => Builder( + builder: (context) => ListTile( + leading: AvatarOrHash(persona.avatarUrl, title), + title: Text(title), + subtitle: switch (persona.triggers.firstOrNull) { + final trigger? => Text( + "Trigger: ${trigger.prefix}text${trigger.suffix}", + ), + null => null, + }, + trailing: Icon(Icons.chevron_right), + onTap: () => context.showAdaptiveSheet( + (_) => PersonaSheet(persona: persona), + ), + ), + ), + ), + ), + .new( + title: "Add Persona", + 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 PersonaSheet(), + ), + ), + ), + ), + ], + ]), + ), .new( title: "Image Packs", icon: Icons.emoji_emotions, 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/per_message_profiles.dart b/lib/models/per_message_profiles.dart new file mode 100644 index 0000000..7de8398 --- /dev/null +++ b/lib/models/per_message_profiles.dart @@ -0,0 +1,48 @@ +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 { + Map toJson() => _$ProfileTriggerToJson(this); + + factory ProfileTrigger.fromJson(Map json) => + _$ProfileTriggerFromJson(json); +} 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/settings.dart b/lib/models/settings.dart index 4b34fd5..923ee5f 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -23,6 +23,7 @@ class const Settings({ final RoomOrder roomOrder = .unreadFirst, final NameColor nameColor = .powerLevel, final ShowAndSend typingIndicators = .showAndSend, + final bool personas = 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/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index 5f34e35..96ed001 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/persona_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"; @@ -565,6 +566,7 @@ class const Composer( ), ) ? [ + PersonaButton(roomId), IconButton( onPressed: hasReplacement ? null diff --git a/lib/widgets/composer/persona_button.dart b/lib/widgets/composer/persona_button.dart new file mode 100644 index 0000000..960a525 --- /dev/null +++ b/lib/widgets/composer/persona_button.dart @@ -0,0 +1,74 @@ +import "package:flutter_riverpod/flutter_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/controllers/personas.dart"; +import "package:nexus/controllers/settings.dart"; +import "package:nexus/main.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; + +/// Chooses the persona messages are sent as in [roomId], if personas are on. +class const PersonaButton(final String roomId, {super.key}) + extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final enabled = ref.watch( + SettingsController.provider.select( + (settings) => settings.value?.personas ?? false, + ), + ); + final (:profiles, :current) = ref.watch( + PersonasController.provider(roomId), + ); + if (!enabled || profiles.isEmpty) return const SizedBox.shrink(); + + Future choose(String profileId) => ref + .read(AccountDataController.provider.notifier) + .setRoomProfile(roomId, profileId) + .onError(showError); + + PopupMenuItem item({ + required String id, + required Widget leading, + required String title, + }) { + final selected = (current?.id ?? "") == id; + return PopupMenuItem( + onTap: () => choose(id), + child: ListTile( + selected: selected, + leading: leading, + title: Text(title), + trailing: selected ? Icon(Icons.check) : null, + ), + ); + } + + return AdaptiveMenuButton( + tooltip: switch (current) { + final current? => "Sending as ${current.displayName ?? current.id}", + null => "Choose persona", + }, + icon: switch (current) { + final current? => AvatarOrHash( + current.avatarUrl, + current.displayName ?? current.id, + ), + null => Icon(Icons.person), + }, + itemBuilder: (_) => [ + item(id: "", leading: Icon(Icons.person), title: "Yourself"), + ...profiles.map( + (profile) => item( + id: profile.id, + leading: AvatarOrHash( + profile.avatarUrl, + profile.displayName ?? profile.id, + ), + title: profile.displayName ?? profile.id, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/settings/persona_sheet.dart b/lib/widgets/settings/persona_sheet.dart new file mode 100644 index 0000000..d88aaf3 --- /dev/null +++ b/lib/widgets/settings/persona_sheet.dart @@ -0,0 +1,138 @@ +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 PersonaSheet({final StoredProfile? persona, super.key}) + extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final saving = Saving.use(); + final trigger = persona?.triggers.firstOrNull; + final nameController = useTextEditingController(text: persona?.displayName); + final prefixController = useTextEditingController(text: trigger?.prefix); + final suffixController = useTextEditingController(text: trigger?.suffix); + final avatar = useState(persona?.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: + persona?.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), + ...?persona?.triggers.skip(1), + ]), + ); + final profiles = current(); + + return update( + profiles.copyWith( + profiles: persona == null + ? profiles.profiles.add(edited) + : profiles.profiles.replaceFirstWhere( + (profile) => profile.id == persona!.id, + (_) => edited, + ), + ), + ).onError(showError); + } + + Future delete() { + final profiles = current(); + return update( + profiles.copyWith( + profiles: profiles.profiles.removeWhere( + (profile) => profile.id == persona!.id, + ), + defaultProfileId: profiles.defaultProfileId == persona!.id + ? null + : profiles.defaultProfileId, + ), + ).onError(showError); + } + + return SheetLayout( + title: Text(persona == null ? "Add Persona" : "Edit Persona"), + actions: [ + if (persona != 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 ? "Persona" : name, + dimension: 120, + ), + ), + ), + TextField( + controller: nameController, + autofocus: persona == 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 persona, 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"), + ), + ), + ], + ), + ], + ); + } +} From 4800123044ea338498c1fae4a03e8ce0f6fa0506 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 15:50:57 -0500 Subject: [PATCH 33/53] tweak PMP support --- .vscode/settings.json | 4 +- lib/controllers/settings_sections.dart | 52 ++++++++++--------- .../{personas.dart => subprofiles.dart} | 11 ++-- lib/models/settings.dart | 2 +- lib/widgets/composer/composer.dart | 4 +- ...ona_button.dart => subprofile_button.dart} | 14 ++--- .../lazy_loading/message_displayname.dart | 3 +- ...rsona_sheet.dart => subprofile_sheet.dart} | 32 ++++++------ lib/widgets/users/user_span.dart | 8 ++- 9 files changed, 69 insertions(+), 61 deletions(-) rename lib/controllers/{personas.dart => subprofiles.dart} (86%) rename lib/widgets/composer/{persona_button.dart => subprofile_button.dart} (82%) rename lib/widgets/settings/{persona_sheet.dart => subprofile_sheet.dart} (81%) 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/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index e2ea8a1..c084b9b 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -43,7 +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/persona_sheet.dart"; +import "package:nexus/widgets/settings/subprofile_sheet.dart"; import "package:nexus/widgets/users/user_bottom_sheet.dart"; import "package:nexus/widgets/encryption/reset_encryption_sheet.dart"; @@ -52,7 +52,7 @@ class SettingsSectionsController @override Future>> build() async { final settings = await ref.watch(SettingsController.provider.future); - final personas = ref.watch( + final subprofiles = ref.watch( AccountDataController.provider.select((data) => data.perMessageProfiles), ); // Not awaited, so a slow homeserver doesn't hold up the rest of settings @@ -448,47 +448,49 @@ class SettingsSectionsController ]), ), .new( - title: "Personas", + title: "Subprofiles", icon: Icons.groups, settings: .new([ .new( - title: "Enable Personas", + 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.personas, + value: settings.subprofiles, onChanged: (value) => ref .read(SettingsController.provider.notifier) - .set(settings.copyWith(personas: value)) + .set(settings.copyWith(subprofiles: value)) .onError(showError), ), ), - if (settings.personas) ...[ - if (personas.profiles.isNotEmpty) + if (settings.subprofiles) ...[ + if (subprofiles.profiles.isNotEmpty) .new( - title: "Default Persona", - description: "Who you send as in rooms you haven't chosen a persona for.", + 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: personas.defaultProfileId ?? "", + value: subprofiles.defaultProfileId ?? "", options: [ "", - ...personas.profiles.map((profile) => profile.id), + ...subprofiles.profiles.map( + (profile) => profile.id, + ), ], - getName: (id) => switch (personas.byId(id)) { + getName: (id) => switch (subprofiles.byId(id)) { final profile? => profile.displayName ?? id, - null => "Yourself", + null => "Account Profile", }, onChanged: (id) => accountData .setPerMessageProfiles( - personas.copyWith( + subprofiles.copyWith( defaultProfileId: id.isEmpty ? null : id, ), ) @@ -496,20 +498,20 @@ class SettingsSectionsController ), ), header( - "Personas", + "Subprofiles", "The names and avatars you can send messages as.", Icons.groups, ), - ...personas.profiles.map( - (persona) => Setting( - title: persona.displayName ?? persona.id, - description: "A persona.", + ...subprofiles.profiles.map( + (subprofile) => Setting( + title: subprofile.displayName ?? subprofile.id, + description: "A subprofile.", icon: Icons.person, builder: (title, _, _) => Builder( builder: (context) => ListTile( - leading: AvatarOrHash(persona.avatarUrl, title), + leading: AvatarOrHash(subprofile.avatarUrl, title), title: Text(title), - subtitle: switch (persona.triggers.firstOrNull) { + subtitle: switch (subprofile.triggers.firstOrNull) { final trigger? => Text( "Trigger: ${trigger.prefix}text${trigger.suffix}", ), @@ -517,14 +519,14 @@ class SettingsSectionsController }, trailing: Icon(Icons.chevron_right), onTap: () => context.showAdaptiveSheet( - (_) => PersonaSheet(persona: persona), + (_) => SubprofileSheet(subprofile: subprofile), ), ), ), ), ), .new( - title: "Add Persona", + title: "Add Subprofile", description: "Create a name and avatar to send messages as.", icon: Icons.add, builder: (title, _, icon) => Builder( @@ -532,7 +534,7 @@ class SettingsSectionsController leading: Icon(icon), title: Text(title), onTap: () => context.showAdaptiveSheet( - (_) => const PersonaSheet(), + (_) => const SubprofileSheet(), ), ), ), diff --git a/lib/controllers/personas.dart b/lib/controllers/subprofiles.dart similarity index 86% rename from lib/controllers/personas.dart rename to lib/controllers/subprofiles.dart index bc3073f..70f6e05 100644 --- a/lib/controllers/personas.dart +++ b/lib/controllers/subprofiles.dart @@ -7,14 +7,15 @@ import "package:nexus/controllers/rooms.dart"; import "package:nexus/models/account_data.dart"; import "package:nexus/models/per_message_profiles.dart"; -typedef RoomPersonas = ({ +typedef RoomSubprofiles = ({ IList profiles, StoredProfile? current, }); -class PersonasController(final String roomId) extends Notifier { +class SubprofilesController(final String roomId) + extends Notifier { @override - RoomPersonas build() { + RoomSubprofiles build() { final global = ref.watch( AccountDataController.provider.select((data) => data.perMessageProfiles), ); @@ -52,5 +53,7 @@ class PersonasController(final String roomId) extends Notifier { } static final provider = NotifierProvider.autoDispose - .family(PersonasController.new); + .family( + SubprofilesController.new, + ); } diff --git a/lib/models/settings.dart b/lib/models/settings.dart index 923ee5f..ffad23b 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -23,7 +23,7 @@ class const Settings({ final RoomOrder roomOrder = .unreadFirst, final NameColor nameColor = .powerLevel, final ShowAndSend typingIndicators = .showAndSend, - final bool personas = false, + final bool subprofiles = 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/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index 96ed001..bd4a3de 100644 --- a/lib/widgets/composer/composer.dart +++ b/lib/widgets/composer/composer.dart @@ -3,7 +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/persona_button.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"; @@ -566,7 +566,7 @@ class const Composer( ), ) ? [ - PersonaButton(roomId), + SubprofileButton(roomId), IconButton( onPressed: hasReplacement ? null diff --git a/lib/widgets/composer/persona_button.dart b/lib/widgets/composer/subprofile_button.dart similarity index 82% rename from lib/widgets/composer/persona_button.dart rename to lib/widgets/composer/subprofile_button.dart index 960a525..d6a52c2 100644 --- a/lib/widgets/composer/persona_button.dart +++ b/lib/widgets/composer/subprofile_button.dart @@ -2,23 +2,23 @@ import "package:flutter_riverpod/flutter_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/controllers/personas.dart"; +import "package:nexus/controllers/subprofiles.dart"; import "package:nexus/controllers/settings.dart"; import "package:nexus/main.dart"; import "package:nexus/widgets/avatars/avatar_or_hash.dart"; -/// Chooses the persona messages are sent as in [roomId], if personas are on. -class const PersonaButton(final String roomId, {super.key}) +/// Chooses the subprofile messages are sent as in [roomId], if subprofiles are on. +class const SubprofileButton(final String roomId, {super.key}) extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final enabled = ref.watch( SettingsController.provider.select( - (settings) => settings.value?.personas ?? false, + (settings) => settings.value?.subprofiles ?? false, ), ); final (:profiles, :current) = ref.watch( - PersonasController.provider(roomId), + SubprofilesController.provider(roomId), ); if (!enabled || profiles.isEmpty) return const SizedBox.shrink(); @@ -47,7 +47,7 @@ class const PersonaButton(final String roomId, {super.key}) return AdaptiveMenuButton( tooltip: switch (current) { final current? => "Sending as ${current.displayName ?? current.id}", - null => "Choose persona", + null => "Choose subprofile", }, icon: switch (current) { final current? => AvatarOrHash( @@ -57,7 +57,7 @@ class const PersonaButton(final String roomId, {super.key}) null => Icon(Icons.person), }, itemBuilder: (_) => [ - item(id: "", leading: Icon(Icons.person), title: "Yourself"), + item(id: "", leading: Icon(Icons.person), title: "Account Profile"), ...profiles.map( (profile) => item( id: profile.id, diff --git a/lib/widgets/lazy_loading/message_displayname.dart b/lib/widgets/lazy_loading/message_displayname.dart index c3fffcd..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"; @@ -34,7 +35,7 @@ class const MessageDisplayname( ), 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/settings/persona_sheet.dart b/lib/widgets/settings/subprofile_sheet.dart similarity index 81% rename from lib/widgets/settings/persona_sheet.dart rename to lib/widgets/settings/subprofile_sheet.dart index d88aaf3..fbfadcd 100644 --- a/lib/widgets/settings/persona_sheet.dart +++ b/lib/widgets/settings/subprofile_sheet.dart @@ -9,16 +9,18 @@ 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 PersonaSheet({final StoredProfile? persona, super.key}) +class const SubprofileSheet({final StoredProfile? subprofile, super.key}) extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final saving = Saving.use(); - final trigger = persona?.triggers.firstOrNull; - final nameController = useTextEditingController(text: persona?.displayName); + 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(persona?.avatarUrl); + final avatar = useState(subprofile?.avatarUrl); final name = useValueListenable(nameController).text.trim(); final accountData = ref.read(AccountDataController.provider.notifier); @@ -35,24 +37,24 @@ class const PersonaSheet({final StoredProfile? persona, super.key}) final suffix = suffixController.text; final edited = StoredProfile( id: - persona?.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), - ...?persona?.triggers.skip(1), + ...?subprofile?.triggers.skip(1), ]), ); final profiles = current(); return update( profiles.copyWith( - profiles: persona == null + profiles: subprofile == null ? profiles.profiles.add(edited) : profiles.profiles.replaceFirstWhere( - (profile) => profile.id == persona!.id, + (profile) => profile.id == subprofile!.id, (_) => edited, ), ), @@ -64,9 +66,9 @@ class const PersonaSheet({final StoredProfile? persona, super.key}) return update( profiles.copyWith( profiles: profiles.profiles.removeWhere( - (profile) => profile.id == persona!.id, + (profile) => profile.id == subprofile!.id, ), - defaultProfileId: profiles.defaultProfileId == persona!.id + defaultProfileId: profiles.defaultProfileId == subprofile!.id ? null : profiles.defaultProfileId, ), @@ -74,9 +76,9 @@ class const PersonaSheet({final StoredProfile? persona, super.key}) } return SheetLayout( - title: Text(persona == null ? "Add Persona" : "Edit Persona"), + title: Text(subprofile == null ? "Add Subprofile" : "Edit Subprofile"), actions: [ - if (persona != null) + if (subprofile != null) TextButton( onPressed: saving.active ? null : delete, style: TextButton.styleFrom( @@ -98,19 +100,19 @@ class const PersonaSheet({final StoredProfile? persona, super.key}) onChanged: (url) async => avatar.value = url, child: AvatarOrHash( avatar.value, - name.isEmpty ? "Persona" : name, + name.isEmpty ? "Subprofile" : name, dimension: 120, ), ), ), TextField( controller: nameController, - autofocus: persona == null, + 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 persona, without them. Leave one empty to only need the other. Both are case-sensitive.", + "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, diff --git a/lib/widgets/users/user_span.dart b/lib/widgets/users/user_span.dart index d12469c..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, @@ -59,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), From 225497030e6998afe3a2adb6e75c035d25796a5d Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 15:54:51 -0500 Subject: [PATCH 34/53] fixup PMPs in encrypted rooms --- lib/models/event.dart | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) 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"], From c786344bf26810d54654dd198ca2e375b1153c63 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 16:06:08 -0500 Subject: [PATCH 35/53] add dynamic hinting and latching for PMPs --- lib/controllers/account_data.dart | 30 +++++++--------- lib/controllers/rooms.dart | 18 ++++++++++ lib/controllers/settings_sections.dart | 15 ++++++++ lib/controllers/subprofiles.dart | 10 +++--- lib/models/per_message_profiles.dart | 5 +++ lib/models/room_subprofiles.dart | 20 +++++++++++ lib/models/settings.dart | 1 + lib/widgets/composer/composer.dart | 19 +++++++++- lib/widgets/composer/subprofile_button.dart | 39 ++++++++++++++------- 9 files changed, 120 insertions(+), 37 deletions(-) create mode 100644 lib/models/room_subprofiles.dart diff --git a/lib/controllers/account_data.dart b/lib/controllers/account_data.dart index 13b5d81..8c68209 100644 --- a/lib/controllers/account_data.dart +++ b/lib/controllers/account_data.dart @@ -87,26 +87,22 @@ class AccountDataController extends Notifier { Future setRoomProfile(String roomId, String profileId) async { const type = AccountData.perMessageProfilesKey; - final current = ref + final rooms = ref.read(RoomsController.provider.notifier); + final previous = ref .read(RoomsController.provider)[roomId] ?.accountData[type]; + final content = {...?previous, "default_profile_id": profileId}; - await ref - .read(ClientController.provider.notifier) - .setAccountData( - .new( - type: type, - roomId: roomId, - content: {...?current, "default_profile_id": profileId}, - ), - ); - await ref - .read(RoomsController.provider.notifier) - .awaitRooms( - (rooms) => - rooms[roomId]?.accountData[type]?["default_profile_id"] == - profileId, - ); + // Shown straight away, rather than once it comes down sync + rooms.setAccountData(roomId, type, content); + try { + await ref + .read(ClientController.provider.notifier) + .setAccountData(.new(type: type, roomId: roomId, content: content)); + } catch (_) { + rooms.setAccountData(roomId, type, previous); + rethrow; + } } /// Saves [rule] of [kind], creating it if it's new, or otherwise changing only diff --git a/lib/controllers/rooms.dart b/lib/controllers/rooms.dart index 91d8093..bd162dd 100644 --- a/lib/controllers/rooms.dart +++ b/lib/controllers/rooms.dart @@ -136,6 +136,24 @@ class RoomsController extends Notifier> { .add(event.eventId, event.rowId); }); + void setAccountData( + String roomId, + String type, + Map? content, + ) { + if (state[roomId] case final room?) { + state = state.add( + roomId, + room.copyWith( + accountData: switch (content) { + final content? => room.accountData.add(type, content), + null => room.accountData.remove(type), + }, + ), + ); + } + } + void update( IMap rooms, [ ISet leftRooms = const .empty(), diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index c084b9b..50a344b 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -467,6 +467,21 @@ class SettingsSectionsController ), ), 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", diff --git a/lib/controllers/subprofiles.dart b/lib/controllers/subprofiles.dart index 70f6e05..98d5f3e 100644 --- a/lib/controllers/subprofiles.dart +++ b/lib/controllers/subprofiles.dart @@ -6,11 +6,7 @@ import "package:nexus/controllers/account_data.dart"; import "package:nexus/controllers/rooms.dart"; import "package:nexus/models/account_data.dart"; import "package:nexus/models/per_message_profiles.dart"; - -typedef RoomSubprofiles = ({ - IList profiles, - StoredProfile? current, -}); +import "package:nexus/models/room_subprofiles.dart"; class SubprofilesController(final String roomId) extends Notifier { @@ -44,8 +40,10 @@ class SubprofilesController(final String roomId) ); final currentId = room?.defaultProfileId ?? global.defaultProfileId; - return ( + return .new( profiles: profiles, + triggerOrder: (room?.profiles ?? const IList.empty()) + .addAll(global.profiles), current: currentId == null || currentId.isEmpty ? null : profiles.firstWhereOrNull((profile) => profile.id == currentId), diff --git a/lib/models/per_message_profiles.dart b/lib/models/per_message_profiles.dart index 7de8398..9d4c386 100644 --- a/lib/models/per_message_profiles.dart +++ b/lib/models/per_message_profiles.dart @@ -41,6 +41,11 @@ class const ProfileTrigger({ 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) => diff --git a/lib/models/room_subprofiles.dart b/lib/models/room_subprofiles.dart new file mode 100644 index 0000000..abf72ac --- /dev/null +++ b/lib/models/room_subprofiles.dart @@ -0,0 +1,20 @@ +import "package:collection/collection.dart"; +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, +}) with _$RoomSubprofiles { + StoredProfile? triggeredBy(String text) => triggerOrder.firstWhereOrNull( + (profile) => + profile.id.isNotEmpty && + profile.triggers.any((trigger) => trigger.matches(text)), + ); +} diff --git a/lib/models/settings.dart b/lib/models/settings.dart index ffad23b..fa5c97a 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -24,6 +24,7 @@ class const Settings({ 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/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index bd4a3de..1baf18e 100644 --- a/lib/widgets/composer/composer.dart +++ b/lib/widgets/composer/composer.dart @@ -27,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"; @@ -433,6 +436,20 @@ class const Composer( attachment != null && attachment.$2 == null) { return; } + if (ref.read(SettingsController.provider).value case Settings( + subprofiles: true, + latchSubprofiles: true, + )) { + final subprofiles = ref.read(SubprofilesController.provider(roomId)); + if (subprofiles.triggeredBy(controller.text) case final triggered? + when triggered.id != subprofiles.current?.id) { + ref + .read(AccountDataController.provider.notifier) + .setRoomProfile(roomId, triggered.id) + .onError(showError); + } + } + onSend( "${TextCommand.prefixOf(textCommands)}${controller.formattedText}", shouldMention: shouldMention.value, @@ -566,7 +583,7 @@ class const Composer( ), ) ? [ - SubprofileButton(roomId), + SubprofileButton(roomId, controller: controller), IconButton( onPressed: hasReplacement ? null diff --git a/lib/widgets/composer/subprofile_button.dart b/lib/widgets/composer/subprofile_button.dart index d6a52c2..145e932 100644 --- a/lib/widgets/composer/subprofile_button.dart +++ b/lib/widgets/composer/subprofile_button.dart @@ -1,15 +1,21 @@ -import "package:flutter_riverpod/flutter_riverpod.dart"; +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/controllers/subprofiles.dart"; import "package:nexus/controllers/settings.dart"; import "package:nexus/main.dart"; +import "package:nexus/models/room_subprofiles.dart"; import "package:nexus/widgets/avatars/avatar_or_hash.dart"; -/// Chooses the subprofile messages are sent as in [roomId], if subprofiles are on. -class const SubprofileButton(final String roomId, {super.key}) - extends ConsumerWidget { +/// 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( @@ -17,10 +23,14 @@ class const SubprofileButton(final String roomId, {super.key}) (settings) => settings.value?.subprofiles ?? false, ), ); - final (:profiles, :current) = ref.watch( - SubprofilesController.provider(roomId), + 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; Future choose(String profileId) => ref .read(AccountDataController.provider.notifier) @@ -45,14 +55,17 @@ class const SubprofileButton(final String roomId, {super.key}) } return AdaptiveMenuButton( - tooltip: switch (current) { - final current? => "Sending as ${current.displayName ?? current.id}", - null => "Choose subprofile", + 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 (current) { - final current? => AvatarOrHash( - current.avatarUrl, - current.displayName ?? current.id, + icon: switch (shown) { + final shown? => AvatarOrHash( + shown.avatarUrl, + shown.displayName ?? shown.id, ), null => Icon(Icons.person), }, From 3cf0b811bbb65604f109251e3175fc77d6aa0e54 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 16:21:43 -0500 Subject: [PATCH 36/53] PMP race condition fixes --- lib/controllers/account_data.dart | 38 ++++++++++++-------- lib/controllers/pending_subprofiles.dart | 45 ++++++++++++++++++++++++ lib/controllers/room_chat.dart | 23 ++++++++++++ lib/controllers/rooms.dart | 18 ---------- lib/controllers/subprofiles.dart | 19 +++++++--- lib/models/room_subprofiles.dart | 1 + 6 files changed, 108 insertions(+), 36 deletions(-) create mode 100644 lib/controllers/pending_subprofiles.dart diff --git a/lib/controllers/account_data.dart b/lib/controllers/account_data.dart index 8c68209..debad12 100644 --- a/lib/controllers/account_data.dart +++ b/lib/controllers/account_data.dart @@ -5,6 +5,7 @@ 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"; @@ -85,24 +86,33 @@ class AccountDataController extends Notifier { (data) => data.perMessageProfiles == profiles, ); - Future setRoomProfile(String roomId, String profileId) async { + Future setRoomProfile(String roomId, String profileId) { const type = AccountData.perMessageProfilesKey; - final rooms = ref.read(RoomsController.provider.notifier); - final previous = ref + const key = "default_profile_id"; + final current = ref .read(RoomsController.provider)[roomId] ?.accountData[type]; - final content = {...?previous, "default_profile_id": profileId}; - // Shown straight away, rather than once it comes down sync - rooms.setAccountData(roomId, type, content); - try { - await ref - .read(ClientController.provider.notifier) - .setAccountData(.new(type: type, roomId: roomId, content: content)); - } catch (_) { - rooms.setAccountData(roomId, type, previous); - rethrow; - } + 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 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/rooms.dart b/lib/controllers/rooms.dart index bd162dd..91d8093 100644 --- a/lib/controllers/rooms.dart +++ b/lib/controllers/rooms.dart @@ -136,24 +136,6 @@ class RoomsController extends Notifier> { .add(event.eventId, event.rowId); }); - void setAccountData( - String roomId, - String type, - Map? content, - ) { - if (state[roomId] case final room?) { - state = state.add( - roomId, - room.copyWith( - accountData: switch (content) { - final content? => room.accountData.add(type, content), - null => room.accountData.remove(type), - }, - ), - ); - } - } - void update( IMap rooms, [ ISet leftRooms = const .empty(), diff --git a/lib/controllers/subprofiles.dart b/lib/controllers/subprofiles.dart index 98d5f3e..21b1a0d 100644 --- a/lib/controllers/subprofiles.dart +++ b/lib/controllers/subprofiles.dart @@ -3,6 +3,7 @@ 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"; @@ -39,14 +40,24 @@ class SubprofilesController(final String roomId) ), ); - final currentId = room?.defaultProfileId ?? global.defaultProfileId; + 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: currentId == null || currentId.isEmpty - ? null - : profiles.firstWhereOrNull((profile) => profile.id == currentId), + current: byId( + ref.watch( + PendingSubprofilesController.provider.select( + (pending) => pending[roomId]?.id, + ), + ) ?? + syncedId, + ), + synced: byId(syncedId), ); } diff --git a/lib/models/room_subprofiles.dart b/lib/models/room_subprofiles.dart index abf72ac..69ec889 100644 --- a/lib/models/room_subprofiles.dart +++ b/lib/models/room_subprofiles.dart @@ -11,6 +11,7 @@ class const RoomSubprofiles({ // Each trigger is tried in this order, as gomuks does when sending required final IList triggerOrder, final StoredProfile? current, + final StoredProfile? synced, }) with _$RoomSubprofiles { StoredProfile? triggeredBy(String text) => triggerOrder.firstWhereOrNull( (profile) => From 6e6bcaaad176f1bda33ed54545181143a184a8d2 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 17:19:19 -0500 Subject: [PATCH 37/53] support a lot more events to be rendered Also adds show hidden events setting. Fixes #178 --- lib/controllers/settings_sections.dart | 10 +- lib/models/settings.dart | 2 +- .../renderers/diffs/pinned_events_diff.dart | 77 ++-------- lib/widgets/renderers/event.dart | 143 ++++++++++++++++-- lib/widgets/renderers/event_preview.dart | 3 +- lib/widgets/renderers/related_event_line.dart | 85 +++++++++++ 6 files changed, 233 insertions(+), 87 deletions(-) create mode 100644 lib/widgets/renderers/related_event_line.dart diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index 50a344b..5121d6b 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -378,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), ), ), diff --git a/lib/models/settings.dart b/lib/models/settings.dart index fa5c97a..6e08a0e 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -18,7 +18,7 @@ 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, 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/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/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"), + }, + ); + } +} From a7e60b946417b0cc910ed8cbab0cff19ec817411 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 26 Nov 2026 17:49:10 -0500 Subject: [PATCH 38/53] use canonical alias ahead of room id for mentions --- lib/controllers/composer_draft.dart | 45 +++++++++++-------- .../composer/overlays/room_overlay.dart | 6 ++- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/lib/controllers/composer_draft.dart b/lib/controllers/composer_draft.dart index c6e8e78..65eb3cb 100644 --- a/lib/controllers/composer_draft.dart +++ b/lib/controllers/composer_draft.dart @@ -84,6 +84,7 @@ class ComposerDraftController(final ComposerParams composer) static final _tagPattern = RegExp( r"\[@[^\]]*\]\(matrix:u/([^)\s]+)\)" r"|\[#[^\]]*\]\(matrix:roomid/([^)?\s]+)[^)\s]*\)" + r"|\[#[^\]]*\]\(matrix:r/([^)?\s]+)[^)\s]*\)" r'|!\[:([^\]\s]+):\]\(mxc://[^)\s]+(?: "(?:[^"\\]|\\.)*")?\)', ); @@ -91,25 +92,31 @@ class ComposerDraftController(final ComposerParams composer) /// 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])) { - (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 shortcode) => .new( - id: match[0]!, - text: shortcode!, - triggerCharacter: ":", - ), - }; + 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) { diff --git a/lib/widgets/composer/overlays/room_overlay.dart b/lib/widgets/composer/overlays/room_overlay.dart index f6b4bed..0c2fed9 100644 --- a/lib/widgets/composer/overlays/room_overlay.dart +++ b/lib/widgets/composer/overlays/room_overlay.dart @@ -42,9 +42,11 @@ 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?.localpart ?? room.metadata?.id ?? From 9f2d22380945000aab514eec5a4095bd4d552652 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Sat, 28 Nov 2026 11:42:34 -0500 Subject: [PATCH 39/53] fix inline images not getting spoilered --- lib/widgets/html/html.dart | 8 ++++++-- .../html/{spoiler_text.dart => spoiler.dart} | 13 ++++++------- 2 files changed, 12 insertions(+), 9 deletions(-) rename lib/widgets/html/{spoiler_text.dart => spoiler.dart} (55%) diff --git a/lib/widgets/html/html.dart b/lib/widgets/html/html.dart index 9236e9a..06e3ebb 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 = diff --git a/lib/widgets/html/spoiler_text.dart b/lib/widgets/html/spoiler.dart similarity index 55% rename from lib/widgets/html/spoiler_text.dart rename to lib/widgets/html/spoiler.dart index 8094f9d..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); @@ -11,15 +11,14 @@ class const SpoilerText(final String text, {super.key}) extends HookWidget { child: AnimatedContainer( duration: Durations.short2, decoration: BoxDecoration( - color: revealed.value - ? Colors.blueGrey.withValues(alpha: 0.3) - : Colors.blueGrey, + color: Colors.blueGrey.withValues(alpha: 0.3), borderRadius: .circular(4), ), - child: Text( - text, - style: .new(color: revealed.value ? null : Colors.transparent), + foregroundDecoration: BoxDecoration( + color: revealed.value ? Colors.transparent : Colors.blueGrey, + borderRadius: .circular(4), ), + child: IgnorePointer(ignoring: !revealed.value, child: child), ), ); } From 7435ecd5f0789785cb346c358f797399a9a06e5f Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Sun, 29 Nov 2026 14:13:33 -0500 Subject: [PATCH 40/53] don't send empty messages if only a subprofile trigger is sent --- lib/models/room_subprofiles.dart | 28 ++++++++++++++++++----- lib/widgets/composer/composer.dart | 36 ++++++++++++++++++++---------- 2 files changed, 46 insertions(+), 18 deletions(-) diff --git a/lib/models/room_subprofiles.dart b/lib/models/room_subprofiles.dart index 69ec889..073536c 100644 --- a/lib/models/room_subprofiles.dart +++ b/lib/models/room_subprofiles.dart @@ -1,4 +1,3 @@ -import "package:collection/collection.dart"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:freezed_annotation/freezed_annotation.dart"; import "package:nexus/models/per_message_profiles.dart"; @@ -13,9 +12,26 @@ class const RoomSubprofiles({ final StoredProfile? current, final StoredProfile? synced, }) with _$RoomSubprofiles { - StoredProfile? triggeredBy(String text) => triggerOrder.firstWhereOrNull( - (profile) => - profile.id.isNotEmpty && - profile.triggers.any((trigger) => trigger.matches(text)), - ); + // 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/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index 1baf18e..f251838 100644 --- a/lib/widgets/composer/composer.dart +++ b/lib/widgets/composer/composer.dart @@ -436,18 +436,30 @@ class const Composer( attachment != null && attachment.$2 == null) { return; } - if (ref.read(SettingsController.provider).value case Settings( - subprofiles: true, - latchSubprofiles: true, - )) { - final subprofiles = ref.read(SubprofilesController.provider(roomId)); - if (subprofiles.triggeredBy(controller.text) case final triggered? - when triggered.id != subprofiles.current?.id) { - ref - .read(AccountDataController.provider.notifier) - .setRoomProfile(roomId, triggered.id) - .onError(showError); - } + 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( From d5f04122eb9fdffde2ebc956d9854a36aadefc7e Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Sun, 29 Nov 2026 14:16:20 -0500 Subject: [PATCH 41/53] added subprofile search --- lib/widgets/composer/subprofile_button.dart | 42 +------- lib/widgets/composer/subprofile_picker.dart | 101 ++++++++++++++++++++ 2 files changed, 105 insertions(+), 38 deletions(-) create mode 100644 lib/widgets/composer/subprofile_picker.dart diff --git a/lib/widgets/composer/subprofile_button.dart b/lib/widgets/composer/subprofile_button.dart index 145e932..dc54b97 100644 --- a/lib/widgets/composer/subprofile_button.dart +++ b/lib/widgets/composer/subprofile_button.dart @@ -2,12 +2,11 @@ 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/controllers/subprofiles.dart"; import "package:nexus/controllers/settings.dart"; -import "package:nexus/main.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. @@ -32,29 +31,7 @@ class const SubprofileButton( if (!enabled || profiles.isEmpty) return const SizedBox.shrink(); final shown = triggered ?? current; - Future choose(String profileId) => ref - .read(AccountDataController.provider.notifier) - .setRoomProfile(roomId, profileId) - .onError(showError); - - PopupMenuItem item({ - required String id, - required Widget leading, - required String title, - }) { - final selected = (current?.id ?? "") == id; - return PopupMenuItem( - onTap: () => choose(id), - child: ListTile( - selected: selected, - leading: leading, - title: Text(title), - trailing: selected ? Icon(Icons.check) : null, - ), - ); - } - - return AdaptiveMenuButton( + return IconButton( tooltip: switch ((triggered, current)) { (final triggered?, _) => "Sending this message as ${triggered.displayName ?? triggered.id}", @@ -69,19 +46,8 @@ class const SubprofileButton( ), null => Icon(Icons.person), }, - itemBuilder: (_) => [ - item(id: "", leading: Icon(Icons.person), title: "Account Profile"), - ...profiles.map( - (profile) => item( - id: profile.id, - leading: AvatarOrHash( - profile.avatarUrl, - profile.displayName ?? profile.id, - ), - title: profile.displayName ?? profile.id, - ), - ), - ], + 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(), + ), + ), + ], + ); + } +} From dccbda78703355011a7d03162a71d9260544e30f Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 1 Dec 2026 01:59:08 -0500 Subject: [PATCH 42/53] make all ExpandableImages downloadable There might have been a reason why I didn't do this but I don't remember it... --- lib/helpers/extensions/show_image_viewer.dart | 19 +++++++++---------- lib/widgets/common/expandable_image.dart | 2 +- lib/widgets/html/html.dart | 1 - lib/widgets/reactions/reactions_popover.dart | 1 - 4 files changed, 10 insertions(+), 13 deletions(-) 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/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/html/html.dart b/lib/widgets/html/html.dart index 06e3ebb..76b656e 100644 --- a/lib/widgets/html/html.dart +++ b/lib/widgets/html/html.dart @@ -98,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/reactions/reactions_popover.dart b/lib/widgets/reactions/reactions_popover.dart index c1200c3..e8e475c 100644 --- a/lib/widgets/reactions/reactions_popover.dart +++ b/lib/widgets/reactions/reactions_popover.dart @@ -68,7 +68,6 @@ class const ReactionsPopover( void expand() => context.showImageViewer( ref, .new(mxc: Uri.parse(reaction)), - downloadFilename: reaction.split("/").last, ); final isImage = reaction.startsWith("mxc://"); From 784db4f1ddee2eb9b413a2def5fb28216f320482 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 1 Dec 2026 02:02:14 -0500 Subject: [PATCH 43/53] open reaction image on long press anywhere in its tab --- lib/widgets/reactions/reactions_popover.dart | 21 ++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/lib/widgets/reactions/reactions_popover.dart b/lib/widgets/reactions/reactions_popover.dart index e8e475c..cf4b717 100644 --- a/lib/widgets/reactions/reactions_popover.dart +++ b/lib/widgets/reactions/reactions_popover.dart @@ -64,6 +64,7 @@ class const ReactionsPopover( controller: tabController, isScrollable: true, tabAlignment: .start, + labelPadding: .zero, tabs: keys.map((reaction) { void expand() => context.showImageViewer( ref, @@ -72,16 +73,20 @@ class const ReactionsPopover( 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()), + ], + ), ), ), ); From 5b73e998df4373dd5b4b879d0d19b4fe42aa4fe5 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 1 Dec 2026 11:10:02 -0500 Subject: [PATCH 44/53] backport a GTK patch so the flatpak doesn't crash --- linux/nix/default.nix | 9 +++ .../patches/gtk3-egl-renderable-type.patch | 60 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 linux/nix/patches/gtk3-egl-renderable-type.patch diff --git a/linux/nix/default.nix b/linux/nix/default.nix index 8f09dbc..6da2a60 100644 --- a/linux/nix/default.nix +++ b/linux/nix/default.nix @@ -14,6 +14,15 @@ android_sdk.accept_license = true; allowUnfree = true; }; + overlays = [ + (_: prev: { + # 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. + gtk3 = prev.gtk3.overrideAttrs (old: { + patches = old.patches or [ ] ++ [ ./patches/gtk3-egl-renderable-type.patch ]; + }); + }) + ]; }; packages = 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 + From fb5e14091e915378b5ee79c8227bcf1ddb85c3d1 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 1 Dec 2026 11:50:00 -0500 Subject: [PATCH 45/53] don't rebuild half the world for the gtk3 patch --- linux/nix/default.nix | 47 ++++++++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/linux/nix/default.nix b/linux/nix/default.nix index 6da2a60..5611f52 100644 --- a/linux/nix/default.nix +++ b/linux/nix/default.nix @@ -14,23 +14,36 @@ android_sdk.accept_license = true; allowUnfree = true; }; - overlays = [ - (_: prev: { - # 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. - gtk3 = prev.gtk3.overrideAttrs (old: { - patches = old.patches or [ ] ++ [ ./patches/gtk3-egl-renderable-type.patch ]; - }); - }) - ]; }; 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 ]; + }); + } + ]; + } + // { + inherit (drv) pname version meta; + }; + + default = withPatchedGtk unpatched; in { inherit default; @@ -41,12 +54,14 @@ 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; + }) + ); runtime = "org.gnome.Platform/51"; permissions = { share = [ "network" ]; From c9fdda41d17633efa1f6499afbadc48fa366e5d7 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 1 Dec 2026 12:19:29 -0500 Subject: [PATCH 46/53] hide the runtime's GTK3 from nix2flatpak, so it bundles our patched one --- linux/nix/default.nix | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/linux/nix/default.nix b/linux/nix/default.nix index 5611f52..87b2f2d 100644 --- a/linux/nix/default.nix +++ b/linux/nix/default.nix @@ -63,6 +63,13 @@ }) ); 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 = [ From 5d15236903369fb91517ecf6c4775f84acdca445 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 1 Dec 2026 12:55:50 -0500 Subject: [PATCH 47/53] override RUNPATH to put patched gtk3 first --- linux/nix/default.nix | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/linux/nix/default.nix b/linux/nix/default.nix index 87b2f2d..79aab66 100644 --- a/linux/nix/default.nix +++ b/linux/nix/default.nix @@ -60,6 +60,13 @@ unset GST_PLUGIN_SYSTEM_PATH_1_0 '' + old.postInstall; + # 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"; From 32df54921557bce8f822689ecd2e30a081beac61 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Tue, 1 Dec 2026 18:05:00 -0500 Subject: [PATCH 48/53] fixup OSK with patched GTK I am really looking forward to dropping all this on a new GTK version. --- linux/nix/default.nix | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/linux/nix/default.nix b/linux/nix/default.nix index 79aab66..aa8e46d 100644 --- a/linux/nix/default.nix +++ b/linux/nix/default.nix @@ -35,6 +35,8 @@ 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" ]; }); } ]; @@ -60,6 +62,10 @@ 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 "" + '' From 7424bec0fb18d8c5d1d1459629acfcd72deb0268 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 2 Dec 2026 13:44:14 -0500 Subject: [PATCH 49/53] bump fluttertagger to fix RangeError --- pubspec.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.lock b/pubspec.lock index a9cf736..7b445a7 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -744,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" From 9d495410f6b78aa00f4acf9227ab20f07b366968 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 2 Dec 2026 13:50:34 -0500 Subject: [PATCH 50/53] make webpush enabled check better Because Continuwuity sends a VAPID even when webpush is disabled. --- lib/controllers/unified_push.dart | 5 +++-- lib/controllers/unified_push_allowed.dart | 2 +- lib/models/capabilities.dart | 8 ++++++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/controllers/unified_push.dart b/lib/controllers/unified_push.dart index 1fa3a2e..d6f3777 100644 --- a/lib/controllers/unified_push.dart +++ b/lib/controllers/unified_push.dart @@ -225,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.", ); @@ -243,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/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) => From f33865962b3536a883fae795ee4969b209ac5088 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 2 Dec 2026 15:27:01 -0500 Subject: [PATCH 51/53] fix fluttertagger hash --- linux/nix/pkg/default.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linux/nix/pkg/default.nix b/linux/nix/pkg/default.nix index 3fbe98f..ada2547 100644 --- a/linux/nix/pkg/default.nix +++ b/linux/nix/pkg/default.nix @@ -61,7 +61,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="; From a7a21f4d1a9968a65210c407c6337405d798c65c Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Wed, 2 Dec 2026 16:08:49 -0500 Subject: [PATCH 52/53] gate invite behind PL check --- lib/widgets/rooms/room_menu_button.dart | 143 +++++++++++++----------- 1 file changed, 77 insertions(+), 66 deletions(-) diff --git a/lib/widgets/rooms/room_menu_button.dart b/lib/widgets/rooms/room_menu_button.dart index 4bfa840..47d4d42 100644 --- a/lib/widgets/rooms/room_menu_button.dart +++ b/lib/widgets/rooms/room_menu_button.dart @@ -7,6 +7,7 @@ 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"; @@ -100,75 +101,85 @@ 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: "", ), ), - child: ListTile( - leading: Icon(Icons.person_add), - title: Text("Invite"), + )) + 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), From 2e6fa1e7d81d48058d70a19526c70fe359a69595 Mon Sep 17 00:00:00 2001 From: Henry-Hiles Date: Thu, 3 Dec 2026 11:32:52 -0500 Subject: [PATCH 53/53] fix nix build --- linux/nix/pkg/default.nix | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/linux/nix/pkg/default.nix b/linux/nix/pkg/default.nix index ada2547..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