Offline (read-only) mode - The last connected radio is remembered; with no radio the app opens on its saved contacts, channels, messages and unread counts. - Main screens stay open on disconnect. A Connect button replaces the battery and signal indicators, with a sheet to reconnect, choose a radio or stop a pending reconnect. - While disconnected everything is read-only: the composer becomes a "connect to send" bar (drafts kept) and controls that change the radio or stored history are disabled or hidden. - Resending while disconnected no longer deletes the message; a different radio no longer shows the previous radio's channels. - Notification taps open the saved chat while offline. Chats and menus - Channel chat menu: notifications, edit channel, delete channel; the filter row lines up with the others; bell moved out of the app bar. - DM and room menus: remove from contacts; rooms get room management. - Search field uses the full app bar; long-press a result to copy. - Hashtag channel titles no longer read "# #name"; more room around the radio activity dot. - Repeat filter: short messages from one sender are caught at the same count as long ones. Layout - Shared menu row (wraps to two lines) and segment label (never splits a word) used across the app. - One Scan button on the scanner; consistent settings tile titles; contact "last seen" wraps instead of truncating; unfetched repeater settings are dimmed. Localization - New European Portuguese locale (pt_PT); regional locales are handled by the language picker, notifications and the background service. - Fill 67 missing strings per locale, including backup and restore. - Keep "Flood" and "Zero Hop" untranslated, shorten "last seen" and routing labels, and fix mistranslated scan, theme and hop strings. - Received-image strings, badge and caption come from translations. - Regenerate the Czech localizations, which were missing strings. Docs - Add documentation/design.md (UI reference) and offline-mode.md; update channel, chat, navigation and scanner docs.
4133 lines
150 KiB
Dart
4133 lines
150 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:math' as math;
|
|
import 'dart:ui' as ui;
|
|
|
|
import 'package:flutter/foundation.dart' show mergeSort;
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/scheduler.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:image_picker/image_picker.dart';
|
|
import 'package:provider/provider.dart';
|
|
|
|
import '../connector/meshcore_connector.dart';
|
|
import '../models/community.dart';
|
|
import '../storage/community_store.dart';
|
|
import '../utils/platform_info.dart';
|
|
import '../helpers/chat_jump.dart';
|
|
import '../helpers/chat_scroll_controller.dart';
|
|
import '../connector/meshcore_protocol.dart';
|
|
import '../helpers/cyr2lat.dart';
|
|
import '../helpers/gif_helper.dart';
|
|
import '../helpers/ipfs_link_attach_flow.dart';
|
|
import '../helpers/contact_share_message.dart';
|
|
import '../helpers/marker_message.dart';
|
|
import '../helpers/message_search.dart';
|
|
import '../widgets/chat_search_results.dart';
|
|
import '../helpers/message_url_image_helper.dart';
|
|
import '../helpers/path_helper.dart';
|
|
import '../helpers/reaction_helper.dart';
|
|
import '../helpers/snack_bar_builder.dart';
|
|
import '../l10n/l10n.dart';
|
|
import '../models/channel.dart';
|
|
import '../models/channel_message.dart';
|
|
import '../models/image_codec_support.dart' show aeicRatePointForUi;
|
|
import '../models/message_filter.dart';
|
|
import '../services/app_settings_service.dart' show AppSettingsService;
|
|
import '../services/chat_text_scale_service.dart';
|
|
import '../services/image_chunk_transport.dart';
|
|
import '../services/image_codec_service.dart';
|
|
import '../services/message_filter/message_filter_service.dart';
|
|
import '../services/message_filter/message_filter_text.dart';
|
|
import '../services/received_image_store.dart';
|
|
import '../services/translation_service.dart';
|
|
import '../utils/image_save.dart';
|
|
import '../utils/lora_airtime.dart';
|
|
import '../utils/radio_guard.dart';
|
|
import '../widgets/marker_label_dialog.dart';
|
|
import '../widgets/received_image_message.dart';
|
|
import '../widgets/channel_notification_mode_sheet.dart';
|
|
import '../widgets/chat_day_separator.dart';
|
|
import '../widgets/empty_state.dart';
|
|
import '../widgets/filter_rule_dialog.dart';
|
|
import '../widgets/filtered_message_ghost.dart';
|
|
import '../widgets/chat_composer.dart';
|
|
import '../widgets/chat_send_pipeline.dart';
|
|
import '../widgets/chat_zoom_wrapper.dart';
|
|
import '../widgets/message_bubble_frame.dart';
|
|
import '../widgets/reaction_chips.dart';
|
|
import '../widgets/emoji_picker.dart';
|
|
import '../widgets/gif_message.dart';
|
|
import '../widgets/jump_to_bottom_button.dart';
|
|
import '../widgets/image_send_codec_binding.dart';
|
|
import '../widgets/image_send_preview_sheet.dart';
|
|
import '../widgets/message_status_icon.dart';
|
|
import '../widgets/radio_stats_entry.dart';
|
|
import '../widgets/sync_progress_overlay.dart';
|
|
import '../widgets/translated_message_content.dart';
|
|
import '../widgets/unread_divider.dart';
|
|
import '../theme/mesh_theme.dart';
|
|
import '../widgets/future_timestamp_indicator.dart';
|
|
import '../widgets/mesh_ui.dart';
|
|
import '../widgets/share_contact_sheet.dart';
|
|
import '../widgets/shared_contact_card.dart';
|
|
import 'app_settings_screen.dart';
|
|
import 'channel_chat_transcript_grouping.dart';
|
|
import 'channels_screen.dart' show confirmDeleteChannel, showEditChannelSheet;
|
|
import 'channel_message_path_screen.dart';
|
|
import 'map_screen.dart';
|
|
import 'region_management_screen.dart';
|
|
import '../storage/region_store.dart';
|
|
import '../utils/share_origin.dart';
|
|
import '../services/chat_background_service.dart';
|
|
import '../widgets/chat_background.dart';
|
|
import '../widgets/holiday_animations.dart';
|
|
|
|
class ChannelChatScreen extends StatefulWidget {
|
|
final Channel channel;
|
|
final int initialUnreadCount;
|
|
|
|
const ChannelChatScreen({
|
|
super.key,
|
|
required this.channel,
|
|
this.initialUnreadCount = 0,
|
|
});
|
|
|
|
@override
|
|
State<ChannelChatScreen> createState() => _ChannelChatScreenState();
|
|
}
|
|
|
|
class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
|
final _holidayWatcher = HolidayTriggerWatcher();
|
|
final _messageAreaKey = GlobalKey();
|
|
final TextEditingController _textController = TextEditingController();
|
|
final ChatScrollController _scrollController = ChatScrollController();
|
|
final FocusNode _textFieldFocusNode = FocusNode();
|
|
ChannelMessage? _replyingToMessage;
|
|
bool _useReplyRegion = false;
|
|
final CommunityStore _communityStore = CommunityStore();
|
|
final CommunityPskIndex _communityIndex = CommunityPskIndex();
|
|
final Map<String, GlobalKey> _messageKeys = {};
|
|
bool _isLoadingOlder = false;
|
|
|
|
/// Storage returned no more history; stop asking for older pages.
|
|
bool _olderHistoryExhausted = false;
|
|
|
|
/// Older pages loaded automatically because filtered messages left the
|
|
/// list too short to scroll (and so to reach the load-older trigger).
|
|
int _hiddenBackfillPages = 0;
|
|
bool _hiddenBackfillScheduled = false;
|
|
static const int _maxHiddenBackfillPages = 20;
|
|
bool _communitiesLoaded = false;
|
|
|
|
/// Per-screen image-id allocator. The id is 8 bits and the reassembly key also
|
|
/// carries the sender prefix and channel, so a per-screen allocator is enough
|
|
/// to keep two images in the same channel apart.
|
|
final ImageIdAllocator _imageIds = ImageIdAllocator();
|
|
|
|
/// Chunks acked so far / total, while an image send is in flight. Both 0 when
|
|
/// nothing is being sent.
|
|
int _imageSendSent = 0;
|
|
int _imageSendTotal = 0;
|
|
|
|
MeshCoreConnector? _connector;
|
|
final ChatSendGuard _sendGuard = ChatSendGuard();
|
|
bool _channelSkipNextBottomSnap = false;
|
|
String? _unreadDividerMessageId;
|
|
_TranscriptLayout? _transcriptLayout;
|
|
ReceivedImageStore? _watchedImageStore;
|
|
int _imageStoreVersion = 0;
|
|
ModalRoute<dynamic>? _route;
|
|
|
|
/// The channel chat currently registered as the visible conversation. A
|
|
/// screen only clears the registration it owns, so one disposed after the
|
|
/// screen underneath re-registered cannot wipe that out.
|
|
static _ChannelChatScreenState? _activeOwner;
|
|
|
|
void _registerActive() {
|
|
final connector = _connector;
|
|
if (connector == null) return;
|
|
_activeOwner = this;
|
|
connector.setActiveChannel(widget.channel.index);
|
|
}
|
|
|
|
void _unregisterActive() {
|
|
if (!identical(_activeOwner, this)) return;
|
|
_activeOwner = null;
|
|
_connector?.setActiveChannel(null);
|
|
}
|
|
|
|
/// Filtered messages the user tapped open on this screen. Session-only by
|
|
/// design: leaving the chat hides them again.
|
|
final Set<String> _revealedFilteredIds = <String>{};
|
|
int _revealVersion = 0;
|
|
|
|
/// Message ids picked for a bulk action. Non-empty means selection mode:
|
|
/// taps toggle messages and the app bar shows the bulk actions.
|
|
final Set<String> _selectedIds = <String>{};
|
|
bool get _selecting => _selectedIds.isNotEmpty;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_textFieldFocusNode.addListener(_onTextFieldFocusChange);
|
|
_scrollController.onScrollNearTop = _loadOlderMessages;
|
|
_scrollController.showJumpToBottom.addListener(_clearDividerAtBottom);
|
|
SchedulerBinding.instance.addPostFrameCallback((_) {
|
|
if (!mounted) return;
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final settings = context.read<AppSettingsService>().settings;
|
|
final unread = widget.initialUnreadCount;
|
|
final messages = connector.getChannelMessages(widget.channel);
|
|
_loadCommunities();
|
|
ChannelMessage? anchor;
|
|
if (unread > 0) {
|
|
anchor = _findOldestUnreadChannelAnchor(messages, unread);
|
|
}
|
|
setState(() {
|
|
if (anchor != null) _unreadDividerMessageId = anchor.messageId;
|
|
});
|
|
_connector = connector;
|
|
if (_route?.isCurrent ?? true) _registerActive();
|
|
if (anchor != null && settings.jumpToOldestUnread) {
|
|
_channelSkipNextBottomSnap = true;
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (!mounted) return;
|
|
// Estimate from visible list entries: filtered messages collapse
|
|
// into ghost rows (or vanish in hide mode), so raw message counts
|
|
// would undershoot.
|
|
var unreadEntries = unread;
|
|
var totalEntries = messages.length;
|
|
final layout = _transcriptLayout;
|
|
if (layout != null && layout.length > 0) {
|
|
final entryIndex = layout.ids.indexOf(
|
|
layout.entryIdFor(anchor!.messageId),
|
|
);
|
|
if (entryIndex >= 0) {
|
|
// Entries are newest first, so the anchor has entryIndex
|
|
// newer entries below it.
|
|
unreadEntries = entryIndex + 1;
|
|
totalEntries = layout.length;
|
|
}
|
|
}
|
|
_scrollController.jumpToEstimatedOffset(
|
|
unreadCount: unreadEntries,
|
|
totalMessages: totalEntries,
|
|
onJumped: () {
|
|
if (!mounted) return;
|
|
_scrollToMessage(anchor!.messageId, quiet: true);
|
|
},
|
|
);
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Loads the community list; also re-run whenever a covering route pops
|
|
/// (see [_onCoveringRouteStatus]).
|
|
Future<void> _loadCommunities() async {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
_communityStore.setPublicKeyHex = connector.storageKeyHex;
|
|
final communities = await _communityStore.loadCommunities();
|
|
if (mounted) {
|
|
setState(() {
|
|
_communityIndex.initialize(communities);
|
|
_communitiesLoaded = true;
|
|
});
|
|
}
|
|
}
|
|
|
|
ChannelMessage? _findOldestUnreadChannelAnchor(
|
|
List<ChannelMessage> messages,
|
|
int unreadCount,
|
|
) {
|
|
if (unreadCount <= 0 || messages.isEmpty) return null;
|
|
var n = 0;
|
|
ChannelMessage? oldest;
|
|
for (final m in messages.reversed) {
|
|
if (!_countsAsUnread(m)) continue;
|
|
n++;
|
|
oldest = m;
|
|
if (n >= unreadCount) break;
|
|
}
|
|
return oldest;
|
|
}
|
|
|
|
void _clearDividerAtBottom() {
|
|
if (!_scrollController.showJumpToBottom.value &&
|
|
_unreadDividerMessageId != null) {
|
|
setState(() => _unreadDividerMessageId = null);
|
|
}
|
|
}
|
|
|
|
void _onTextFieldFocusChange() {
|
|
if (_textFieldFocusNode.hasFocus && mounted) {
|
|
_scrollController.handleKeyboardOpen();
|
|
}
|
|
}
|
|
|
|
Future<void> _loadOlderMessages() async {
|
|
if (_isLoadingOlder || _olderHistoryExhausted) return;
|
|
setState(() => _isLoadingOlder = true);
|
|
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final older = await connector.loadOlderChannelMessages(
|
|
widget.channel.index,
|
|
);
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_isLoadingOlder = false;
|
|
if (older.isEmpty) _olderHistoryExhausted = true;
|
|
});
|
|
}
|
|
}
|
|
|
|
/// When filtered messages are hidden or collapsed, the loaded window can
|
|
/// leave nothing (or too little) on screen to scroll, so the scroll-near-top
|
|
/// trigger for older history never fires. Keep loading older pages until
|
|
/// the list can scroll, storage runs out, or the automatic page cap is hit.
|
|
void _scheduleHiddenHistoryBackfill() {
|
|
if (_hiddenBackfillScheduled ||
|
|
_isLoadingOlder ||
|
|
_olderHistoryExhausted ||
|
|
_hiddenBackfillPages >= _maxHiddenBackfillPages) {
|
|
return;
|
|
}
|
|
_hiddenBackfillScheduled = true;
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
_hiddenBackfillScheduled = false;
|
|
if (!mounted || _isLoadingOlder || _olderHistoryExhausted) return;
|
|
if (_scrollController.hasClients &&
|
|
_scrollController.position.maxScrollExtent > 0) {
|
|
return;
|
|
}
|
|
_hiddenBackfillPages++;
|
|
unawaited(_loadOlderMessages());
|
|
});
|
|
}
|
|
|
|
/// Loads an older page on request, restarting the automatic page cap.
|
|
void _loadOlderHiddenHistory() {
|
|
_hiddenBackfillPages = 0;
|
|
unawaited(_loadOlderMessages());
|
|
}
|
|
|
|
@override
|
|
void didChangeDependencies() {
|
|
super.didChangeDependencies();
|
|
final route = ModalRoute.of(context);
|
|
if (!identical(route, _route)) {
|
|
_route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus);
|
|
_route = route;
|
|
route?.secondaryAnimation?.addStatusListener(_onCoveringRouteStatus);
|
|
}
|
|
}
|
|
|
|
/// Reloads communities when a route pushed on top of this one is popped,
|
|
/// so a community joined or created elsewhere gets its badge and type here.
|
|
///
|
|
/// Also keeps the active conversation honest: a page pushed on top (e.g.
|
|
/// another chat opened from a notification) hides this channel, so its
|
|
/// messages must count as unread again until it is uncovered.
|
|
void _onCoveringRouteStatus(AnimationStatus status) {
|
|
if (!mounted) return;
|
|
if (status == AnimationStatus.dismissed) {
|
|
_registerActive();
|
|
_loadCommunities();
|
|
} else {
|
|
// Not just `forward`: a page pushed without a transition jumps
|
|
// straight to `completed`.
|
|
_unregisterActive();
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus);
|
|
_watchedImageStore?.removeListener(_onImageStoreChanged);
|
|
_unregisterActive();
|
|
_scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom);
|
|
_textFieldFocusNode.removeListener(_onTextFieldFocusChange);
|
|
_textFieldFocusNode.dispose();
|
|
_textController.dispose();
|
|
_searchController.dispose();
|
|
_highlightTimer?.cancel();
|
|
_scrollController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
void _setReplyingTo(ChannelMessage message) {
|
|
setState(() {
|
|
_replyingToMessage = message;
|
|
_useReplyRegion = message.region?.isNotEmpty ?? false;
|
|
});
|
|
// Replying means typing next: open the keyboard on the composer.
|
|
_textFieldFocusNode.requestFocus();
|
|
}
|
|
|
|
void _cancelReply() {
|
|
setState(() {
|
|
_replyingToMessage = null;
|
|
_useReplyRegion = false;
|
|
});
|
|
}
|
|
|
|
Future<void> _scrollToMessage(String messageId, {bool quiet = false}) async {
|
|
// A message hidden by the filter is represented by its ghost row (or the
|
|
// nearest visible row in hide mode).
|
|
final key =
|
|
_messageKeys[_transcriptLayout?.entryIdFor(messageId) ?? messageId];
|
|
if (key == null) {
|
|
// The auto unread-jump can resolve a frame after navigating away;
|
|
// a deactivated context can't host a snackbar.
|
|
if (quiet || !mounted || !context.mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.chat_originalMessageNotFound),
|
|
duration: const Duration(seconds: 2),
|
|
);
|
|
return;
|
|
}
|
|
|
|
final targetContext = key.currentContext;
|
|
if (targetContext == null) return;
|
|
|
|
await Scrollable.ensureVisible(
|
|
targetContext,
|
|
duration: const Duration(milliseconds: 300),
|
|
curve: Curves.easeInOut,
|
|
alignment: 0.3,
|
|
);
|
|
}
|
|
|
|
Widget _channelIcon(Channel channel) {
|
|
// Determine icon based on channel type
|
|
final ChannelType channelType = Channel.getChannelType(
|
|
channel,
|
|
_communityIndex,
|
|
);
|
|
final bool isCommunityChannel = Channel.isCommunityChannel(channelType);
|
|
IconData icon;
|
|
switch (channelType) {
|
|
case ChannelType.communityPublic:
|
|
icon = Icons.groups;
|
|
case ChannelType.communityHashtag:
|
|
icon = Icons.tag;
|
|
case ChannelType.public:
|
|
icon = Icons.public;
|
|
case ChannelType.hashtag:
|
|
icon = Icons.tag;
|
|
case ChannelType.private:
|
|
icon = Icons.lock;
|
|
}
|
|
return Stack(
|
|
children: [
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 3),
|
|
child: _communitiesLoaded
|
|
? Icon(icon, size: 20)
|
|
: SizedBox.square(dimension: 20),
|
|
),
|
|
if (isCommunityChannel)
|
|
Positioned(
|
|
right: 0,
|
|
bottom: 0,
|
|
child: Container(
|
|
width: 12,
|
|
height: 12,
|
|
decoration: BoxDecoration(
|
|
color: MeshPalette.magenta,
|
|
shape: BoxShape.circle,
|
|
border: Border.all(
|
|
color: Theme.of(context).cardColor,
|
|
width: 2,
|
|
),
|
|
),
|
|
child: const Icon(Icons.people, size: 8, color: MeshPalette.ink),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
bool _searching = false;
|
|
String _searchQuery = '';
|
|
final TextEditingController _searchController = TextEditingController();
|
|
|
|
bool get _showSearchResults => _searching && _searchQuery.trim().isNotEmpty;
|
|
|
|
void _openSearch() => setState(() => _searching = true);
|
|
|
|
void _closeSearch() {
|
|
_searchController.clear();
|
|
setState(() {
|
|
_searching = false;
|
|
_searchQuery = '';
|
|
});
|
|
}
|
|
|
|
Widget _buildSearchField() {
|
|
return CallbackShortcuts(
|
|
bindings: {
|
|
const SingleActivator(LogicalKeyboardKey.escape): _closeSearch,
|
|
},
|
|
child: TextField(
|
|
controller: _searchController,
|
|
autofocus: true,
|
|
textInputAction: TextInputAction.search,
|
|
style: const TextStyle(fontSize: 16),
|
|
decoration: InputDecoration(
|
|
hintText: context.l10n.chatSearch_hint,
|
|
border: InputBorder.none,
|
|
),
|
|
onChanged: (value) => setState(() => _searchQuery = value),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildSearchResults(
|
|
Future<List<ChatSearchEntry>> Function() loadEntries,
|
|
) {
|
|
return ChatSearchResults(
|
|
query: _searchQuery.trim(),
|
|
loadEntries: loadEntries,
|
|
textScale: context.watch<ChatTextScaleService>().scale,
|
|
onSelect: (entry) => unawaited(_jumpToSearchResult(entry.id)),
|
|
);
|
|
}
|
|
|
|
/// Message briefly highlighted after jumping to it from search.
|
|
String? _highlightedMessageId;
|
|
Timer? _highlightTimer;
|
|
|
|
/// Closes search and scrolls the transcript to [messageId], loading older
|
|
/// pages first when the message is further back than what is loaded.
|
|
Future<void> _jumpToSearchResult(String messageId) async {
|
|
FocusScope.of(context).unfocus();
|
|
_closeSearch();
|
|
final connector = context.read<MeshCoreConnector>();
|
|
bool loaded() => connector
|
|
.getChannelMessages(widget.channel)
|
|
.any((m) => m.messageId == messageId);
|
|
for (var page = 0; page < 500 && !loaded(); page++) {
|
|
if (!mounted || _olderHistoryExhausted) break;
|
|
if (_isLoadingOlder) {
|
|
await Future<void>.delayed(const Duration(milliseconds: 50));
|
|
continue;
|
|
}
|
|
await _loadOlderMessages();
|
|
}
|
|
// Let the transcript (rebuilt after closing search) lay out.
|
|
await WidgetsBinding.instance.endOfFrame;
|
|
if (!mounted) return;
|
|
final layout = _transcriptLayout;
|
|
final index = layout == null || !loaded()
|
|
? -1
|
|
: layout.ids.indexOf(layout.entryIdFor(messageId));
|
|
final found =
|
|
index >= 0 &&
|
|
await scrollListToIndex(
|
|
controller: _scrollController,
|
|
targetIndex: index,
|
|
itemCount: layout!.length,
|
|
isMounted: () => mounted,
|
|
);
|
|
if (!mounted) return;
|
|
if (!found) {
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.chatSearch_jumpFailed),
|
|
);
|
|
return;
|
|
}
|
|
_highlightTimer?.cancel();
|
|
setState(() => _highlightedMessageId = layout.entryIdFor(messageId));
|
|
_highlightTimer = Timer(const Duration(seconds: 2), () {
|
|
if (mounted) setState(() => _highlightedMessageId = null);
|
|
});
|
|
}
|
|
|
|
Widget _menuRow(IconData icon, String label, {Color? color}) =>
|
|
MeshMenuItemRow(icon: icon, label: label, color: color);
|
|
|
|
// Region lives here (and on a tap of the title) so the channel name keeps
|
|
// its room in the app bar; so does the notification mode.
|
|
Widget _buildOverflowMenu(BuildContext context) {
|
|
final muteKey = widget.channel.muteKey;
|
|
final error = Theme.of(context).colorScheme.error;
|
|
return PopupMenuButton<String>(
|
|
icon: const Icon(Icons.more_vert),
|
|
onSelected: (value) {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
switch (value) {
|
|
case 'messageFilter':
|
|
_toggleChannelFiltering();
|
|
case 'notifications':
|
|
showChannelNotificationModeSheet(context, muteKey);
|
|
case 'region':
|
|
openRegionSelectDialog(widget.channel);
|
|
case 'editChannel':
|
|
showEditChannelSheet(
|
|
context,
|
|
connector,
|
|
widget.channel,
|
|
onSaved: _onChannelEdited,
|
|
);
|
|
case 'background':
|
|
showChatBackgroundSheet(
|
|
context,
|
|
ChatBackgroundService.channelKey(widget.channel),
|
|
);
|
|
case 'clearChat':
|
|
_confirmClearChat();
|
|
case 'deleteChannel':
|
|
confirmDeleteChannel(
|
|
context,
|
|
connector,
|
|
widget.channel,
|
|
onDeleted: () {
|
|
if (mounted) Navigator.of(context).pop();
|
|
},
|
|
);
|
|
}
|
|
},
|
|
itemBuilder: (context) {
|
|
final notificationMode = context
|
|
.read<AppSettingsService>()
|
|
.getChannelNotificationMode(muteKey);
|
|
final readOnly = isRadioReadOnly(context.read<MeshCoreConnector>());
|
|
return [
|
|
if (_messageFilter case final filter? when filter.settings.enabled)
|
|
PopupMenuItem(
|
|
value: 'messageFilter',
|
|
child: _menuRow(
|
|
filter.isChannelFiltered(_messageFilterChannelId)
|
|
? Icons.check_box
|
|
: Icons.check_box_outline_blank,
|
|
context.l10n.messageFilter_channelToggle,
|
|
),
|
|
),
|
|
PopupMenuItem(
|
|
value: 'notifications',
|
|
child: _menuRow(
|
|
channelNotificationModeIcon(notificationMode),
|
|
context.l10n.channels_notificationModeTooltip(
|
|
channelNotificationModeLabel(context, notificationMode),
|
|
),
|
|
),
|
|
),
|
|
PopupMenuItem(
|
|
value: 'region',
|
|
child: _menuRow(
|
|
Icons.landscape,
|
|
context.l10n.channels_regionSelect_Title,
|
|
),
|
|
),
|
|
PopupMenuItem(
|
|
value: 'editChannel',
|
|
enabled: !readOnly,
|
|
child: _menuRow(Icons.settings, context.l10n.channels_editChannel),
|
|
),
|
|
PopupMenuItem(
|
|
value: 'background',
|
|
child: _menuRow(Icons.wallpaper, context.l10n.chatBackground_title),
|
|
),
|
|
PopupMenuItem(
|
|
value: 'clearChat',
|
|
enabled: !readOnly,
|
|
child: _menuRow(
|
|
Icons.delete,
|
|
context.l10n.contact_clearChat,
|
|
color: readOnly ? null : error,
|
|
),
|
|
),
|
|
PopupMenuItem(
|
|
value: 'deleteChannel',
|
|
enabled: !readOnly,
|
|
child: _menuRow(
|
|
Icons.delete_forever,
|
|
context.l10n.channels_deleteChannel,
|
|
color: readOnly ? null : error,
|
|
),
|
|
),
|
|
];
|
|
},
|
|
);
|
|
}
|
|
|
|
/// A rename or new PSK changes what this screen is keyed on (mute key,
|
|
/// type, stored history), so reopen it on the saved channel.
|
|
void _onChannelEdited(Channel saved) {
|
|
if (!mounted) return;
|
|
final old = widget.channel;
|
|
if (saved.name == old.name && saved.pskHex == old.pskHex) return;
|
|
Navigator.of(context).pushReplacement(
|
|
PageRouteBuilder<void>(
|
|
transitionDuration: Duration.zero,
|
|
reverseTransitionDuration: Duration.zero,
|
|
pageBuilder: (_, _, _) => ChannelChatScreen(channel: saved),
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<List<ChatSearchEntry>> _loadSearchEntries() async {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final messages = await connector.allChannelMessagesForSearch(
|
|
widget.channel.index,
|
|
);
|
|
return [
|
|
// Messages the filter caught stay out of search, as in the chat.
|
|
for (final m in messages)
|
|
if (!m.isFiltered)
|
|
ChatSearchEntry(
|
|
id: m.messageId,
|
|
sender: m.senderName,
|
|
text: m.text,
|
|
translatedText: m.translatedText,
|
|
time: m.receivedAt,
|
|
matchSender: true,
|
|
),
|
|
];
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return PopScope(
|
|
canPop: !_searching && !_selecting,
|
|
onPopInvokedWithResult: (didPop, _) {
|
|
if (didPop) return;
|
|
if (_selecting) {
|
|
_clearSelection();
|
|
} else if (_searching) {
|
|
_closeSearch();
|
|
}
|
|
},
|
|
child: _buildScaffold(context),
|
|
);
|
|
}
|
|
|
|
Widget _buildScaffold(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: _selecting
|
|
? _buildSelectionAppBar(context)
|
|
: AppBar(
|
|
leading: _searching
|
|
? IconButton(
|
|
tooltip: context.l10n.chatSearch_close,
|
|
icon: const Icon(Icons.arrow_back),
|
|
onPressed: _closeSearch,
|
|
)
|
|
: null,
|
|
title: _searching
|
|
? _buildSearchField()
|
|
: GestureDetector(
|
|
behavior: HitTestBehavior.opaque,
|
|
onTap: () => openRegionSelectDialog(widget.channel),
|
|
child: Row(
|
|
children: [
|
|
// A hashtag name already starts with '#'; a # icon
|
|
// before it would read "# #name".
|
|
if (!widget.channel.name.startsWith('#')) ...[
|
|
_channelIcon(widget.channel),
|
|
const SizedBox(width: 8),
|
|
],
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
widget.channel.name.isEmpty
|
|
? context.l10n.channels_channelIndex(
|
|
widget.channel.index,
|
|
)
|
|
: widget.channel.name,
|
|
style: const TextStyle(fontSize: 16),
|
|
maxLines: 1,
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
Consumer<MeshCoreConnector>(
|
|
builder: (context, connector, _) {
|
|
// Hashtag channels get no type label: the # icon
|
|
// and name already say it, and the title needs the
|
|
// room.
|
|
final privacy =
|
|
switch (Channel.getChannelType(
|
|
widget.channel,
|
|
_communityIndex,
|
|
)) {
|
|
ChannelType.public =>
|
|
context.l10n.channels_public,
|
|
ChannelType.hashtag => null,
|
|
ChannelType.private =>
|
|
context.l10n.channels_private,
|
|
ChannelType.communityPublic =>
|
|
context
|
|
.l10n
|
|
.community_publicChannel,
|
|
ChannelType.communityHashtag => null,
|
|
};
|
|
final ownRegion = connector
|
|
.getChannelRegion(widget.channel.index);
|
|
final region = connector
|
|
.getEffectiveChannelRegion(
|
|
widget.channel.index,
|
|
);
|
|
final defaultSuffix = ownRegion.isEmpty
|
|
? ' ${context.l10n.channels_regionDefaultSuffix}'
|
|
: '';
|
|
final radioDefault =
|
|
connector.defaultFloodScopeName;
|
|
final regionText = region.isNotEmpty
|
|
? '${context.l10n.channels_regionSetTo(region)}$defaultSuffix'
|
|
: radioDefault != null &&
|
|
connector
|
|
.channelUsesRadioDefaultScope(
|
|
widget.channel.index,
|
|
)
|
|
? '${context.l10n.channels_regionSetTo(radioDefault)} ${context.l10n.channels_regionRadioDefaultSuffix}'
|
|
: null;
|
|
final subtitle = [
|
|
?privacy,
|
|
?regionText,
|
|
].join(' • ');
|
|
if (subtitle.isEmpty) {
|
|
return const SizedBox.shrink();
|
|
}
|
|
return Text(
|
|
subtitle,
|
|
overflow: TextOverflow.ellipsis,
|
|
style: const TextStyle(fontSize: 12),
|
|
);
|
|
},
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
centerTitle: false,
|
|
bottom: const SyncProgressAppBarBottom(),
|
|
actionsPadding: const EdgeInsetsDirectional.only(end: 4),
|
|
// While searching the field gets the whole bar; the leading
|
|
// arrow closes the search.
|
|
actions: _searching
|
|
? null
|
|
: [
|
|
const RadioStatsIconButton(),
|
|
IconButton(
|
|
tooltip: context.l10n.chatSearch_tooltip,
|
|
icon: const Icon(Icons.search),
|
|
onPressed: _openSearch,
|
|
),
|
|
_buildOverflowMenu(context),
|
|
],
|
|
),
|
|
body: _showSearchResults
|
|
? _buildSearchResults(_loadSearchEntries)
|
|
: SafeArea(
|
|
top: false,
|
|
child: Column(
|
|
children: [
|
|
Expanded(
|
|
child: ChatBackdrop(
|
|
key: _messageAreaKey,
|
|
chatKey: ChatBackgroundService.channelKey(widget.channel),
|
|
child: Consumer<MeshCoreConnector>(
|
|
builder: (context, connector, child) {
|
|
final messages = connector.getChannelMessages(
|
|
widget.channel,
|
|
);
|
|
// A filtered message must not trigger holiday effects.
|
|
final newest = connector.latestVisibleChannelMessage(
|
|
widget.channel,
|
|
);
|
|
_holidayWatcher.onNewest(
|
|
context,
|
|
id: newest?.messageId,
|
|
texts: [newest?.text, newest?.translatedText],
|
|
receivedAt: newest?.receivedAt,
|
|
originOf: () => newestMessageOrigin(
|
|
_messageAreaKey,
|
|
isOutgoing: newest?.isOutgoing ?? false,
|
|
),
|
|
);
|
|
final layout = _transcriptLayoutFor(
|
|
context,
|
|
messages,
|
|
);
|
|
// Fewer entries than messages means the filter hid or
|
|
// collapsed some; make sure older history stays reachable.
|
|
final hidesMessages = layout.length < messages.length;
|
|
if (hidesMessages) _scheduleHiddenHistoryBackfill();
|
|
|
|
if (layout.length == 0) {
|
|
final canLoadOlder =
|
|
hidesMessages && !_olderHistoryExhausted;
|
|
return EmptyState(
|
|
icon: widget.channel.isPublicChannel
|
|
? Icons.public
|
|
: Icons.tag,
|
|
title: context.l10n.chat_noMessages,
|
|
subtitle: context.l10n.chat_sendMessageTo(
|
|
widget.channel.name.isEmpty
|
|
? context.l10n.channels_channelIndex(
|
|
widget.channel.index,
|
|
)
|
|
: widget.channel.name,
|
|
),
|
|
// Past the automatic page cap, filtered messages may
|
|
// still hide older conversation: let the user ask.
|
|
action: canLoadOlder
|
|
? FilledButton.tonal(
|
|
onPressed: _isLoadingOlder
|
|
? null
|
|
: _loadOlderHiddenHistory,
|
|
child: Text(
|
|
context.l10n.chat_loadOlderMessages,
|
|
),
|
|
)
|
|
: null,
|
|
);
|
|
}
|
|
|
|
final urlImagesEnabled = connector
|
|
.isChannelUrlImagesEnabled(widget.channel.index);
|
|
final rowCount = layout.length;
|
|
final itemCount =
|
|
rowCount + (_isLoadingOlder ? 1 : 0);
|
|
|
|
// Auto-scroll to bottom if user is already at bottom
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (!mounted) return;
|
|
if (_channelSkipNextBottomSnap) {
|
|
_channelSkipNextBottomSnap = false;
|
|
return;
|
|
}
|
|
_scrollController.scrollToBottomIfAtBottom();
|
|
});
|
|
|
|
return Stack(
|
|
children: [
|
|
ChatZoomWrapper(
|
|
child: ListView.builder(
|
|
reverse: true, // List grows from bottom up
|
|
controller: _scrollController,
|
|
padding: const EdgeInsets.all(8),
|
|
itemCount: itemCount,
|
|
itemBuilder: (context, index) {
|
|
// Loading indicator now appears at end (bottom) of reversed list
|
|
if (_isLoadingOlder &&
|
|
index == itemCount - 1) {
|
|
return const Padding(
|
|
padding: EdgeInsets.symmetric(
|
|
vertical: 16,
|
|
),
|
|
child: Center(
|
|
child: SizedBox(
|
|
width: 20,
|
|
height: 20,
|
|
child: CircularProgressIndicator(
|
|
strokeWidth: 2,
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
final row = layout.rowAt(index, messages);
|
|
final GlobalKey messageKey;
|
|
if (layout.keyedIndices.contains(index)) {
|
|
messageKey = _messageKeys.putIfAbsent(
|
|
row.id,
|
|
GlobalKey.new,
|
|
);
|
|
} else {
|
|
messageKey = GlobalKey();
|
|
}
|
|
final dividerId = _unreadDividerMessageId;
|
|
final isUnreadAnchor =
|
|
dividerId != null &&
|
|
row.id == layout.entryIdFor(dividerId);
|
|
return Container(
|
|
key: messageKey,
|
|
child: Builder(
|
|
builder: (context) {
|
|
final textScale = context
|
|
.select<
|
|
ChatTextScaleService,
|
|
double
|
|
>((service) => service.scale);
|
|
final message = row.message;
|
|
final ghost = row.ghost;
|
|
Widget bubble;
|
|
if (ghost != null) {
|
|
bubble = _buildFilteredGhost(
|
|
ghost,
|
|
textScale,
|
|
expanded: row.ghostExpanded,
|
|
urlImagesEnabled:
|
|
urlImagesEnabled,
|
|
);
|
|
} else if (message != null) {
|
|
bubble = _buildMessageBubble(
|
|
message,
|
|
textScale,
|
|
urlImagesEnabled,
|
|
showFilterBanner:
|
|
layout.filterActive &&
|
|
message.isFiltered,
|
|
);
|
|
} else {
|
|
bubble = _buildImageBubble(
|
|
row.image!,
|
|
textScale,
|
|
);
|
|
}
|
|
final startsDay =
|
|
index == rowCount - 1 ||
|
|
!isSameChatDay(
|
|
layout
|
|
.rowAt(index + 1, messages)
|
|
.receivedAt,
|
|
row.receivedAt,
|
|
);
|
|
if (row.id == _highlightedMessageId) {
|
|
bubble = AnimatedContainer(
|
|
duration: const Duration(
|
|
milliseconds: 300,
|
|
),
|
|
decoration: BoxDecoration(
|
|
color: Theme.of(context)
|
|
.colorScheme
|
|
.primary
|
|
.withValues(alpha: 0.18),
|
|
borderRadius:
|
|
BorderRadius.circular(
|
|
MeshRadii.md,
|
|
),
|
|
),
|
|
child: bubble,
|
|
);
|
|
}
|
|
if (isUnreadAnchor || startsDay) {
|
|
return Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
if (startsDay)
|
|
ChatDaySeparator(
|
|
day: row.receivedAt,
|
|
),
|
|
if (isUnreadAnchor)
|
|
const UnreadDivider(),
|
|
bubble,
|
|
],
|
|
);
|
|
}
|
|
return bubble;
|
|
},
|
|
),
|
|
);
|
|
},
|
|
),
|
|
),
|
|
JumpToBottomButton(
|
|
scrollController: _scrollController,
|
|
),
|
|
],
|
|
);
|
|
},
|
|
),
|
|
),
|
|
),
|
|
_buildInputBar(),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
/// Whether [m] counts toward the unread badge and divider. Filtered
|
|
/// messages don't while the filter hides them here (the connector never
|
|
/// counts them on arrival); with filtering off for this channel they show
|
|
/// as ordinary messages and count like ordinary messages.
|
|
bool _countsAsUnread(ChannelMessage m) {
|
|
if (m.isOutgoing) return false;
|
|
if (!m.isFiltered) return true;
|
|
return !(_messageFilter?.isChannelFiltered(_messageFilterChannelId) ??
|
|
false);
|
|
}
|
|
|
|
void _markAsUnread(ChannelMessage message) {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final messages = connector.getChannelMessages(widget.channel);
|
|
var count = 0;
|
|
var found = false;
|
|
for (final m in messages) {
|
|
if (m.messageId == message.messageId) found = true;
|
|
if (found && _countsAsUnread(m)) count++;
|
|
}
|
|
connector.setChannelUnreadCount(widget.channel.index, count);
|
|
}
|
|
|
|
Widget _buildMessageBubble(
|
|
ChannelMessage message,
|
|
double textScale,
|
|
bool urlImagesEnabled, {
|
|
bool showFilterBanner = false,
|
|
}) {
|
|
final settingsService = context.watch<AppSettingsService>();
|
|
final publicIpfsGateway = settingsService.settings.publicIpfsGateway;
|
|
final enableTracing = settingsService.settings.enableMessageTracing;
|
|
final regionOnHopsLine = settingsService.settings.regionOnHopsLine;
|
|
final isOutgoing = message.isOutgoing;
|
|
final scheme = Theme.of(context).colorScheme;
|
|
final gifId = GifHelper.parseGif(message.text);
|
|
final poi = parseMarkerText(message.text);
|
|
final contactShare = parseContactShare(message.text);
|
|
final translatedDisplayText =
|
|
message.translatedText != null &&
|
|
message.translatedText!.trim().isNotEmpty
|
|
? message.translatedText!.trim()
|
|
: message.text;
|
|
final originalDisplayText = message.isOutgoing
|
|
? message.originalText
|
|
: (translatedDisplayText != message.text ? message.text : null);
|
|
final displayPath = message.pathBytes.isNotEmpty
|
|
? message.pathBytes
|
|
: (message.pathVariants.isNotEmpty
|
|
? message.pathVariants.first
|
|
: Uint8List(0));
|
|
final displayPathHashWidth =
|
|
message.pathHashWidth ??
|
|
context.read<MeshCoreConnector>().pathHashByteWidth;
|
|
final displayHopCount = _displayHopCount(
|
|
displayPath,
|
|
displayPathHashWidth,
|
|
message.pathLength,
|
|
);
|
|
|
|
final colors = MessageBubbleColors.of(context, isOutgoing: isOutgoing);
|
|
final textColor = colors.text;
|
|
final metaColor = colors.meta;
|
|
const bodyFontSize = 14.0;
|
|
|
|
Widget buildTextContent() {
|
|
return Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.end,
|
|
children: [
|
|
Flexible(
|
|
child: TranslatedMessageContent(
|
|
displayText: translatedDisplayText,
|
|
originalText: originalDisplayText,
|
|
style: TextStyle(
|
|
color: textColor,
|
|
fontSize: bodyFontSize * textScale,
|
|
),
|
|
originalStyle: TextStyle(
|
|
fontSize: bodyFontSize * textScale,
|
|
fontStyle: FontStyle.italic,
|
|
color: textColor.withValues(alpha: 0.72),
|
|
),
|
|
onSecondaryTap: PlatformInfo.isDesktop
|
|
? () => _showMessageActions(message)
|
|
: null,
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
const maxSwipeOffset = 64.0;
|
|
const replySwipeThreshold = 64.0;
|
|
final messageBody = LayoutBuilder(
|
|
builder: (context, constraints) => Column(
|
|
crossAxisAlignment: isOutgoing
|
|
? CrossAxisAlignment.end
|
|
: CrossAxisAlignment.start,
|
|
children: [
|
|
Row(
|
|
mainAxisAlignment: isOutgoing
|
|
? MainAxisAlignment.end
|
|
: MainAxisAlignment.start,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
if (!isOutgoing) ...[
|
|
_buildAvatar(message.senderName, textScale),
|
|
const SizedBox(width: 6),
|
|
],
|
|
Flexible(
|
|
child: GestureDetector(
|
|
onLongPress: () => _selecting
|
|
? _toggleSelected(message)
|
|
: _showMessageActions(message),
|
|
onSecondaryTapUp: PlatformInfo.isDesktop
|
|
? (_) => _showMessageActions(message)
|
|
: null,
|
|
child: MessageBubbleFrame(
|
|
isOutgoing: isOutgoing,
|
|
compact: gifId != null,
|
|
maxWidth: constraints.maxWidth,
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
if (!isOutgoing) ...[
|
|
Padding(
|
|
padding: gifId != null
|
|
? const EdgeInsets.only(
|
|
left: 8,
|
|
top: 4,
|
|
bottom: 4,
|
|
)
|
|
: EdgeInsets.zero,
|
|
child: Text(
|
|
message.senderName,
|
|
style: TextStyle(
|
|
fontSize: 13 * textScale,
|
|
fontWeight: FontWeight.w700,
|
|
color: textColor,
|
|
),
|
|
),
|
|
),
|
|
if (gifId == null) const SizedBox(height: 2),
|
|
],
|
|
if (showFilterBanner)
|
|
FilteredMessageBanner(
|
|
reason: messageFilterReasonLabel(
|
|
context.l10n,
|
|
message.filterReason,
|
|
message.filterDetail,
|
|
),
|
|
color: textColor,
|
|
textScale: textScale,
|
|
onNotSpam: () => _markNotSpam(message),
|
|
onHide: () => _hideFilteredMessage(message),
|
|
),
|
|
if (message.replyToMessageId != null) ...[
|
|
_buildReplyPreview(message, textScale),
|
|
const SizedBox(height: 8),
|
|
],
|
|
if (contactShare != null)
|
|
SharedContactCard(
|
|
share: contactShare,
|
|
isOutgoing: isOutgoing,
|
|
textScale: textScale,
|
|
textColor: textColor,
|
|
metaColor: textColor.withValues(alpha: 0.7),
|
|
)
|
|
else if (poi != null)
|
|
_buildPoiMessage(
|
|
context,
|
|
poi,
|
|
isOutgoing,
|
|
textScale,
|
|
message.senderName,
|
|
)
|
|
else if (gifId != null)
|
|
Stack(
|
|
children: [
|
|
ClipRRect(
|
|
borderRadius: BorderRadius.circular(8),
|
|
child: GifMessage(
|
|
url:
|
|
'https://media.giphy.com/media/$gifId/giphy.gif',
|
|
backgroundColor: Colors.transparent,
|
|
fallbackTextColor: textColor.withValues(
|
|
alpha: 0.7,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
)
|
|
else if (urlImagesEnabled)
|
|
MessageUrlImageFutureBuilder(
|
|
messageId: message.messageId,
|
|
text: message.text,
|
|
publicGateway: publicIpfsGateway,
|
|
builder: (context, snapshot) {
|
|
final imageAttachment = snapshot.data;
|
|
|
|
if (imageAttachment != null) {
|
|
return Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(
|
|
vertical: 4,
|
|
),
|
|
child: Align(
|
|
alignment: isOutgoing
|
|
? Alignment.centerRight
|
|
: Alignment.centerLeft,
|
|
child: MessageUrlImagePreview(
|
|
imageUrl: imageAttachment,
|
|
),
|
|
),
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.only(top: 8),
|
|
child: TranslatedMessageContent(
|
|
displayText: translatedDisplayText,
|
|
originalText: originalDisplayText,
|
|
style: TextStyle(
|
|
color: textColor,
|
|
fontSize: bodyFontSize * textScale,
|
|
),
|
|
originalStyle: TextStyle(
|
|
fontSize: bodyFontSize * textScale,
|
|
fontStyle: FontStyle.italic,
|
|
color: textColor.withValues(
|
|
alpha: 0.72,
|
|
),
|
|
),
|
|
onSecondaryTap: PlatformInfo.isDesktop
|
|
? () => _showMessageActions(message)
|
|
: null,
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
return buildTextContent();
|
|
},
|
|
)
|
|
else
|
|
Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
if (settingsService.settings.loadLinkImages &&
|
|
MessageUrlImageHelper.hasPotentialImageUrl(
|
|
message.text,
|
|
))
|
|
Padding(
|
|
padding: const EdgeInsets.only(bottom: 4),
|
|
child: Text(
|
|
context.l10n.urlImage_possible,
|
|
style: TextStyle(
|
|
color: metaColor,
|
|
fontSize: 12 * textScale,
|
|
),
|
|
),
|
|
),
|
|
buildTextContent(),
|
|
],
|
|
),
|
|
if (displayPath.isNotEmpty) ...[
|
|
const SizedBox(height: 3),
|
|
Padding(
|
|
padding: gifId != null
|
|
? const EdgeInsets.symmetric(horizontal: 8)
|
|
: EdgeInsets.zero,
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
_RouteRegionChips(
|
|
sameLine: regionOnHopsLine,
|
|
children: [
|
|
RouteChip(
|
|
isDirect: (message.pathLength ?? -1) >= 0,
|
|
hops: displayHopCount,
|
|
),
|
|
if (message.region?.isNotEmpty ?? false)
|
|
Padding(
|
|
padding: regionOnHopsLine
|
|
? EdgeInsets.zero
|
|
: const EdgeInsets.only(top: 2),
|
|
child: Container(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 6,
|
|
vertical: 2,
|
|
),
|
|
decoration: BoxDecoration(
|
|
color: scheme.surfaceContainerHigh,
|
|
borderRadius: BorderRadius.circular(
|
|
MeshRadii.xs,
|
|
),
|
|
border: Border.all(
|
|
color: scheme.outlineVariant,
|
|
),
|
|
),
|
|
child: Text(
|
|
_displayRegion(message.region!),
|
|
style: MeshTheme.mono(
|
|
fontSize: 12 * textScale,
|
|
color: metaColor,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
if (enableTracing) ...[
|
|
const SizedBox(width: 4),
|
|
Flexible(
|
|
child: Text(
|
|
context.l10n.channels_via(
|
|
_formatPathPrefixes(
|
|
displayPath,
|
|
displayPathHashWidth,
|
|
),
|
|
),
|
|
maxLines: 2,
|
|
overflow: TextOverflow.ellipsis,
|
|
style: MeshTheme.mono(
|
|
fontSize: 12 * textScale,
|
|
color: metaColor,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
],
|
|
),
|
|
),
|
|
],
|
|
const SizedBox(height: 3),
|
|
Padding(
|
|
padding: gifId != null
|
|
? const EdgeInsets.only(
|
|
left: 8,
|
|
right: 8,
|
|
bottom: 4,
|
|
)
|
|
: EdgeInsets.zero,
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(
|
|
formatChatTime(context, message.timestamp),
|
|
style: MeshTheme.mono(
|
|
fontSize: 12 * textScale,
|
|
color: metaColor,
|
|
),
|
|
),
|
|
if (message.hasFutureTimestamp) ...[
|
|
const SizedBox(width: 4),
|
|
FutureTimestampIndicator(size: 16 * textScale),
|
|
],
|
|
if (enableTracing &&
|
|
!isOutgoing &&
|
|
message.repeatCount > 0) ...[
|
|
const SizedBox(width: 6),
|
|
Icon(
|
|
Icons.repeat,
|
|
size: 14 * textScale,
|
|
color: metaColor,
|
|
),
|
|
const SizedBox(width: 2),
|
|
Text(
|
|
'${message.repeatCount}',
|
|
style: MeshTheme.mono(
|
|
fontSize: 12 * textScale,
|
|
color: metaColor,
|
|
),
|
|
),
|
|
],
|
|
if (isOutgoing) ...[
|
|
const SizedBox(width: 4),
|
|
MessageStatusIcon(
|
|
size: 16 * textScale,
|
|
isAcked: false,
|
|
isChannel: true,
|
|
repeatCount: message.repeatCount,
|
|
resendProgress: context
|
|
.read<MeshCoreConnector>()
|
|
.channelResendProgress(message.messageId),
|
|
hopShortfall: context
|
|
.read<MeshCoreConnector>()
|
|
.channelHopShortfall(message.messageId),
|
|
isPending:
|
|
message.status ==
|
|
ChannelMessageStatus.pending,
|
|
isFailed:
|
|
message.status ==
|
|
ChannelMessageStatus.failed,
|
|
onColor: metaColor,
|
|
),
|
|
],
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
if (message.reactions.isNotEmpty) ...[
|
|
const SizedBox(height: 4),
|
|
Padding(
|
|
padding: EdgeInsets.only(left: isOutgoing ? 0 : 42),
|
|
child: ReactionChips(
|
|
reactions: message.reactions,
|
|
onTap: (_) => _showReactionsReport(message),
|
|
),
|
|
),
|
|
],
|
|
],
|
|
),
|
|
);
|
|
|
|
if (_selecting) {
|
|
return _buildSelectableRow(message, messageBody);
|
|
}
|
|
if (!isOutgoing &&
|
|
!PlatformInfo.isDesktop &&
|
|
!isRadioReadOnly(context.read<MeshCoreConnector>())) {
|
|
return _SwipeReplyBubble(
|
|
maxSwipeOffset: maxSwipeOffset,
|
|
replySwipeThreshold: replySwipeThreshold,
|
|
onReplyTriggered: () => _setReplyingTo(message),
|
|
hintBuilder: ({required isStart}) =>
|
|
_buildReplySwipeHint(isStart: isStart),
|
|
child: messageBody,
|
|
);
|
|
} else {
|
|
return Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 3),
|
|
child: messageBody,
|
|
);
|
|
}
|
|
}
|
|
|
|
Widget _buildReplySwipeHint({required bool isStart}) {
|
|
final colorScheme = Theme.of(context).colorScheme;
|
|
final content = Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Icon(Icons.reply, color: colorScheme.primary),
|
|
const SizedBox(width: 6),
|
|
Text(
|
|
context.l10n.chat_reply,
|
|
style: TextStyle(
|
|
color: colorScheme.primary,
|
|
fontWeight: FontWeight.w600,
|
|
),
|
|
),
|
|
],
|
|
);
|
|
|
|
return Container(
|
|
alignment: isStart ? Alignment.centerLeft : Alignment.centerRight,
|
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
|
color: colorScheme.primary.withValues(alpha: 0.08),
|
|
child: isStart
|
|
? content
|
|
: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(
|
|
context.l10n.chat_reply,
|
|
style: TextStyle(
|
|
color: colorScheme.primary,
|
|
fontWeight: FontWeight.w600,
|
|
),
|
|
),
|
|
const SizedBox(width: 6),
|
|
Icon(Icons.reply, color: colorScheme.primary),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
/// Decoded preview of quoted text: a GIF thumbnail, a location label, or
|
|
/// the text itself — never the raw `g:`/marker payload. Shared by the reply
|
|
/// quote inside bubbles and the "Replying to" banner above the composer.
|
|
Widget _buildReplyContent(
|
|
String replyText,
|
|
double textScale, {
|
|
required Color color,
|
|
int maxLines = 2,
|
|
double gifSize = 80,
|
|
}) {
|
|
final colorScheme = Theme.of(context).colorScheme;
|
|
final gifId = GifHelper.parseGif(replyText);
|
|
final poi = parseMarkerText(replyText);
|
|
if (gifId != null) {
|
|
return ClipRRect(
|
|
borderRadius: BorderRadius.circular(4),
|
|
child: GifMessage(
|
|
url: 'https://media.giphy.com/media/$gifId/giphy.gif',
|
|
backgroundColor: colorScheme.surfaceContainerHighest,
|
|
fallbackTextColor: color,
|
|
maxSize: gifSize,
|
|
),
|
|
);
|
|
}
|
|
final contactShare = parseContactShare(replyText);
|
|
if (contactShare != null) {
|
|
return Row(
|
|
children: [
|
|
Icon(Icons.person_add_alt, size: 16, color: color),
|
|
const SizedBox(width: 4),
|
|
Flexible(
|
|
child: Text(
|
|
context.l10n.contactShare_preview(
|
|
contactShare.name.isEmpty
|
|
? contactShare.shortKey
|
|
: contactShare.name,
|
|
),
|
|
maxLines: 1,
|
|
overflow: TextOverflow.ellipsis,
|
|
style: TextStyle(fontSize: 12 * textScale, color: color),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
if (poi != null) {
|
|
return Row(
|
|
children: [
|
|
Icon(Icons.location_on_outlined, size: 16, color: color),
|
|
const SizedBox(width: 4),
|
|
Flexible(
|
|
child: Text(
|
|
context.l10n.chat_location,
|
|
maxLines: 1,
|
|
overflow: TextOverflow.ellipsis,
|
|
style: TextStyle(fontSize: 12 * textScale, color: color),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
return Text(
|
|
replyText,
|
|
maxLines: maxLines,
|
|
overflow: TextOverflow.ellipsis,
|
|
style: TextStyle(
|
|
fontSize: 12 * textScale,
|
|
color: color,
|
|
fontStyle: FontStyle.italic,
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildReplyPreview(ChannelMessage message, double textScale) {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final isOwnNode = message.replyToSenderName == connector.selfName;
|
|
final colorScheme = Theme.of(context).colorScheme;
|
|
final previewColor = colorScheme.onSurface.withValues(alpha: 0.7);
|
|
// The quoted text was copied when the reply arrived; if the quoted message
|
|
// is hidden by the filter, don't spell it out until it is revealed.
|
|
final quotedId = message.replyToMessageId;
|
|
final quoted = quotedId == null
|
|
? null
|
|
: _channelMessageById(
|
|
connector.getChannelMessages(widget.channel),
|
|
quotedId,
|
|
);
|
|
final concealed =
|
|
quoted != null &&
|
|
isReplyPreviewConcealed(
|
|
quotedIsFiltered: quoted.isFiltered,
|
|
filterActive:
|
|
_messageFilter?.isChannelFiltered(_messageFilterChannelId) ??
|
|
false,
|
|
quotedRevealed: _revealedFilteredIds.contains(quoted.messageId),
|
|
);
|
|
final contentPreview = concealed
|
|
? Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Icon(
|
|
Icons.visibility_off_outlined,
|
|
size: 16 * textScale,
|
|
color: previewColor,
|
|
),
|
|
const SizedBox(width: 6),
|
|
Flexible(
|
|
child: Text(
|
|
context.l10n.messageFilter_ghostSingle,
|
|
style: TextStyle(
|
|
fontSize: 13 * textScale,
|
|
fontStyle: FontStyle.italic,
|
|
color: previewColor,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
)
|
|
: _buildReplyContent(
|
|
message.replyToText ?? '',
|
|
textScale,
|
|
color: previewColor,
|
|
);
|
|
|
|
return GestureDetector(
|
|
onTap: () => _scrollToMessage(message.replyToMessageId!),
|
|
child: Container(
|
|
padding: const EdgeInsets.all(8),
|
|
decoration: BoxDecoration(
|
|
color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
|
|
borderRadius: BorderRadius.circular(MeshRadii.sm),
|
|
border: Border(
|
|
left: BorderSide(color: colorScheme.primary, width: 3),
|
|
),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
context.l10n.chat_replyTo(message.replyToSenderName ?? ''),
|
|
style: TextStyle(
|
|
fontSize: 12 * textScale,
|
|
fontWeight: FontWeight.bold,
|
|
color: isOwnNode ? colorScheme.primary : colorScheme.onSurface,
|
|
),
|
|
),
|
|
const SizedBox(height: 2),
|
|
contentPreview,
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
void _showReactionsReport(ChannelMessage message) {
|
|
final scheme = Theme.of(context).colorScheme;
|
|
showDialog(
|
|
context: context,
|
|
builder: (context) => AlertDialog(
|
|
title: Text(context.l10n.reaction_report),
|
|
content: SizedBox(
|
|
width: double.maxFinite,
|
|
child: Scrollbar(
|
|
child: ListView(
|
|
shrinkWrap: true,
|
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
|
children: message.reactionList().map((reaction) {
|
|
return Container(
|
|
padding: const EdgeInsetsDirectional.symmetric(vertical: 4),
|
|
child: Container(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 8,
|
|
vertical: 4,
|
|
),
|
|
decoration: BoxDecoration(
|
|
color: scheme.surfaceContainerHigh,
|
|
borderRadius: BorderRadius.circular(MeshRadii.pill),
|
|
border: Border.all(
|
|
color: scheme.outlineVariant,
|
|
width: 1,
|
|
),
|
|
),
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 8,
|
|
vertical: 4,
|
|
),
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(
|
|
reaction.emoji,
|
|
style: MeshTheme.emoji(fontSize: 16),
|
|
textHeightBehavior: const TextHeightBehavior(
|
|
applyHeightToFirstAscent: false,
|
|
applyHeightToLastDescent: false,
|
|
),
|
|
),
|
|
const SizedBox(width: 12),
|
|
Expanded(
|
|
child: Text(
|
|
reaction.senderName ??
|
|
context.l10n.reaction_unknownSender,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}).toList(),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildPoiMessage(
|
|
BuildContext context,
|
|
MarkerPayload poi,
|
|
bool isOutgoing,
|
|
double textScale,
|
|
String senderName, {
|
|
Widget? trailing,
|
|
}) {
|
|
final scheme = Theme.of(context).colorScheme;
|
|
final bubble = MeshBubbleTheme.of(context);
|
|
final textColor = isOutgoing ? bubble.meInk : scheme.onSurface;
|
|
final metaColor = textColor.withValues(alpha: 0.7);
|
|
|
|
return Row(
|
|
crossAxisAlignment: CrossAxisAlignment.center,
|
|
children: [
|
|
IconButton(
|
|
icon: Icon(Icons.location_on_outlined, color: scheme.primary),
|
|
padding: EdgeInsets.zero,
|
|
constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
|
|
onPressed: () {
|
|
final selfName =
|
|
context.read<MeshCoreConnector>().selfName ??
|
|
context.l10n.chat_me;
|
|
final fromName = isOutgoing ? selfName : senderName;
|
|
final key = buildSharedMarkerKey(
|
|
sourceId: 'channel:${widget.channel.index}',
|
|
label: poi.label,
|
|
fromName: fromName,
|
|
flags: poi.flags,
|
|
isChannel: true,
|
|
);
|
|
Navigator.push(
|
|
context,
|
|
MaterialPageRoute(
|
|
builder: (context) => MapScreen(
|
|
highlightPosition: poi.position,
|
|
highlightLabel: poi.label,
|
|
highlightMarkerKey: key,
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
const SizedBox(width: 8),
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
context.l10n.chat_poiShared,
|
|
style: TextStyle(
|
|
color: textColor,
|
|
fontWeight: FontWeight.w600,
|
|
fontSize: 14 * textScale,
|
|
),
|
|
),
|
|
if (poi.label.isNotEmpty)
|
|
Text(
|
|
poi.label,
|
|
style: TextStyle(color: metaColor, fontSize: 12 * textScale),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
if (trailing != null) ...[const SizedBox(width: 4), trailing],
|
|
],
|
|
);
|
|
}
|
|
|
|
/// The image codec, or null when it is not registered (screen tests).
|
|
ImageCodecService? get _imageCodec {
|
|
try {
|
|
return context.read<ImageCodecService>();
|
|
} on ProviderNotFoundException {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
void _explainImageCodecNotReady(ImageCodecService codec) {
|
|
final l10n = context.l10n;
|
|
final availability = codec.availability;
|
|
final String message;
|
|
switch (availability) {
|
|
case ImageCodecAvailability.downloading:
|
|
message = l10n.imageSend_codecDownloading;
|
|
case ImageCodecAvailability.unavailable:
|
|
message = codec.unavailableReason ?? l10n.imageSend_codecUnavailable;
|
|
case ImageCodecAvailability.disabled:
|
|
message = codec.needsModelDownload
|
|
? l10n.imageSend_modelNotDownloaded
|
|
: codec.statusReason ?? l10n.imageSend_codecDisabled;
|
|
case ImageCodecAvailability.ready:
|
|
return;
|
|
}
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(message),
|
|
action: availability == ImageCodecAvailability.disabled
|
|
? SnackBarAction(
|
|
label: l10n.receivedImage_openSettings,
|
|
onPressed: () => Navigator.of(context).push(
|
|
MaterialPageRoute<void>(
|
|
builder: (_) =>
|
|
const AppSettingsScreen(focusImageMessages: true),
|
|
),
|
|
),
|
|
)
|
|
: null,
|
|
);
|
|
}
|
|
|
|
Future<void> _sendImageViaIpfs() {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
return attachIpfsLinkToDraft(
|
|
context: context,
|
|
controller: _textController,
|
|
focusNode: _textFieldFocusNode,
|
|
maxBytes: maxChannelMessageBytes(connector.selfName),
|
|
encodeOutbound: (text) {
|
|
final replyTo = _replyingToMessage;
|
|
return connector.prepareChannelOutboundText(
|
|
widget.channel.index,
|
|
replyTo == null ? text : '${_replyPrefix(replyTo)}$text',
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
/// Takes no [BuildContext]: it uses the [State]'s own, so the `mounted`
|
|
/// checks around each `await` are the ones that actually govern it.
|
|
Future<void> _showImageSendPreview() async {
|
|
final codec = _imageCodec;
|
|
if (codec == null) return;
|
|
if (codec.availability != ImageCodecAvailability.ready) {
|
|
_explainImageCodecNotReady(codec);
|
|
return;
|
|
}
|
|
final connector = context.read<MeshCoreConnector>();
|
|
|
|
// The picked bytes are kept past the preview on purpose: the sender's own
|
|
// bubble renders from them (see [_registerOutgoingImage]). The bitstream
|
|
// cannot serve — turning it back into pixels is a ~2.16 GiB, ~1 s decode
|
|
// of an image the sender is already holding.
|
|
final XFile? picked;
|
|
try {
|
|
picked = await ImagePicker().pickImage(
|
|
source: ImageSource.gallery,
|
|
// The codec centre-crops to 512x512 anyway, so there is nothing to
|
|
// gain from decoding a 12 MP original — but stay well above 512 so the
|
|
// crop still has detail to work with.
|
|
maxWidth: 2048,
|
|
maxHeight: 2048,
|
|
);
|
|
} on Exception catch (e) {
|
|
debugPrint('image pick failed: $e');
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.chat_imagePickFailed),
|
|
);
|
|
return;
|
|
}
|
|
if (picked == null) return; // cancelled at the picker
|
|
|
|
final Uint8List sourceBytes;
|
|
final int originalFileBytes;
|
|
try {
|
|
sourceBytes = await picked.readAsBytes();
|
|
// XFile.length() is the on-disk size — what the sheet shows against the
|
|
// transmitted size — and unlike dart:io it also works on web.
|
|
originalFileBytes = await picked.length();
|
|
} on Exception catch (e) {
|
|
debugPrint('image read failed: $e');
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.chat_imagePickFailed),
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (!mounted) return;
|
|
final result = await showImageSendPreviewSheet(
|
|
context: context,
|
|
imageBytes: sourceBytes,
|
|
originalFileBytes: originalFileBytes,
|
|
codec: codec,
|
|
);
|
|
if (result == null) return; // cancelled at the preview
|
|
if (!mounted) return;
|
|
await _sendImage(connector, result, sourceBytes: sourceBytes);
|
|
}
|
|
|
|
/// Chunks [result] and puts it on the channel as GRP_DATA packets.
|
|
///
|
|
/// Chunk geometry, CRC and parity all come from [buildImageChunks] \u2014 the
|
|
/// single source of truth for the wire format \u2014 and the blobs go out through
|
|
/// [MeshCoreConnector.sendImageChunks] as one list, so the connector owns the
|
|
/// inter-chunk pacing and the whole image sits inside one scoped send.
|
|
///
|
|
/// [sourceBytes] is the original picked file. It is only ever used to draw
|
|
/// the sender's own bubble; nothing about the transmission depends on it.
|
|
Future<void> _sendImage(
|
|
MeshCoreConnector connector,
|
|
ImageSendPreviewResult result, {
|
|
required Uint8List sourceBytes,
|
|
}) async {
|
|
final l10n = context.l10n;
|
|
|
|
// The image preview may still be open when the link drops.
|
|
if (!ensureRadioConnected(context)) return;
|
|
if (!connector.supportsChannelData) {
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(l10n.imageSend_deviceUnsupported),
|
|
);
|
|
return;
|
|
}
|
|
final senderPrefix = connector.imageSenderPrefix;
|
|
if (senderPrefix == null) {
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(l10n.imageSend_deviceUnsupported),
|
|
);
|
|
return;
|
|
}
|
|
|
|
final ImageChunkSet chunkSet;
|
|
try {
|
|
chunkSet = buildImageChunks(
|
|
payload: result.payload,
|
|
metadata: ImageStreamMetadata(
|
|
rate: result.rate,
|
|
squareSize: kImageCodecSquareSize,
|
|
// The codec stretched the whole frame into a square, which the
|
|
// receiver cannot undo from pixels alone. Naming the source shape
|
|
// here costs no extra bytes -- it rides in spare bits of the metadata
|
|
// byte -- and lets the receiver letterbox back.
|
|
aspectCode: await _aspectCodeOf(sourceBytes),
|
|
),
|
|
senderPrefix: senderPrefix,
|
|
imgId: _imageIds.next(),
|
|
parity: result.includeParity,
|
|
);
|
|
} on ArgumentError {
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(context, content: Text(l10n.imageSend_tooLarge));
|
|
return;
|
|
}
|
|
if (!mounted) return;
|
|
|
|
// Pace on the measured per-packet airtime when the radio parameters are
|
|
// known; fall back to the base gap when they are not, rather than
|
|
// hammering the channel back-to-back.
|
|
final total = result.airtime;
|
|
final perPacket = total == null
|
|
? Duration.zero
|
|
: Duration(
|
|
microseconds:
|
|
total.inMicroseconds ~/
|
|
(result.packetCount == 0 ? 1 : result.packetCount),
|
|
);
|
|
|
|
setState(() {
|
|
_imageSendTotal = chunkSet.blobs.length;
|
|
_imageSendSent = 0;
|
|
});
|
|
try {
|
|
final sent = await connector.sendImageChunks(
|
|
chunkSet.blobs,
|
|
channelIndex: widget.channel.index,
|
|
interChunkDelay: imageSendChunkGap(perPacket),
|
|
onProgress: (sentChunks, totalChunks) {
|
|
if (!mounted) return;
|
|
setState(() => _imageSendSent = sentChunks);
|
|
},
|
|
);
|
|
// Register before the snack bar, so the bubble is on screen by the time
|
|
// the confirmation appears rather than a frame behind it.
|
|
if (sent) {
|
|
await _registerOutgoingImage(
|
|
result: result,
|
|
chunkSet: chunkSet,
|
|
senderPrefix: senderPrefix,
|
|
sourceBytes: sourceBytes,
|
|
);
|
|
}
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(
|
|
sent
|
|
? l10n.imageSend_sentConfirmation(chunkSet.blobs.length)
|
|
: l10n.imageSend_deviceUnsupported,
|
|
),
|
|
);
|
|
} on Exception catch (error) {
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(l10n.imageSend_sendFailed('$error')),
|
|
);
|
|
} finally {
|
|
if (mounted) {
|
|
setState(() {
|
|
_imageSendTotal = 0;
|
|
_imageSendSent = 0;
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Puts the image the user just sent into [ReceivedImageStore] so it appears
|
|
/// in their own transcript.
|
|
///
|
|
/// GRP_DATA is not echoed back to the sender and an image is not a
|
|
/// [ChannelMessage], so without this the sender sees a "sent" snack bar and
|
|
/// an otherwise empty conversation. The entry lands in `decoded` directly —
|
|
/// an outgoing image is never queued for inference, so showing your own
|
|
/// photo costs no model memory.
|
|
///
|
|
/// Best effort throughout: a failure here has already been preceded by a
|
|
/// successful transmission, so it must not turn into an error the user sees.
|
|
Future<void> _registerOutgoingImage({
|
|
required ImageSendPreviewResult result,
|
|
required ImageChunkSet chunkSet,
|
|
required int senderPrefix,
|
|
required Uint8List sourceBytes,
|
|
}) async {
|
|
final ReceivedImageStore store;
|
|
try {
|
|
store = context.read<ReceivedImageStore>();
|
|
} on ProviderNotFoundException {
|
|
return; // screen test without the store
|
|
}
|
|
final previewPng = await _squarePreviewPng(sourceBytes);
|
|
if (previewPng == null) return;
|
|
try {
|
|
await store.registerOutgoing(
|
|
channelIndex: widget.channel.index,
|
|
channelId: widget.channel.storageId,
|
|
// The same 16 bits the chunk header carries, so the entry keys the
|
|
// same way an inbound one would.
|
|
senderPrefix: senderPrefix,
|
|
imgId: chunkSet.imgId,
|
|
previewPng: previewPng,
|
|
rate: aeicRatePointForUi(result.rate),
|
|
chunkCount: chunkSet.dataChunkCount,
|
|
aspectCode: await _aspectCodeOf(sourceBytes),
|
|
);
|
|
} on Exception catch (error) {
|
|
debugPrint('outgoing image registration failed: $error');
|
|
}
|
|
}
|
|
|
|
/// The [kImageAspectCodes] entry matching [imageBytes]'s shape.
|
|
///
|
|
/// Decodes only to read the dimensions. Falls back to "unknown" (rendered
|
|
/// square) rather than guessing, because asserting the wrong shape would
|
|
/// letterbox the receiver's copy incorrectly and look like a codec bug.
|
|
static Future<int> _aspectCodeOf(Uint8List imageBytes) async {
|
|
ui.Image? image;
|
|
try {
|
|
final codec = await ui.instantiateImageCodec(imageBytes);
|
|
image = (await codec.getNextFrame()).image;
|
|
return imageAspectCodeFor(image.width, image.height);
|
|
} on Exception catch (error) {
|
|
debugPrint('aspect probe failed: $error');
|
|
return kImageAspectUnknown;
|
|
} finally {
|
|
image?.dispose();
|
|
}
|
|
}
|
|
|
|
/// [imageBytes] stretched to 512x512, as PNG.
|
|
///
|
|
/// This is what the preview sheet showed (`BoxFit.fill` on a 1:1 box is
|
|
/// exactly the stretch the codec applies) and what the codec actually
|
|
/// encoded, so the sender's bubble matches both. Deliberately not a decode of the
|
|
/// bitstream: that would cost ~2.16 GiB and ~1 s to reproduce, less well, an
|
|
/// image this device is already holding in memory.
|
|
///
|
|
/// Returns null rather than throwing on an undecodable source — the send has
|
|
/// already happened by the time this runs.
|
|
static Future<Uint8List?> _squarePreviewPng(Uint8List imageBytes) async {
|
|
ui.Image? source;
|
|
ui.Image? square;
|
|
try {
|
|
final codec = await ui.instantiateImageCodec(imageBytes);
|
|
source = (await codec.getNextFrame()).image;
|
|
final dst = kImageCodecSquareSize.toDouble();
|
|
final recorder = ui.PictureRecorder();
|
|
ui.Canvas(recorder).drawImageRect(
|
|
source,
|
|
// Whole frame, matching _toSquareRgb in image_codec_service.dart. If
|
|
// one of these two is a crop and the other a stretch, the sender's
|
|
// bubble silently stops matching what the receiver sees.
|
|
ui.Rect.fromLTWH(
|
|
0,
|
|
0,
|
|
source.width.toDouble(),
|
|
source.height.toDouble(),
|
|
),
|
|
ui.Rect.fromLTWH(0, 0, dst, dst),
|
|
ui.Paint()..filterQuality = ui.FilterQuality.medium,
|
|
);
|
|
square = await recorder.endRecording().toImage(
|
|
kImageCodecSquareSize,
|
|
kImageCodecSquareSize,
|
|
);
|
|
final data = await square.toByteData(format: ui.ImageByteFormat.png);
|
|
return data?.buffer.asUint8List();
|
|
} on Exception catch (error) {
|
|
debugPrint('outgoing image preview render failed: $error');
|
|
return null;
|
|
} finally {
|
|
source?.dispose();
|
|
square?.dispose();
|
|
}
|
|
}
|
|
|
|
/// The merged, ordered transcript (messages + AEIC images), memoised.
|
|
///
|
|
/// Sorting the whole transcript and rebuilding the key bookkeeping on every
|
|
/// connector notification is wasted work when this channel did not change
|
|
/// (most notifications are about other chats, contacts or radio state), so
|
|
/// the layout is only recomputed when the message list's identity, length or
|
|
/// ends change, or the image store notified.
|
|
///
|
|
/// Returns no images when [ReceivedImageStore] is not registered, so a screen
|
|
/// test without the provider still renders. [context] must be the context
|
|
/// of the element currently building (the `Consumer` builder's, not the
|
|
/// `State`'s) — `watch` asserts on that.
|
|
_TranscriptLayout _transcriptLayoutFor(
|
|
BuildContext context,
|
|
List<ChannelMessage> messages,
|
|
) {
|
|
ReceivedImageStore? store;
|
|
try {
|
|
store = context.watch<ReceivedImageStore>();
|
|
} on ProviderNotFoundException {
|
|
store = null;
|
|
}
|
|
if (!identical(store, _watchedImageStore)) {
|
|
_watchedImageStore?.removeListener(_onImageStoreChanged);
|
|
_watchedImageStore = store;
|
|
store?.addListener(_onImageStoreChanged);
|
|
_imageStoreVersion++;
|
|
}
|
|
MessageFilterService? filter;
|
|
try {
|
|
filter = context.watch<MessageFilterService>();
|
|
} on ProviderNotFoundException {
|
|
filter = null;
|
|
}
|
|
final displayMode =
|
|
filter?.settings.displayMode ?? FilterDisplayMode.placeholder;
|
|
final filterActive =
|
|
filter?.isChannelFiltered(_messageFilterChannelId) ?? true;
|
|
// Spam / Not spam replace a message in place (same list, length and
|
|
// ends), so the memo also keys on which messages are filtered.
|
|
final filterVersion = Object.hash(
|
|
displayMode,
|
|
filterActive,
|
|
_revealVersion,
|
|
_filteredMessagesSignature(messages),
|
|
);
|
|
final cached = _transcriptLayout;
|
|
if (cached != null &&
|
|
cached.matches(
|
|
messages,
|
|
_imageStoreVersion,
|
|
widget.channel.index,
|
|
filterVersion,
|
|
)) {
|
|
return cached;
|
|
}
|
|
final images = store == null
|
|
? const <ReceivedImageEntry>[]
|
|
: store.entriesForChannel(widget.channel.storageId);
|
|
final layout = _TranscriptLayout.build(
|
|
messages: messages,
|
|
images: images,
|
|
imageVersion: _imageStoreVersion,
|
|
channelIndex: widget.channel.index,
|
|
filterVersion: filterVersion,
|
|
displayMode: displayMode,
|
|
filterActive: filterActive,
|
|
revealedIds: _revealedFilteredIds,
|
|
);
|
|
// Prune stale keys (deleted/cleared messages) to avoid unbounded growth.
|
|
final liveIds = layout.ids.toSet();
|
|
_messageKeys.removeWhere((id, _) => !liveIds.contains(id));
|
|
_transcriptLayout = layout;
|
|
return layout;
|
|
}
|
|
|
|
void _onImageStoreChanged() => _imageStoreVersion++;
|
|
|
|
List<ChannelMessage>? _indexSource;
|
|
int _indexSourceLength = -1;
|
|
Map<String, int> _indexById = const {};
|
|
|
|
/// The newest message with [id] in [messages], via an id -> index map
|
|
/// rebuilt only when the list is replaced, changes length, or an entry
|
|
/// moved. Reply previews call this per bubble on every rebuild; a linear
|
|
/// scan each time made a busy transcript O(n^2).
|
|
ChannelMessage? _channelMessageById(
|
|
List<ChannelMessage> messages,
|
|
String id,
|
|
) {
|
|
if (!identical(messages, _indexSource) ||
|
|
messages.length != _indexSourceLength) {
|
|
_rebuildIndex(messages);
|
|
}
|
|
var index = _indexById[id];
|
|
if (index != null &&
|
|
(index >= messages.length || messages[index].messageId != id)) {
|
|
_rebuildIndex(messages);
|
|
index = _indexById[id];
|
|
}
|
|
return index == null ? null : messages[index];
|
|
}
|
|
|
|
void _rebuildIndex(List<ChannelMessage> messages) {
|
|
final byId = <String, int>{};
|
|
// Later entries win, matching the previous `lastOrNull` lookup.
|
|
for (var i = 0; i < messages.length; i++) {
|
|
byId[messages[i].messageId] = i;
|
|
}
|
|
_indexById = byId;
|
|
_indexSource = messages;
|
|
_indexSourceLength = messages.length;
|
|
}
|
|
|
|
/// Cheap fingerprint of which messages are filtered, so the layout memo
|
|
/// notices a message being marked spam or not spam in place.
|
|
static int _filteredMessagesSignature(List<ChannelMessage> messages) {
|
|
var hash = 0;
|
|
var count = 0;
|
|
for (final m in messages) {
|
|
if (!m.isFiltered) continue;
|
|
count++;
|
|
hash = Object.hash(hash, m.messageId);
|
|
}
|
|
return Object.hash(count, hash);
|
|
}
|
|
|
|
/// Bubble for one AEIC image, following the GIF-message precedent: minimal
|
|
/// chrome, the renderer owns every state (receiving / decoding / failed) and
|
|
/// the mandatory AI-reconstruction label.
|
|
Widget _buildImageBubble(ReceivedImageEntry entry, double textScale) {
|
|
final scheme = Theme.of(context).colorScheme;
|
|
final isOutgoing = entry.isOutgoing;
|
|
final bubbleTheme = MeshBubbleTheme.of(context);
|
|
final textColor = isOutgoing ? bubbleTheme.meInk : scheme.onSurface;
|
|
final metaColor = textColor.withValues(alpha: 0.65);
|
|
|
|
final bubble = Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 3),
|
|
child: Row(
|
|
mainAxisAlignment: isOutgoing
|
|
? MainAxisAlignment.end
|
|
: MainAxisAlignment.start,
|
|
crossAxisAlignment: CrossAxisAlignment.end,
|
|
children: [
|
|
if (!isOutgoing) ...[
|
|
_buildAvatar(_imageSenderLabel(entry), textScale),
|
|
const SizedBox(width: 6),
|
|
],
|
|
Flexible(
|
|
child: Container(
|
|
padding: const EdgeInsets.all(4),
|
|
decoration: BoxDecoration(
|
|
color: isOutgoing ? bubbleTheme.me : scheme.surfaceContainerLow,
|
|
borderRadius: BorderRadius.circular(MeshRadii.lg),
|
|
border: Border.all(
|
|
color: isOutgoing
|
|
? bubbleTheme.meBorder
|
|
: scheme.outlineVariant,
|
|
width: 1,
|
|
),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
if (!isOutgoing)
|
|
Padding(
|
|
padding: const EdgeInsets.only(
|
|
left: 8,
|
|
top: 4,
|
|
bottom: 4,
|
|
),
|
|
child: Text(
|
|
_imageSenderLabel(entry),
|
|
style: TextStyle(
|
|
fontSize: 13 * textScale,
|
|
fontWeight: FontWeight.w700,
|
|
color: textColor,
|
|
),
|
|
),
|
|
),
|
|
ReceivedImageMessage(
|
|
streamId: entry.streamId,
|
|
isOutgoing: isOutgoing,
|
|
fallbackTextColor: textColor,
|
|
// The placeholder's "no model installed" tap lands here.
|
|
// `focusImageMessages` scrolls straight to the image block
|
|
// — it sits below six other sections, so the plain screen
|
|
// would open at the top with no sign of what was tapped for.
|
|
onOpenCodecSettings: () => Navigator.of(context).push(
|
|
MaterialPageRoute<void>(
|
|
builder: (_) =>
|
|
const AppSettingsScreen(focusImageMessages: true),
|
|
),
|
|
),
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.only(
|
|
left: 8,
|
|
right: 8,
|
|
bottom: 4,
|
|
),
|
|
child: Text(
|
|
formatChatTime(context, entry.firstSeen),
|
|
style: MeshTheme.mono(
|
|
fontSize: 12 * textScale,
|
|
color: metaColor,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
return GestureDetector(
|
|
onLongPress: () => _showImageActions(entry),
|
|
onSecondaryTap: () => _showImageActions(entry),
|
|
child: bubble,
|
|
);
|
|
}
|
|
|
|
void _showImageActions(ReceivedImageEntry entry) {
|
|
final l10n = context.l10n;
|
|
final readOnly = isRadioReadOnly(context.read<MeshCoreConnector>());
|
|
final canSave = entry.state == ReceivedImageState.decoded;
|
|
showMeshSheet(
|
|
context,
|
|
builder: (sheetContext) => SafeArea(
|
|
child: SingleChildScrollView(
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
BottomSheetHeader(
|
|
title: l10n.receivedImage_awaiting(
|
|
entry.bitstreamByteCount,
|
|
entry.totalChunks,
|
|
),
|
|
subtitle: _imageSenderLabel(entry),
|
|
),
|
|
if (canSave)
|
|
ListTile(
|
|
leading: const Icon(Icons.save_alt),
|
|
title: Text(l10n.receivedImage_save),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_saveImage(entry);
|
|
},
|
|
),
|
|
ListTile(
|
|
leading: const Icon(Icons.info_outline),
|
|
title: Text(l10n.receivedImage_packetInfo),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_showImagePacketInfo(entry);
|
|
},
|
|
),
|
|
const Divider(height: 1),
|
|
ListTile(
|
|
enabled: !readOnly,
|
|
leading: Icon(
|
|
Icons.delete_outline,
|
|
color: readOnly ? null : Theme.of(context).colorScheme.error,
|
|
),
|
|
title: Text(
|
|
l10n.common_delete,
|
|
style: TextStyle(
|
|
color: readOnly
|
|
? null
|
|
: Theme.of(context).colorScheme.error,
|
|
),
|
|
),
|
|
onTap: () async {
|
|
Navigator.pop(sheetContext);
|
|
await context.read<ReceivedImageStore>().deleteImage(
|
|
entry.streamId,
|
|
);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(l10n.chat_messageDeleted),
|
|
);
|
|
},
|
|
),
|
|
const SizedBox(height: 8),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> _saveImage(ReceivedImageEntry entry) async {
|
|
final l10n = context.l10n;
|
|
final shareOrigin = shareOriginOf(context);
|
|
final png = await context.read<ReceivedImageStore>().ensurePng(
|
|
entry.streamId,
|
|
);
|
|
if (!mounted) return;
|
|
final shareText = l10n.receivedImage_shareCaption(entry.bitstreamByteCount);
|
|
if (png == null ||
|
|
!await saveImagePng(
|
|
png,
|
|
entry,
|
|
shareText: shareText,
|
|
sharePositionOrigin: shareOrigin,
|
|
)) {
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(l10n.receivedImage_saveFailed),
|
|
);
|
|
}
|
|
}
|
|
|
|
void _showImagePacketInfo(ReceivedImageEntry entry) {
|
|
final l10n = context.l10n;
|
|
final decodeMs = entry.decodeMs;
|
|
showDialog<void>(
|
|
context: context,
|
|
builder: (dialogContext) => AlertDialog(
|
|
scrollable: true,
|
|
title: Text(l10n.receivedImage_packetInfo),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(_imageSenderLabel(entry)),
|
|
Text(formatChatTime(context, entry.firstSeen)),
|
|
Text(
|
|
l10n.receivedImage_awaiting(
|
|
entry.bitstreamByteCount,
|
|
entry.totalChunks,
|
|
),
|
|
),
|
|
if (entry.recoveredWithParity)
|
|
Text(l10n.receivedImage_parityRecovered),
|
|
if (decodeMs != null) Text(l10n.receivedImage_decodeTime(decodeMs)),
|
|
],
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(dialogContext),
|
|
child: Text(l10n.common_close),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
/// GRP_DATA carries no sender name — only the 2-byte public-key prefix the
|
|
/// chunk header stamps — so resolve that against the contact list and fall
|
|
/// back to the raw prefix only when nobody matches.
|
|
///
|
|
/// Two bytes is 65,536 values, so a collision between two known contacts is
|
|
/// possible. When it happens the sender is genuinely ambiguous and naming
|
|
/// either one would be a guess, so the prefix is shown instead.
|
|
String _imageSenderLabel(ReceivedImageEntry entry) {
|
|
final hex = entry.senderPrefix.toRadixString(16).padLeft(4, '0');
|
|
final connector = context.read<MeshCoreConnector>();
|
|
if (entry.isOutgoing) {
|
|
return connector.selfName ?? context.l10n.receivedImage_senderPrefix(hex);
|
|
}
|
|
final matches = connector.contacts
|
|
.where((c) => c.publicKeyHex.toLowerCase().startsWith(hex))
|
|
.toList();
|
|
if (matches.length == 1) return matches.single.name;
|
|
return context.l10n.receivedImage_senderPrefix(hex);
|
|
}
|
|
|
|
Widget _buildAvatar(String senderName, double textScale) {
|
|
return AvatarCircle(
|
|
name: senderName,
|
|
size: (32 * textScale).clamp(28.0, 56.0),
|
|
);
|
|
}
|
|
|
|
Widget _buildReplyBanner(double textScale) {
|
|
final message = _replyingToMessage!;
|
|
final scheme = Theme.of(context).colorScheme;
|
|
final replyRegion = message.region;
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
|
decoration: BoxDecoration(
|
|
color: scheme.surfaceContainerHigh,
|
|
border: Border(
|
|
bottom: BorderSide(color: scheme.outlineVariant, width: 1),
|
|
),
|
|
),
|
|
child: Row(
|
|
children: [
|
|
Icon(Icons.reply, size: 18, color: scheme.primary),
|
|
const SizedBox(width: 8),
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
context.l10n.chat_replyingTo(message.senderName),
|
|
style: MeshTheme.mono(
|
|
fontSize: 12 * textScale,
|
|
fontWeight: FontWeight.w700,
|
|
color: scheme.primary,
|
|
),
|
|
),
|
|
_buildReplyContent(
|
|
message.text,
|
|
textScale,
|
|
color: scheme.onSurfaceVariant,
|
|
maxLines: 1,
|
|
gifSize: 48,
|
|
),
|
|
],
|
|
),
|
|
),
|
|
if (replyRegion?.isNotEmpty ?? false)
|
|
InkWell(
|
|
borderRadius: BorderRadius.circular(MeshRadii.xs),
|
|
onTap: () => setState(() => _useReplyRegion = !_useReplyRegion),
|
|
child: Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
|
|
decoration: BoxDecoration(
|
|
color: _useReplyRegion
|
|
? scheme.primaryContainer
|
|
: scheme.surfaceContainerHighest,
|
|
borderRadius: BorderRadius.circular(MeshRadii.xs),
|
|
border: Border.all(
|
|
color: _useReplyRegion
|
|
? scheme.primary
|
|
: scheme.outlineVariant,
|
|
),
|
|
),
|
|
child: Text(
|
|
context.l10n.channels_regionSetTo(replyRegion!),
|
|
style:
|
|
MeshTheme.mono(
|
|
fontSize: 12 * textScale,
|
|
color: _useReplyRegion
|
|
? scheme.onPrimaryContainer
|
|
: scheme.onSurfaceVariant,
|
|
).copyWith(
|
|
decoration: _useReplyRegion
|
|
? null
|
|
: TextDecoration.lineThrough,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(width: 4),
|
|
IconButton(
|
|
icon: const Icon(Icons.close, size: 18),
|
|
tooltip: context.l10n.chat_cancelReply,
|
|
onPressed: _cancelReply,
|
|
color: scheme.onSurfaceVariant,
|
|
constraints: const BoxConstraints(minWidth: 44, minHeight: 44),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
/// "Sending image — packet 2 of 3", above the composer.
|
|
///
|
|
/// A per-chunk figure rather than a spinner because an image occupies the
|
|
/// channel for seconds and the user needs to see it advancing.
|
|
Widget _buildImageSendProgress(ColorScheme scheme) {
|
|
final total = _imageSendTotal;
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
|
decoration: BoxDecoration(
|
|
color: scheme.surfaceContainerHigh,
|
|
border: Border(
|
|
bottom: BorderSide(color: scheme.outlineVariant, width: 1),
|
|
),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
context.l10n.imageSend_sendingProgress(_imageSendSent, total),
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
const SizedBox(height: 6),
|
|
LinearProgressIndicator(
|
|
value: total == 0 ? null : _imageSendSent / total,
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
/// The `@[name] ` prefix a reply prepends to the outgoing text.
|
|
static String _replyPrefix(ChannelMessage replyTo) =>
|
|
'@[${replyTo.senderName}] ';
|
|
|
|
Widget _buildInputBar() {
|
|
// Only the fields the composer depends on, so unrelated connector
|
|
// notifications (adverts, other chats, radio stats) don't rebuild it.
|
|
final (selfName, useEncoder) = context
|
|
.select<MeshCoreConnector, (String?, bool)>(
|
|
(c) => (
|
|
c.selfName,
|
|
c.isChannelSmazEnabled(widget.channel.index) ||
|
|
c.isChannelCyr2LatEnabled(widget.channel.index),
|
|
),
|
|
);
|
|
final showImageAction = context.select<AppSettingsService, bool>(
|
|
(s) => s.settings.imageMessagesEnabled,
|
|
);
|
|
final showIpfsAction = context.select<AppSettingsService, bool>(
|
|
(s) => s.settings.uploadIpfsEndpoint.trim().isNotEmpty,
|
|
);
|
|
final replyTo = _replyingToMessage;
|
|
final replyPrefixBytes = replyTo == null
|
|
? 0
|
|
: utf8.encode(_replyPrefix(replyTo)).length;
|
|
final maxBytes = math.max(
|
|
0,
|
|
maxChannelMessageBytes(selfName) - replyPrefixBytes,
|
|
);
|
|
final scheme = Theme.of(context).colorScheme;
|
|
return ChatComposer(
|
|
controller: _textController,
|
|
focusNode: _textFieldFocusNode,
|
|
maxBytes: maxBytes,
|
|
encoder: useEncoder
|
|
? (text) => context
|
|
.read<MeshCoreConnector>()
|
|
.prepareChannelOutboundText(widget.channel.index, text)
|
|
: null,
|
|
onSend: _sendMessage,
|
|
sendTooltip: context.l10n.chat_sendMessage,
|
|
header: [
|
|
if (replyTo != null)
|
|
Builder(
|
|
builder: (context) {
|
|
final textScale = context.select<ChatTextScaleService, double>(
|
|
(service) => service.scale,
|
|
);
|
|
return _buildReplyBanner(textScale);
|
|
},
|
|
),
|
|
if (_imageSendTotal > 0) _buildImageSendProgress(scheme),
|
|
],
|
|
actionsBuilder: () {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
return [
|
|
ChatComposerAction(
|
|
id: 'gif',
|
|
icon: Icons.gif_box,
|
|
label: context.l10n.chat_sendGif,
|
|
),
|
|
if (showIpfsAction)
|
|
ChatComposerAction(
|
|
id: 'ipfs-image',
|
|
icon: Icons.cloud_upload_outlined,
|
|
label: context.l10n.chat_sendImageIpfs,
|
|
),
|
|
if (showImageAction)
|
|
ChatComposerAction(
|
|
id: 'meshcore-image',
|
|
icon: Icons.image_outlined,
|
|
label: context.l10n.chat_sendImageLora,
|
|
),
|
|
if (hasShareableLocation(
|
|
connector.selfLatitude,
|
|
connector.selfLongitude,
|
|
))
|
|
ChatComposerAction(
|
|
id: 'send-my-location',
|
|
icon: Icons.my_location,
|
|
label: context.l10n.chat_shareMyLocation,
|
|
),
|
|
ChatComposerAction(
|
|
id: 'share-contact',
|
|
icon: Icons.person_add_alt,
|
|
label: context.l10n.contactShare_shareAction,
|
|
),
|
|
];
|
|
},
|
|
onAction: (action) {
|
|
if (!mounted) return;
|
|
switch (action) {
|
|
case 'gif':
|
|
showChatGifPicker(context, _textController);
|
|
case 'ipfs-image':
|
|
_sendImageViaIpfs();
|
|
case 'meshcore-image':
|
|
_showImageSendPreview();
|
|
case 'send-my-location':
|
|
_shareMyLocation(context.read<MeshCoreConnector>());
|
|
case 'share-contact':
|
|
showShareContactSheet(
|
|
context,
|
|
_textController,
|
|
focusNode: _textFieldFocusNode,
|
|
);
|
|
}
|
|
},
|
|
);
|
|
}
|
|
|
|
/// Shares the radio's own position as a map marker on this channel. It is
|
|
/// not a reply, so any reply in progress stays open for the next message;
|
|
/// it shares the text send guard and cooldown.
|
|
Future<void> _shareMyLocation(MeshCoreConnector connector) async {
|
|
if (!ensureRadioConnected(context)) return;
|
|
return shareMyLocationMarker(
|
|
context: context,
|
|
connector: connector,
|
|
guard: _sendGuard,
|
|
logTag: 'ChannelChat',
|
|
send: (markerText) =>
|
|
connector.sendChannelMessage(widget.channel, markerText),
|
|
);
|
|
}
|
|
|
|
Future<void> _sendMessage() {
|
|
return _sendGuard.runExclusive(_sendMessageInner);
|
|
}
|
|
|
|
Future<void> _sendMessageInner() async {
|
|
final text = _textController.text.trim();
|
|
if (text.isEmpty) return;
|
|
// Capture the reply target now; the user may change it while the
|
|
// outgoing translation runs.
|
|
final replyTo = _replyingToMessage;
|
|
final replyRegion = _useReplyRegion ? replyTo?.region : null;
|
|
|
|
// Before anything clears the text box: offline the draft must stay.
|
|
if (!ensureRadioConnected(context)) return;
|
|
if (!_sendGuard.checkCooldown(context)) return;
|
|
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final translation = await translateOutgoingText(context, text);
|
|
if (translation == null || !mounted) return;
|
|
// The link can drop while the translation runs.
|
|
if (!ensureRadioConnected(context)) return;
|
|
|
|
String messageText = translation.text;
|
|
if (replyTo != null) {
|
|
messageText = '${_replyPrefix(replyTo)}$messageText';
|
|
}
|
|
|
|
final maxBytes = maxChannelMessageBytes(connector.selfName);
|
|
final outboundText = connector.prepareChannelOutboundText(
|
|
widget.channel.index,
|
|
messageText,
|
|
);
|
|
if (utf8.encode(outboundText).length > maxBytes) {
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.chat_messageTooLong(maxBytes)),
|
|
);
|
|
return;
|
|
}
|
|
|
|
// When messageText is transformed with cyr2lat, it (generally) hasn't visual differences,
|
|
// but we getting messages doubles in chat screen (source text and transformed).
|
|
// To prevent, we'll perform transform of source before pass to main sender logic.
|
|
// We can pass whole text, senderName will be kept intact
|
|
if (connector.isChannelCyr2LatEnabled(widget.channel.index)) {
|
|
messageText = Cyr2Lat.encode(messageText);
|
|
}
|
|
// end transform
|
|
|
|
// Keep anything the user typed or a new reply picked during translation.
|
|
if (_textController.text.trim() == text) {
|
|
_textController.clear();
|
|
}
|
|
if (identical(_replyingToMessage, replyTo)) {
|
|
_cancelReply();
|
|
}
|
|
_textFieldFocusNode.requestFocus();
|
|
connector.sendChannelMessage(
|
|
widget.channel,
|
|
messageText,
|
|
originalText: translation.originalText,
|
|
translatedLanguageCode: translation.languageCode,
|
|
translationModelId: translation.modelId,
|
|
region: replyRegion,
|
|
replyTo: replyTo,
|
|
);
|
|
// Only a dispatched send starts the cooldown.
|
|
_sendGuard.markDispatched();
|
|
}
|
|
|
|
void _showMessagePathInfo(ChannelMessage message) {
|
|
Navigator.push(
|
|
context,
|
|
MaterialPageRoute(
|
|
builder: (context) =>
|
|
ChannelMessagePathScreen(message: message, channelMessage: true),
|
|
),
|
|
);
|
|
}
|
|
|
|
void _showMessageActions(ChannelMessage message) {
|
|
final readOnly = isRadioReadOnly(context.read<MeshCoreConnector>());
|
|
final translationService = context.read<TranslationService>();
|
|
final canTranslateMessage =
|
|
translationService.canTranslateIncoming(
|
|
text: message.text,
|
|
isCli: false,
|
|
isOutgoing: message.isOutgoing,
|
|
) &&
|
|
(message.translatedText?.trim().isEmpty ?? true);
|
|
// Filter actions apply to incoming messages in a channel the filter
|
|
// covers; structured payloads (GIFs, markers) are never filtered.
|
|
final filter = _messageFilter;
|
|
final showFilterActions =
|
|
!message.isOutgoing &&
|
|
filter != null &&
|
|
filter.isChannelFiltered(_messageFilterChannelId) &&
|
|
(message.isFiltered ||
|
|
!MessageFilterText.isStructuredPayload(message.text));
|
|
|
|
showMeshSheet(
|
|
context,
|
|
builder: (sheetContext) => SafeArea(
|
|
child: SingleChildScrollView(
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
BottomSheetHeader(
|
|
title: message.text.characters.length > 40
|
|
? '${message.text.characters.take(40)}…'
|
|
: message.text,
|
|
subtitle: message.senderName.isNotEmpty
|
|
? message.senderName
|
|
: null,
|
|
),
|
|
ListTile(
|
|
enabled: !readOnly,
|
|
leading: const Icon(Icons.reply),
|
|
title: Text(context.l10n.chat_reply),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_setReplyingTo(message);
|
|
},
|
|
),
|
|
ListTile(
|
|
leading: const Icon(Icons.checklist),
|
|
title: Text(context.l10n.chat_selectMessages),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_toggleSelected(message);
|
|
},
|
|
),
|
|
ListTile(
|
|
leading: const Icon(Icons.route),
|
|
title: Text(context.l10n.chat_path),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_showMessagePathInfo(message);
|
|
},
|
|
),
|
|
if (message.pathBytes.isNotEmpty)
|
|
ListTile(
|
|
leading: const Icon(Icons.map_outlined),
|
|
title: Text(context.l10n.chat_viewPathOnMap),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
Navigator.push(
|
|
context,
|
|
MaterialPageRoute(
|
|
builder: (context) => ChannelMessagePathMapScreen(
|
|
message: message,
|
|
channelMessage: true,
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
// Can't react to your own messages
|
|
if (!message.isOutgoing)
|
|
ListTile(
|
|
enabled: !readOnly,
|
|
leading: const Icon(Icons.add_reaction_outlined),
|
|
title: Text(context.l10n.chat_addReaction),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_showEmojiPicker(message);
|
|
},
|
|
),
|
|
ListTile(
|
|
leading: const Icon(Icons.copy),
|
|
title: Text(context.l10n.common_copy),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
copyChatMessageText(context, message.text);
|
|
},
|
|
),
|
|
if (canTranslateMessage)
|
|
ListTile(
|
|
leading: const Icon(Icons.translate),
|
|
title: Text(context.l10n.translation_translateMessage),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
unawaited(
|
|
context.read<MeshCoreConnector>().translateChannelMessage(
|
|
widget.channel.index,
|
|
message,
|
|
manualTranslation: true,
|
|
),
|
|
);
|
|
},
|
|
),
|
|
if (!message.isOutgoing)
|
|
ListTile(
|
|
leading: const Icon(Icons.mark_chat_unread_outlined),
|
|
title: Text(context.l10n.chat_markAsUnread),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_markAsUnread(message);
|
|
},
|
|
),
|
|
if (showFilterActions) ...[
|
|
const Divider(height: 1),
|
|
if (message.isFiltered)
|
|
ListTile(
|
|
enabled: !readOnly,
|
|
leading: const Icon(Icons.visibility_outlined),
|
|
title: Text(context.l10n.messageFilter_notSpam),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_markNotSpam(message);
|
|
},
|
|
)
|
|
else
|
|
ListTile(
|
|
enabled: !readOnly,
|
|
leading: const Icon(Icons.visibility_off_outlined),
|
|
title: Text(context.l10n.messageFilter_markSpam),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_markSpam(message);
|
|
},
|
|
),
|
|
if (message.senderName.trim().isNotEmpty)
|
|
ListTile(
|
|
leading: const Icon(Icons.person_off_outlined),
|
|
title: Text(context.l10n.messageFilter_filterSender),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_filterSender(message.senderName);
|
|
},
|
|
),
|
|
ListTile(
|
|
leading: const Icon(Icons.filter_alt_outlined),
|
|
title: Text(context.l10n.messageFilter_filterLikeThis),
|
|
onTap: () {
|
|
Navigator.pop(sheetContext);
|
|
_filterMessagesLike(message);
|
|
},
|
|
),
|
|
],
|
|
const Divider(height: 1),
|
|
ListTile(
|
|
enabled: !readOnly,
|
|
leading: Icon(
|
|
Icons.delete_outline,
|
|
color: readOnly ? null : Theme.of(context).colorScheme.error,
|
|
),
|
|
title: Text(
|
|
context.l10n.common_delete,
|
|
style: TextStyle(
|
|
color: readOnly
|
|
? null
|
|
: Theme.of(context).colorScheme.error,
|
|
),
|
|
),
|
|
onTap: () async {
|
|
Navigator.pop(sheetContext);
|
|
await _deleteMessage(message);
|
|
},
|
|
),
|
|
const SizedBox(height: 8),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
// ---- bulk selection -------------------------------------------------------
|
|
|
|
void _toggleSelected(ChannelMessage message) {
|
|
HapticFeedback.selectionClick();
|
|
setState(() {
|
|
if (!_selectedIds.remove(message.messageId)) {
|
|
_selectedIds.add(message.messageId);
|
|
}
|
|
});
|
|
}
|
|
|
|
void _clearSelection() => setState(_selectedIds.clear);
|
|
|
|
/// Selected messages still in the transcript, oldest first.
|
|
List<ChannelMessage> _selectedMessages() {
|
|
final messages = context.read<MeshCoreConnector>().getChannelMessages(
|
|
widget.channel,
|
|
);
|
|
return [
|
|
for (final m in messages)
|
|
if (_selectedIds.contains(m.messageId)) m,
|
|
];
|
|
}
|
|
|
|
/// Messages the user can currently see (filtered ones only once revealed).
|
|
List<ChannelMessage> _visibleMessages() {
|
|
final messages = context.read<MeshCoreConnector>().getChannelMessages(
|
|
widget.channel,
|
|
);
|
|
final filterActive = _transcriptLayout?.filterActive ?? true;
|
|
return [
|
|
for (final m in messages)
|
|
if (!(filterActive &&
|
|
m.isFiltered &&
|
|
!_revealedFilteredIds.contains(m.messageId)))
|
|
m,
|
|
];
|
|
}
|
|
|
|
bool _canMarkSpam(ChannelMessage m) =>
|
|
!m.isOutgoing &&
|
|
!m.isFiltered &&
|
|
!MessageFilterText.isStructuredPayload(m.text);
|
|
|
|
Widget _buildSelectableRow(ChannelMessage message, Widget messageBody) {
|
|
final scheme = Theme.of(context).colorScheme;
|
|
final selected = _selectedIds.contains(message.messageId);
|
|
return Semantics(
|
|
selected: selected,
|
|
button: true,
|
|
child: Material(
|
|
color: selected
|
|
? scheme.primary.withValues(alpha: 0.16)
|
|
: Colors.transparent,
|
|
child: InkWell(
|
|
onTap: () => _toggleSelected(message),
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 8),
|
|
child: Row(
|
|
children: [
|
|
Icon(
|
|
selected ? Icons.check_circle : Icons.radio_button_unchecked,
|
|
size: 28,
|
|
color: selected ? scheme.primary : scheme.onSurfaceVariant,
|
|
),
|
|
const SizedBox(width: 8),
|
|
// Links, reply previews and reactions inside the bubble must
|
|
// not react while picking messages.
|
|
Expanded(child: AbsorbPointer(child: messageBody)),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
PreferredSizeWidget _buildSelectionAppBar(BuildContext context) {
|
|
final l10n = context.l10n;
|
|
final selected = _selectedMessages();
|
|
final filter = _messageFilter;
|
|
// Offline the stored conversation is read-only: no delete or spam marks.
|
|
final readOnly = context.radioReadOnly;
|
|
final filterCoversChannel =
|
|
!readOnly &&
|
|
filter != null &&
|
|
filter.isChannelFiltered(_messageFilterChannelId);
|
|
final spamCandidates = filterCoversChannel
|
|
? selected.where(_canMarkSpam).toList()
|
|
: const <ChannelMessage>[];
|
|
final notSpamCandidates = filterCoversChannel
|
|
? selected.where((m) => m.isFiltered).toList()
|
|
: const <ChannelMessage>[];
|
|
return AppBar(
|
|
leading: IconButton(
|
|
tooltip: l10n.chat_clearSelection,
|
|
icon: const Icon(Icons.close),
|
|
onPressed: _clearSelection,
|
|
),
|
|
title: Text(l10n.chat_selectedCount(selected.length)),
|
|
actions: [
|
|
if (spamCandidates.isNotEmpty)
|
|
IconButton(
|
|
tooltip: l10n.messageFilter_markSpam,
|
|
icon: const Icon(Icons.visibility_off_outlined),
|
|
onPressed: () => _bulkMarkSpam(spamCandidates),
|
|
),
|
|
if (notSpamCandidates.isNotEmpty)
|
|
IconButton(
|
|
tooltip: l10n.messageFilter_notSpam,
|
|
icon: const Icon(Icons.visibility_outlined),
|
|
onPressed: () => _bulkMarkNotSpam(notSpamCandidates),
|
|
),
|
|
IconButton(
|
|
tooltip: l10n.common_delete,
|
|
icon: const Icon(Icons.delete_outline),
|
|
onPressed: selected.isEmpty || readOnly
|
|
? null
|
|
: () => _bulkDelete(selected),
|
|
),
|
|
PopupMenuButton<String>(
|
|
icon: const Icon(Icons.more_vert),
|
|
onSelected: (value) {
|
|
switch (value) {
|
|
case 'select_all':
|
|
setState(() {
|
|
_selectedIds.addAll(
|
|
_visibleMessages().map((m) => m.messageId),
|
|
);
|
|
});
|
|
case 'copy':
|
|
_bulkCopy(selected);
|
|
}
|
|
},
|
|
itemBuilder: (context) => [
|
|
PopupMenuItem(
|
|
value: 'select_all',
|
|
child: ListTile(
|
|
leading: const Icon(Icons.select_all),
|
|
title: Text(l10n.chat_selectAll),
|
|
contentPadding: EdgeInsets.zero,
|
|
),
|
|
),
|
|
PopupMenuItem(
|
|
value: 'copy',
|
|
child: ListTile(
|
|
leading: const Icon(Icons.copy),
|
|
title: Text(l10n.common_copy),
|
|
contentPadding: EdgeInsets.zero,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
Future<void> _bulkMarkSpam(List<ChannelMessage> messages) async {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final text = context.l10n.messageFilter_markedSpamCount(messages.length);
|
|
setState(() {
|
|
_selectedIds.clear();
|
|
_revealedFilteredIds.removeAll(messages.map((m) => m.messageId));
|
|
_revealVersion++;
|
|
});
|
|
await connector.markChannelMessagesSpam([
|
|
for (final m in messages) (widget.channel, m),
|
|
]);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(context, content: Text(text));
|
|
}
|
|
|
|
Future<void> _bulkMarkNotSpam(List<ChannelMessage> messages) async {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final text = context.l10n.messageFilter_markedNotSpamCount(messages.length);
|
|
setState(() {
|
|
_selectedIds.clear();
|
|
_revealedFilteredIds.removeAll(messages.map((m) => m.messageId));
|
|
_revealVersion++;
|
|
});
|
|
await connector.markChannelMessagesNotSpam([
|
|
for (final m in messages) (widget.channel, m),
|
|
]);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(context, content: Text(text));
|
|
}
|
|
|
|
Future<void> _bulkDelete(List<ChannelMessage> messages) async {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final confirmed = await confirmBulkDelete(context, messages.length);
|
|
if (!confirmed || !mounted) return;
|
|
setState(_selectedIds.clear);
|
|
final removed = await connector.deleteChannelMessages(messages);
|
|
if (!mounted || removed == 0) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.chat_messagesDeleted(removed)),
|
|
);
|
|
}
|
|
|
|
void _bulkCopy(List<ChannelMessage> messages) {
|
|
final text = messages
|
|
.map(
|
|
(m) => m.senderName.isEmpty || m.isOutgoing
|
|
? m.text
|
|
: '${m.senderName}: ${m.text}',
|
|
)
|
|
.join('\n');
|
|
setState(_selectedIds.clear);
|
|
copyChatMessageText(context, text);
|
|
}
|
|
|
|
// ---- message filter -------------------------------------------------------
|
|
|
|
/// The message filter, or null when it is not registered (screen tests).
|
|
MessageFilterService? get _messageFilter {
|
|
try {
|
|
return context.read<MessageFilterService>();
|
|
} on ProviderNotFoundException {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
String get _messageFilterChannelId =>
|
|
MeshCoreConnector.messageFilterChannelId(widget.channel);
|
|
|
|
void _setRevealed(Iterable<String> ids, {required bool revealed}) {
|
|
setState(() {
|
|
if (revealed) {
|
|
_revealedFilteredIds.addAll(ids);
|
|
} else {
|
|
_revealedFilteredIds.removeAll(ids);
|
|
}
|
|
_revealVersion++;
|
|
});
|
|
}
|
|
|
|
/// "Hide" on a revealed message collapses its whole run back into one
|
|
/// ghost row, not just that message.
|
|
void _hideFilteredMessage(ChannelMessage message) {
|
|
final layout = _transcriptLayout;
|
|
final messages = context.read<MeshCoreConnector>().getChannelMessages(
|
|
widget.channel,
|
|
);
|
|
final ids = layout == null
|
|
? [message.messageId]
|
|
: layout.revealedRunIdsFor(message.messageId, messages);
|
|
_setRevealed(ids, revealed: false);
|
|
}
|
|
|
|
Future<void> _markSpam(ChannelMessage message) async {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
// Collapse it straight away, even if it had been revealed before.
|
|
_setRevealed([message.messageId], revealed: false);
|
|
await connector.markChannelMessageSpam(widget.channel, message);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.messageFilter_markedSpam),
|
|
);
|
|
}
|
|
|
|
Future<void> _markNotSpam(ChannelMessage message) async {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
_setRevealed([message.messageId], revealed: false);
|
|
await connector.markChannelMessageNotSpam(widget.channel, message);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.messageFilter_markedNotSpam),
|
|
);
|
|
}
|
|
|
|
Future<void> _filterSender(String senderName) async {
|
|
final filter = _messageFilter;
|
|
if (filter == null) return;
|
|
final confirmed = await showDialog<bool>(
|
|
context: context,
|
|
builder: (dialogContext) => AlertDialog(
|
|
title: Text(dialogContext.l10n.messageFilter_filterSender),
|
|
content: Text(
|
|
dialogContext.l10n.messageFilter_filterSenderConfirm(senderName),
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(dialogContext, false),
|
|
child: Text(dialogContext.l10n.common_cancel),
|
|
),
|
|
FilledButton(
|
|
onPressed: () => Navigator.pop(dialogContext, true),
|
|
child: Text(dialogContext.l10n.messageFilter_filterSender),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
if (confirmed != true) return;
|
|
await filter.addRule(
|
|
FilterRule(
|
|
id: MessageFilterService.newRuleId(),
|
|
pattern: senderName,
|
|
field: FilterRuleField.sender,
|
|
match: FilterRuleMatch.exact,
|
|
),
|
|
);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.messageFilter_ruleSaved),
|
|
);
|
|
}
|
|
|
|
Future<void> _filterMessagesLike(ChannelMessage message) async {
|
|
final filter = _messageFilter;
|
|
if (filter == null) return;
|
|
final rule = await showFilterRuleDialog(
|
|
context,
|
|
initialPattern: message.text,
|
|
initialField: FilterRuleField.text,
|
|
);
|
|
if (rule == null) return;
|
|
await filter.addRule(rule);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.messageFilter_ruleSaved),
|
|
);
|
|
}
|
|
|
|
Future<void> _toggleChannelFiltering() async {
|
|
final filter = _messageFilter;
|
|
if (filter == null) return;
|
|
final channelId = _messageFilterChannelId;
|
|
await filter.setChannelExcluded(
|
|
channelId,
|
|
filter.isChannelFiltered(channelId),
|
|
);
|
|
}
|
|
|
|
/// One entry for a run of hidden messages (newest first): a ghost header
|
|
/// that animates the run's messages open and closed underneath it. Opening
|
|
/// lasts for this visit to the chat.
|
|
Widget _buildFilteredGhost(
|
|
List<ChannelMessage> run,
|
|
double textScale, {
|
|
required bool expanded,
|
|
required bool urlImagesEnabled,
|
|
}) {
|
|
final newest = run.first;
|
|
return FilteredMessageRun(
|
|
count: run.length,
|
|
expanded: expanded,
|
|
buildMessages: (context) => [
|
|
for (final message in run.reversed)
|
|
_buildMessageBubble(
|
|
message,
|
|
textScale,
|
|
urlImagesEnabled,
|
|
showFilterBanner: true,
|
|
),
|
|
],
|
|
reason: messageFilterReasonLabel(
|
|
context.l10n,
|
|
newest.filterReason,
|
|
newest.filterDetail,
|
|
),
|
|
textScale: textScale,
|
|
onToggle: () =>
|
|
_setRevealed([for (final m in run) m.messageId], revealed: !expanded),
|
|
);
|
|
}
|
|
|
|
void _showEmojiPicker(ChannelMessage message) {
|
|
showMeshSheet(
|
|
context,
|
|
builder: (context) => EmojiPicker(
|
|
onEmojiSelected: (emoji) {
|
|
_sendReaction(message, emoji);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
void _sendReaction(ChannelMessage message, String emoji) {
|
|
if (!ensureRadioConnected(context)) return;
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final emojiIndex = ReactionHelper.emojiToIndex(emoji);
|
|
if (emojiIndex == null) return; // Unknown emoji, skip
|
|
final hash = message.computeReactionHash();
|
|
final reactionText = ReactionHelper.encodeReaction(hash, emojiIndex);
|
|
connector.sendChannelMessage(widget.channel, reactionText);
|
|
}
|
|
|
|
Future<void> _confirmClearChat() async {
|
|
final confirmed = await confirmClearChat(
|
|
context,
|
|
message: context.l10n.channels_clearChatConfirm,
|
|
);
|
|
if (confirmed) {
|
|
if (!mounted || !ensureRadioConnected(context)) return;
|
|
context.read<MeshCoreConnector>().clearMessagesForChannel(
|
|
widget.channel.index,
|
|
);
|
|
final channelId = widget.channel.storageId;
|
|
if (channelId == null) return;
|
|
try {
|
|
await context.read<ReceivedImageStore>().deleteImagesForChannelId(
|
|
channelId,
|
|
);
|
|
} on ProviderNotFoundException {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<void> _deleteMessage(ChannelMessage message) async {
|
|
if (!ensureRadioConnected(context)) return;
|
|
await context.read<MeshCoreConnector>().deleteChannelMessage(message);
|
|
if (!mounted) return;
|
|
showDismissibleSnackBar(
|
|
context,
|
|
content: Text(context.l10n.chat_messageDeleted),
|
|
);
|
|
}
|
|
|
|
String _formatPathPrefixes(Uint8List pathBytes, int pathHashByteWidth) {
|
|
return PathHelper.splitPathBytes(
|
|
pathBytes,
|
|
pathHashByteWidth,
|
|
).map(PathHelper.formatHopHex).join(',');
|
|
}
|
|
|
|
int? _displayHopCount(
|
|
Uint8List pathBytes,
|
|
int pathHashByteWidth,
|
|
int? fallbackPathLength,
|
|
) {
|
|
if ((fallbackPathLength ?? -1) < 0) return null;
|
|
if (pathBytes.isEmpty) return fallbackPathLength;
|
|
return PathHelper.splitPathBytes(pathBytes, pathHashByteWidth).length;
|
|
}
|
|
|
|
String _displayRegion(String region) {
|
|
return region.startsWith('#') ? region.substring(1) : region;
|
|
}
|
|
|
|
Future<void> openRegionSelectDialog(Channel channel) async {
|
|
// The AppBar subtitle reads the region from the connector inside a
|
|
// Consumer, so setChannelRegion's notifyListeners refreshes it directly —
|
|
// no post-dialog setState needed.
|
|
await showDialog(
|
|
context: context,
|
|
builder: (BuildContext context) => _RegionSelectDialog(channel: channel),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _RegionSelectDialog extends StatefulWidget {
|
|
final Channel channel;
|
|
|
|
const _RegionSelectDialog({required this.channel});
|
|
|
|
@override
|
|
State<_RegionSelectDialog> createState() => _RegionSelectDialogState();
|
|
}
|
|
|
|
class _RegionSelectDialogState extends State<_RegionSelectDialog> {
|
|
final RegionStore regionStore = RegionStore();
|
|
|
|
bool _canForceUnscoped(BuildContext context) =>
|
|
context.read<MeshCoreConnector>().supportsExplicitUnscopedFlood;
|
|
|
|
bool _hasOwnAssignment(BuildContext context) {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final index = widget.channel.index;
|
|
return connector.hasChannelRegion(index) ||
|
|
connector.isChannelExplicitlyUnscoped(index);
|
|
}
|
|
|
|
/// On firmware that cannot force an unscoped flood, explain that floods
|
|
/// without a region still use the radio's default region.
|
|
List<Widget> _buildRadioDefaultNote(BuildContext context) {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final radioDefault = connector.defaultFloodScopeName;
|
|
if (radioDefault == null || connector.supportsExplicitUnscopedFlood) {
|
|
return const [];
|
|
}
|
|
return [
|
|
const SizedBox(height: 8),
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
|
child: Text(
|
|
context.l10n.channels_regionRadioDefaultApplies(radioDefault),
|
|
style: Theme.of(context).textTheme.bodyMedium,
|
|
),
|
|
),
|
|
];
|
|
}
|
|
|
|
Widget _buildUnscopedTile(BuildContext context) {
|
|
final connector = context.read<MeshCoreConnector>();
|
|
final selected = connector.isChannelExplicitlyUnscoped(
|
|
widget.channel.index,
|
|
);
|
|
final primary = Theme.of(context).colorScheme.primary;
|
|
return ListTile(
|
|
leading: Icon(Icons.public_off, color: selected ? primary : null),
|
|
title: Text(context.l10n.settings_regionNoRegion),
|
|
trailing: selected ? Icon(Icons.check, color: primary) : null,
|
|
tileColor: selected ? primary.withValues(alpha: 0.16) : null,
|
|
onTap: () {
|
|
// Tapping the already-selected option clears it back to the default.
|
|
connector.setChannelRegion(
|
|
widget.channel.index,
|
|
selected ? '' : kUnscopedRegion,
|
|
);
|
|
Navigator.pop(context);
|
|
},
|
|
);
|
|
}
|
|
|
|
List<Region> regions = [];
|
|
int selectedIndex = -1;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
loadRegions();
|
|
}
|
|
|
|
void loadRegions() {
|
|
setState(() {
|
|
regions = regionStore.loadRegions();
|
|
final channelRegion = context.read<MeshCoreConnector>().getChannelRegion(
|
|
widget.channel.index,
|
|
);
|
|
selectedIndex = regions.indexOf(channelRegion);
|
|
});
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Dialog(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(8.0),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
AppBar(
|
|
backgroundColor: Colors.transparent,
|
|
title: Text(context.l10n.channels_regionSelect_Title),
|
|
centerTitle: true,
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
|
child: Text(
|
|
context.l10n.channels_regionSelectExplanation,
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
),
|
|
..._buildRadioDefaultNote(context),
|
|
const SizedBox(height: 8),
|
|
if (_canForceUnscoped(context)) _buildUnscopedTile(context),
|
|
if (regions.isEmpty)
|
|
Padding(
|
|
padding: const EdgeInsets.all(24),
|
|
child: Text(context.l10n.channels_regionEmpty),
|
|
)
|
|
else
|
|
Expanded(
|
|
child: ListView.builder(
|
|
itemCount: regions.length,
|
|
itemBuilder: (context, index) {
|
|
final selected = selectedIndex == index;
|
|
final primary = Theme.of(context).colorScheme.primary;
|
|
return ListTile(
|
|
leading: Icon(
|
|
Icons.landscape,
|
|
color: selected ? primary : null,
|
|
),
|
|
title: Text(regions[index]),
|
|
trailing: selected
|
|
? Icon(Icons.check, color: primary)
|
|
: null,
|
|
tileColor: selected
|
|
? primary.withValues(alpha: 0.16)
|
|
: null,
|
|
onTap: () {
|
|
// Tapping the already-selected region clears it.
|
|
context.read<MeshCoreConnector>().setChannelRegion(
|
|
widget.channel.index,
|
|
selected ? '' : regions[index],
|
|
);
|
|
Navigator.pop(context);
|
|
},
|
|
);
|
|
},
|
|
),
|
|
),
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.end,
|
|
children: [
|
|
TextButton(
|
|
onPressed: !_hasOwnAssignment(context)
|
|
? null
|
|
: () {
|
|
context.read<MeshCoreConnector>().setChannelRegion(
|
|
widget.channel.index,
|
|
'',
|
|
);
|
|
Navigator.pop(context);
|
|
},
|
|
child: Text(context.l10n.common_clear),
|
|
),
|
|
TextButton(
|
|
onPressed: () async {
|
|
await pushRegionManagementScreen(context);
|
|
if (!mounted) return;
|
|
loadRegions();
|
|
},
|
|
child: Text(context.l10n.channels_manageRegions),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _SwipeReplyBubble extends StatefulWidget {
|
|
final double maxSwipeOffset;
|
|
final double replySwipeThreshold;
|
|
final VoidCallback onReplyTriggered;
|
|
final Widget Function({required bool isStart}) hintBuilder;
|
|
final Widget child;
|
|
|
|
const _SwipeReplyBubble({
|
|
required this.maxSwipeOffset,
|
|
required this.replySwipeThreshold,
|
|
required this.onReplyTriggered,
|
|
required this.hintBuilder,
|
|
required this.child,
|
|
});
|
|
|
|
@override
|
|
State<_SwipeReplyBubble> createState() => _SwipeReplyBubbleState();
|
|
}
|
|
|
|
class _SwipeReplyBubbleState extends State<_SwipeReplyBubble> {
|
|
Offset? _swipeStartPosition;
|
|
double _swipeOffset = 0;
|
|
double _maxSwipeDistance = 0;
|
|
int? _swipePointerId;
|
|
bool _swipeLockedToHorizontal = false;
|
|
bool _isRtl = false;
|
|
|
|
void _handleSwipeStart(Offset position) {
|
|
_swipeStartPosition = position;
|
|
_maxSwipeDistance = 0;
|
|
if (_swipeOffset != 0) {
|
|
setState(() => _swipeOffset = 0);
|
|
}
|
|
}
|
|
|
|
void _handleSwipePointerDown(PointerDownEvent event) {
|
|
_swipePointerId = event.pointer;
|
|
_swipeLockedToHorizontal = false;
|
|
_handleSwipeStart(event.position);
|
|
}
|
|
|
|
void _handleSwipePointerMove(PointerMoveEvent event) {
|
|
if (_swipePointerId != event.pointer || _swipeStartPosition == null) {
|
|
return;
|
|
}
|
|
|
|
final rawDx = event.position.dx - _swipeStartPosition!.dx;
|
|
final dy = (event.position.dy - _swipeStartPosition!.dy).abs();
|
|
// In LTR swipe left (rawDx < 0) triggers reply; in RTL swipe right (rawDx > 0).
|
|
final signedDx = _isRtl ? rawDx : -rawDx;
|
|
|
|
const axisLockThreshold = 12.0;
|
|
if (!_swipeLockedToHorizontal) {
|
|
// A gesture that moves vertically first is a scroll: give it up for
|
|
// the rest of this pointer so a diagonal thumb drift while scrolling
|
|
// cannot trigger a reply.
|
|
if (dy >= axisLockThreshold && dy >= signedDx.abs()) {
|
|
_resetSwipe();
|
|
return;
|
|
}
|
|
// Lock only for a clearly horizontal drag.
|
|
if (signedDx < axisLockThreshold || signedDx < dy * 2) {
|
|
return;
|
|
}
|
|
_swipeLockedToHorizontal = true;
|
|
} else if (dy > math.max(48.0, signedDx)) {
|
|
// The finger wandered off vertically (list scrolled under it).
|
|
_resetSwipe();
|
|
return;
|
|
}
|
|
|
|
_handleSwipeUpdate(event.position);
|
|
}
|
|
|
|
void _handleSwipeUpdate(Offset position) {
|
|
if (_swipeStartPosition == null) return;
|
|
|
|
final rawDx = position.dx - _swipeStartPosition!.dx;
|
|
final signedDx = _isRtl ? rawDx : -rawDx;
|
|
if (signedDx <= 0) return;
|
|
|
|
if (signedDx < 6) return;
|
|
|
|
if (signedDx > _maxSwipeDistance) {
|
|
_maxSwipeDistance = signedDx;
|
|
}
|
|
|
|
final double clamped = signedDx.clamp(0.0, widget.maxSwipeOffset);
|
|
final adjusted = _applySwipeResistance(clamped, widget.maxSwipeOffset);
|
|
// Translate in the gesture direction: negative for LTR (left), positive for RTL (right).
|
|
final translationOffset = _isRtl ? adjusted : -adjusted;
|
|
if (translationOffset != _swipeOffset) {
|
|
setState(() => _swipeOffset = translationOffset);
|
|
}
|
|
}
|
|
|
|
void _handleSwipePointerUp(Offset position) {
|
|
if (_swipeLockedToHorizontal && _swipeStartPosition != null) {
|
|
final rawDx = position.dx - _swipeStartPosition!.dx;
|
|
final signedDx = _isRtl ? rawDx : -rawDx;
|
|
final peak = math.max(
|
|
_maxSwipeDistance,
|
|
signedDx.clamp(0.0, double.infinity),
|
|
);
|
|
if (peak >= widget.replySwipeThreshold) {
|
|
widget.onReplyTriggered();
|
|
HapticFeedback.selectionClick();
|
|
}
|
|
}
|
|
_resetSwipe();
|
|
}
|
|
|
|
void _resetSwipe() {
|
|
if (_swipeOffset != 0) {
|
|
setState(() => _swipeOffset = 0);
|
|
}
|
|
_swipeStartPosition = null;
|
|
_maxSwipeDistance = 0;
|
|
_swipePointerId = null;
|
|
_swipeLockedToHorizontal = false;
|
|
}
|
|
|
|
double _applySwipeResistance(double rawOffset, double maxOffset) {
|
|
final abs = rawOffset.abs();
|
|
if (abs <= 0) return 0;
|
|
final norm = (abs / maxOffset).clamp(0.0, 1.0);
|
|
const deadZone = 0.18;
|
|
if (norm <= deadZone) {
|
|
return rawOffset.sign * maxOffset * (norm * 0.08);
|
|
}
|
|
final t = ((norm - deadZone) / (1 - deadZone)).clamp(0.0, 1.0);
|
|
final curved = t < 0.5
|
|
? 16 * math.pow(t, 5)
|
|
: 1 - math.pow(-2 * t + 2, 5) / 2;
|
|
const deadZoneEnd = 0.0144;
|
|
return rawOffset.sign *
|
|
maxOffset *
|
|
(deadZoneEnd + curved * (1 - deadZoneEnd));
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
_isRtl = Directionality.of(context) == TextDirection.rtl;
|
|
// In LTR, the bubble slides left and the hint appears on the right (isStart: false).
|
|
// In RTL, the bubble slides right and the hint appears on the left (isStart: true).
|
|
final hintIsStart = _isRtl;
|
|
return Listener(
|
|
onPointerDown: _handleSwipePointerDown,
|
|
onPointerMove: _handleSwipePointerMove,
|
|
onPointerUp: (event) => _handleSwipePointerUp(event.position),
|
|
onPointerCancel: (_) => _resetSwipe(),
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 8),
|
|
child: Stack(
|
|
alignment: Alignment.center,
|
|
children: [
|
|
Positioned.fill(
|
|
child: Opacity(
|
|
opacity: _swipeOffset.abs() / widget.maxSwipeOffset,
|
|
child: widget.hintBuilder(isStart: hintIsStart),
|
|
),
|
|
),
|
|
AnimatedContainer(
|
|
duration: const Duration(milliseconds: 150),
|
|
transform: Matrix4.translationValues(_swipeOffset, 0, 0),
|
|
curve: Curves.easeOut,
|
|
child: widget.child,
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
/// One row of the channel transcript.
|
|
///
|
|
/// Exactly one of [message] / [image] / [ghost] is non-null. Images cannot be
|
|
/// `ChannelMessage`s: they arrive as GRP_DATA chunks with no text frame behind
|
|
/// them, are keyed on (sender prefix, img id, channel) rather than a message id,
|
|
/// and are persisted by [ReceivedImageStore] instead of the channel message
|
|
/// store.
|
|
@immutable
|
|
class _ChannelChatRow {
|
|
final ChannelMessage? message;
|
|
final ReceivedImageEntry? image;
|
|
|
|
/// A run of consecutive messages hidden by the message filter, newest
|
|
/// first, shown as one ghost row.
|
|
final List<ChannelMessage>? ghost;
|
|
|
|
/// [ghost] is a revealed run: its messages are shown under the header.
|
|
final bool ghostExpanded;
|
|
|
|
const _ChannelChatRow({
|
|
this.message,
|
|
this.image,
|
|
this.ghost,
|
|
this.ghostExpanded = false,
|
|
});
|
|
|
|
/// Local arrival time, used for ordering and day separators so a sender
|
|
/// clock running ahead cannot pin a row to the bottom (#584). A ghost run
|
|
/// never spans two days, so its newest member stands for it.
|
|
DateTime get receivedAt =>
|
|
message?.receivedAt ?? ghost?.first.receivedAt ?? image!.firstSeen;
|
|
|
|
/// Stable identity for the scroll-to-message [GlobalKey] map. The `aeic:`
|
|
/// and `ghost:` prefixes keep these from ever colliding with a message id.
|
|
String get id {
|
|
final run = ghost;
|
|
// Same id open or closed, so the run keeps its State and can animate.
|
|
if (run != null) return 'ghost:${run.first.messageId}';
|
|
return message?.messageId ?? 'aeic:${image!.streamId}';
|
|
}
|
|
}
|
|
|
|
/// Memoised ordering of a channel transcript, newest first.
|
|
///
|
|
/// Rows hold positions, not message objects: the connector replaces messages
|
|
/// in place (status, repeats, reactions) without changing their order or id,
|
|
/// so [rowAt] always reads the current object from the live list.
|
|
///
|
|
/// Messages hidden by the message filter are grouped by [groupFilteredRows]:
|
|
/// each visible entry is one row, or one ghost standing in for a run of
|
|
/// hidden messages (none at all in hide mode).
|
|
class _TranscriptLayout {
|
|
final List<ChannelMessage> _source;
|
|
final int _sourceLength;
|
|
final String? _firstId;
|
|
final String? _lastId;
|
|
final int _imageVersion;
|
|
final int _channelIndex;
|
|
final int _filterVersion;
|
|
|
|
/// Newest first. `>= 0` is a message index; `< 0` is image `-(i + 1)`.
|
|
final List<int> _order;
|
|
final List<ReceivedImageEntry> _images;
|
|
|
|
/// Visible entries, newest first; their rows index into [_order].
|
|
final List<TranscriptEntry> _entries;
|
|
|
|
/// Whether filtered messages are being hidden in this channel. When false
|
|
/// they render as ordinary bubbles, without the filter banner.
|
|
final bool filterActive;
|
|
|
|
/// Entry ids, aligned with the visible entries.
|
|
final List<String> ids;
|
|
|
|
/// Row id (message id) -> id of the entry that shows it, for rows that are
|
|
/// not entries themselves (inside a ghost, or dropped in hide mode).
|
|
final Map<String, String> _entryIdByRowId;
|
|
|
|
/// Two messages can collide on messageId (same ms + name/text hash). Only
|
|
/// the first occurrence owns the shared GlobalKey used for
|
|
/// scroll-to-message; duplicates get a local key so no two widgets share
|
|
/// one GlobalKey.
|
|
final Set<int> keyedIndices;
|
|
|
|
_TranscriptLayout._(
|
|
this._source,
|
|
this._sourceLength,
|
|
this._firstId,
|
|
this._lastId,
|
|
this._imageVersion,
|
|
this._channelIndex,
|
|
this._filterVersion,
|
|
this._order,
|
|
this._images,
|
|
this._entries,
|
|
this.filterActive,
|
|
this.ids,
|
|
this._entryIdByRowId,
|
|
this.keyedIndices,
|
|
);
|
|
|
|
factory _TranscriptLayout.build({
|
|
required List<ChannelMessage> messages,
|
|
required List<ReceivedImageEntry> images,
|
|
required int imageVersion,
|
|
required int channelIndex,
|
|
required int filterVersion,
|
|
required FilterDisplayMode displayMode,
|
|
required bool filterActive,
|
|
required Set<String> revealedIds,
|
|
}) {
|
|
DateTime timeOf(int code) =>
|
|
code >= 0 ? messages[code].receivedAt : images[-code - 1].firstSeen;
|
|
// Images are not ChannelMessages: they arrive as GRP_DATA chunks and are
|
|
// owned by ReceivedImageStore, so the two sources are merged here in
|
|
// arrival (receivedAt) order and the list indexes rows, not messages.
|
|
final order = <int>[
|
|
for (var i = 0; i < messages.length; i++) i,
|
|
for (var i = 0; i < images.length; i++) -(i + 1),
|
|
];
|
|
// Stable ascending sort, then reversed so newest appear at the bottom of
|
|
// the reversed ListView.
|
|
mergeSort<int>(order, compare: (a, b) => timeOf(a).compareTo(timeOf(b)));
|
|
final reversed = order.reversed.toList(growable: false);
|
|
final rowInfos = <TranscriptRowInfo>[
|
|
for (final code in reversed)
|
|
code >= 0
|
|
? TranscriptRowInfo(
|
|
id: messages[code].messageId,
|
|
receivedAt: messages[code].receivedAt,
|
|
isFiltered: messages[code].isFiltered,
|
|
)
|
|
: TranscriptRowInfo(
|
|
id: 'aeic:${images[-code - 1].streamId}',
|
|
receivedAt: images[-code - 1].firstSeen,
|
|
isImage: true,
|
|
),
|
|
];
|
|
final entries = groupFilteredRows(
|
|
rowInfos,
|
|
mode: displayMode,
|
|
revealedIds: revealedIds,
|
|
filterActive: filterActive,
|
|
sameDay: isSameChatDay,
|
|
);
|
|
final ids = <String>[for (final entry in entries) entry.id];
|
|
final entryIdByRowId = <String, String>{};
|
|
final entryByRow = entryIndexByRow(entries, rowInfos.length);
|
|
for (var row = 0; row < rowInfos.length; row++) {
|
|
final entry = entryByRow[row];
|
|
if (entry == null) continue;
|
|
final rowId = rowInfos[row].id;
|
|
final entryId = ids[entry];
|
|
// First occurrence wins, matching the GlobalKey ownership below.
|
|
if (rowId != entryId) entryIdByRowId.putIfAbsent(rowId, () => entryId);
|
|
}
|
|
final seen = <String>{};
|
|
final keyed = <int>{};
|
|
for (var i = 0; i < ids.length; i++) {
|
|
if (seen.add(ids[i])) keyed.add(i);
|
|
}
|
|
return _TranscriptLayout._(
|
|
messages,
|
|
messages.length,
|
|
messages.isEmpty ? null : messages.first.messageId,
|
|
messages.isEmpty ? null : messages.last.messageId,
|
|
imageVersion,
|
|
channelIndex,
|
|
filterVersion,
|
|
reversed,
|
|
images,
|
|
entries,
|
|
filterActive,
|
|
ids,
|
|
entryIdByRowId,
|
|
keyed,
|
|
);
|
|
}
|
|
|
|
int get length => _entries.length;
|
|
|
|
bool matches(
|
|
List<ChannelMessage> messages,
|
|
int imageVersion,
|
|
int channel,
|
|
int filterVersion,
|
|
) {
|
|
return identical(messages, _source) &&
|
|
messages.length == _sourceLength &&
|
|
imageVersion == _imageVersion &&
|
|
channel == _channelIndex &&
|
|
filterVersion == _filterVersion &&
|
|
(messages.isEmpty ? null : messages.first.messageId) == _firstId &&
|
|
(messages.isEmpty ? null : messages.last.messageId) == _lastId;
|
|
}
|
|
|
|
/// Id of the visible entry that shows the row with [rowId]: the row itself,
|
|
/// its ghost, or (hide mode) the nearest visible row.
|
|
String entryIdFor(String rowId) => _entryIdByRowId[rowId] ?? rowId;
|
|
|
|
/// Ids of every message in the revealed run containing [messageId], so
|
|
/// "Hide" on one of them collapses the whole run; just [messageId] when it
|
|
/// is not part of a revealed run.
|
|
List<String> revealedRunIdsFor(
|
|
String messageId,
|
|
List<ChannelMessage> messages,
|
|
) {
|
|
for (final entry in _entries) {
|
|
if (!entry.expanded) continue;
|
|
final ids = [
|
|
for (final row in entry.rows)
|
|
if (_order[row] >= 0) messages[_order[row]].messageId,
|
|
];
|
|
if (ids.contains(messageId)) return ids;
|
|
}
|
|
return [messageId];
|
|
}
|
|
|
|
_ChannelChatRow rowAt(int index, List<ChannelMessage> messages) {
|
|
final entry = _entries[index];
|
|
if (entry.isGhost) {
|
|
return _ChannelChatRow(
|
|
ghost: [for (final row in entry.rows) messages[_order[row]]],
|
|
ghostExpanded: entry.expanded,
|
|
);
|
|
}
|
|
final code = _order[entry.row];
|
|
return code >= 0
|
|
? _ChannelChatRow(message: messages[code])
|
|
: _ChannelChatRow(image: _images[-code - 1]);
|
|
}
|
|
}
|
|
|
|
/// A message's route chip and region chip: stacked by default, or side by
|
|
/// side (wrapping on narrow bubbles) when "Region next to hop count" is on.
|
|
class _RouteRegionChips extends StatelessWidget {
|
|
const _RouteRegionChips({required this.sameLine, required this.children});
|
|
|
|
final bool sameLine;
|
|
final List<Widget> children;
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
if (sameLine) {
|
|
// Flexible bounds the Wrap's width inside the bubble's Row so a long
|
|
// region name wraps under the hop chip instead of overflowing.
|
|
return Flexible(
|
|
child: Wrap(
|
|
spacing: 4,
|
|
runSpacing: 2,
|
|
crossAxisAlignment: WrapCrossAlignment.center,
|
|
children: children,
|
|
),
|
|
);
|
|
}
|
|
return Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: children,
|
|
);
|
|
}
|
|
}
|