From 05b47a037b62bf1e5132a9d55159d3b21154e440 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:50:29 -0700 Subject: [PATCH 1/2] Add interactive GPS coordinates in messages --- lib/helpers/coordinate_parser.dart | 277 ++++++++++ lib/helpers/link_handler.dart | 356 +++++++++++-- lib/l10n/app_en.arb | 6 +- lib/l10n/app_localizations.dart | 24 + lib/l10n/app_localizations_bg.dart | 12 + lib/l10n/app_localizations_cs.dart | 12 + lib/l10n/app_localizations_de.dart | 12 + lib/l10n/app_localizations_en.dart | 12 + lib/l10n/app_localizations_es.dart | 12 + lib/l10n/app_localizations_fr.dart | 12 + lib/l10n/app_localizations_hu.dart | 12 + lib/l10n/app_localizations_it.dart | 12 + lib/l10n/app_localizations_ja.dart | 12 + lib/l10n/app_localizations_ko.dart | 12 + lib/l10n/app_localizations_nl.dart | 12 + lib/l10n/app_localizations_pl.dart | 12 + lib/l10n/app_localizations_pt.dart | 12 + lib/l10n/app_localizations_ru.dart | 12 + lib/l10n/app_localizations_sk.dart | 12 + lib/l10n/app_localizations_sl.dart | 12 + lib/l10n/app_localizations_sv.dart | 12 + lib/l10n/app_localizations_uk.dart | 12 + lib/l10n/app_localizations_zh.dart | 12 + lib/screens/bookmarks_screen.dart | 3 + lib/screens/channel_chat_screen.dart | 2 + lib/screens/chat_screen.dart | 2 + lib/screens/coordinate_map_screen.dart | 260 ++++++++++ lib/widgets/translated_message_content.dart | 4 + test/helpers/coordinate_parser_test.dart | 219 ++++++++ test/screens/coordinate_messages_test.dart | 484 ++++++++++++++++++ test/screens/small_screen_layout_test.dart | 6 + .../translated_message_content_test.dart | 84 ++- untranslated.json | 114 ++++- 33 files changed, 1985 insertions(+), 84 deletions(-) create mode 100644 lib/helpers/coordinate_parser.dart create mode 100644 lib/screens/coordinate_map_screen.dart create mode 100644 test/helpers/coordinate_parser_test.dart create mode 100644 test/screens/coordinate_messages_test.dart diff --git a/lib/helpers/coordinate_parser.dart b/lib/helpers/coordinate_parser.dart new file mode 100644 index 00000000..2fc30033 --- /dev/null +++ b/lib/helpers/coordinate_parser.dart @@ -0,0 +1,277 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_linkify/flutter_linkify.dart'; + +import '../utils/platform_info.dart'; + +/// A parsed WGS84 decimal coordinate pair (`latitude, longitude`) found in text. +@immutable +class ParsedCoordinate { + final double latitude; + final double longitude; + final String rawText; + final int start; + final int end; + + const ParsedCoordinate({ + required this.latitude, + required this.longitude, + required this.rawText, + required this.start, + required this.end, + }); + + @override + bool operator ==(Object other) => + identical(this, other) || + other is ParsedCoordinate && + latitude == other.latitude && + longitude == other.longitude && + rawText == other.rawText && + start == other.start && + end == other.end; + + @override + int get hashCode => Object.hash(latitude, longitude, rawText, start, end); + + @override + String toString() => + 'ParsedCoordinate($latitude, $longitude, "$rawText", $start..$end)'; +} + +/// Linkify element representing a detected GPS coordinate pair. +class CoordinateElement extends LinkableElement { + final double latitude; + final double longitude; + + CoordinateElement({ + required this.latitude, + required this.longitude, + required String rawText, + }) : super( + rawText, + buildExternalMapUri(latitude, longitude).toString(), + rawText, + ); + + @override + bool operator ==(Object other) => + identical(this, other) || + other is CoordinateElement && + super.equals(other) && + latitude == other.latitude && + longitude == other.longitude; + + @override + int get hashCode => Object.hash(super.hashCode, latitude, longitude); + + @override + String toString() => "CoordinateElement: '$text' ($latitude, $longitude)"; +} + +/// Builds a platform-appropriate external maps URI for [latitude] and [longitude]. +Uri buildExternalMapUri( + double latitude, + double longitude, { + TargetPlatform? platform, + bool? isWeb, +}) { + final normalizedLat = latitude == 0 ? 0.0 : latitude; + final normalizedLon = longitude == 0 ? 0.0 : longitude; + final latStr = normalizedLat.toString(); + final lonStr = normalizedLon.toString(); + + final web = isWeb ?? PlatformInfo.isWeb; + if (web) { + return Uri.parse( + 'https://www.openstreetmap.org/?mlat=$latStr&mlon=$lonStr#map=16/$latStr/$lonStr', + ); + } + + final targetPlatform = platform ?? defaultTargetPlatform; + return switch (targetPlatform) { + TargetPlatform.android => Uri.parse( + 'geo:$latStr,$lonStr?q=$latStr,$lonStr', + ), + TargetPlatform.iOS || TargetPlatform.macOS => Uri.parse( + 'https://maps.apple.com/?ll=$latStr,$lonStr&q=$latStr,$lonStr', + ), + TargetPlatform.linux || + TargetPlatform.windows || + TargetPlatform.fuchsia => Uri.parse( + 'https://www.openstreetmap.org/?mlat=$latStr&mlon=$lonStr#map=16/$latStr/$lonStr', + ), + }; +} + +/// Detects decimal `latitude, longitude` GPS coordinates inside [TextElement]s +/// while avoiding URLs, version numbers, integer pairs, and embedded identifiers. +class CoordinateLinkifier extends Linkifier { + const CoordinateLinkifier(); + + static final RegExp _candidateRegex = RegExp( + r'([+-]?\d+\.\d+),[ \t]*([+-]?\d+\.\d+)', + ); + + // Covers URI schemes and bare domain/path strings that UrlLinkifier leaves + // as plain text (e.g. geo:..., ftp://..., maps.google.com/?q=...). + static final RegExp _nonLinkifiedUrlRegex = RegExp( + r'(?:[a-zA-Z][a-zA-Z0-9+.-]*://|geo:|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/)[^\s]*', + ); + + static final RegExp _disallowedBoundaryChar = RegExp(r'[A-Za-z0-9_+-]'); + static final RegExp _asciiDigit = RegExp(r'[0-9]'); + + @override + List parse( + List elements, + LinkifyOptions options, + ) { + final result = []; + for (final element in elements) { + if (element is! TextElement) { + result.add(element); + continue; + } + result.addAll(_parseSegment(element.text)); + } + return result; + } + + static List _parseSegment(String text) { + final blockedRanges = <({int start, int end})>[ + for (final m in _nonLinkifiedUrlRegex.allMatches(text)) + (start: m.start, end: m.end), + ]; + + final elements = []; + var cursor = 0; + + for (final match in _candidateRegex.allMatches(text)) { + if (_isInsideRanges(match.start, match.end, blockedRanges)) { + continue; + } + if (!_hasValidBoundaries(text, match.start, match.end)) { + continue; + } + + final lat = double.tryParse(match.group(1)!); + final lon = double.tryParse(match.group(2)!); + if (lat == null || lon == null || !lat.isFinite || !lon.isFinite) { + continue; + } + if (lat < -90.0 || lat > 90.0 || lon < -180.0 || lon > 180.0) { + continue; + } + + if (match.start > cursor) { + elements.add(TextElement(text.substring(cursor, match.start))); + } + elements.add( + CoordinateElement( + latitude: lat == 0 ? 0.0 : lat, + longitude: lon == 0 ? 0.0 : lon, + rawText: match.group(0)!, + ), + ); + cursor = match.end; + } + + if (elements.isEmpty) { + return [TextElement(text)]; + } + if (cursor < text.length) { + elements.add(TextElement(text.substring(cursor))); + } + return elements; + } + + static bool _isInsideRanges( + int start, + int end, + List<({int start, int end})> ranges, + ) { + for (final range in ranges) { + if (start < range.end && end > range.start) { + return true; + } + } + return false; + } + + static bool _hasValidBoundaries(String text, int start, int end) { + if (start > 0) { + final prev = text[start - 1]; + if (prev == '.' || _disallowedBoundaryChar.hasMatch(prev)) { + return false; + } + } + if (end < text.length) { + final next = text[end]; + if (_disallowedBoundaryChar.hasMatch(next)) { + return false; + } + // Reject version-like continuations (e.g. "1.2,3.4.5"), while allowing + // trailing sentence periods (e.g. "38.722,-9.139."). + if (next == '.' && + end + 1 < text.length && + _asciiDigit.hasMatch(text[end + 1])) { + return false; + } + } + return true; + } +} + +/// Shared parser returning linkified elements and extracted [ParsedCoordinate]s. +class CoordinateParser { + CoordinateParser._(); + + static const LinkifyOptions linkifyOptions = LinkifyOptions( + humanize: false, + defaultToHttps: false, + ); + + static const List linkifiers = [ + UrlLinkifier(), + EmailLinkifier(), + CoordinateLinkifier(), + ]; + + /// Splits [text] into URL, email, coordinate, and plain-text elements. + static List linkifyWithCoordinates(String text) { + if (text.isEmpty) return const []; + var elements = [TextElement(text)]; + for (final linkifier in linkifiers) { + elements = linkifier.parse(elements, linkifyOptions); + } + return elements; + } + + /// Extracts all valid WGS84 decimal coordinates in [text]. + static List parse(String text) { + if (text.isEmpty) return const []; + final elements = linkifyWithCoordinates(text); + final results = []; + var offset = 0; + + for (final element in elements) { + final raw = element.originText; + final index = text.indexOf(raw, offset); + final start = index >= 0 ? index : offset; + final end = start + raw.length; + if (element is CoordinateElement) { + results.add( + ParsedCoordinate( + latitude: element.latitude, + longitude: element.longitude, + rawText: element.text, + start: start, + end: end, + ), + ); + } + offset = end; + } + return results; + } +} diff --git a/lib/helpers/link_handler.dart b/lib/helpers/link_handler.dart index 8a4752d7..ba109649 100644 --- a/lib/helpers/link_handler.dart +++ b/lib/helpers/link_handler.dart @@ -1,10 +1,16 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_linkify/flutter_linkify.dart'; import 'package:url_launcher/url_launcher.dart'; -import '../l10n/l10n.dart'; -import '../utils/platform_info.dart'; + +import '../helpers/coordinate_parser.dart'; import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; +import '../screens/coordinate_map_screen.dart'; +import '../theme/mesh_theme.dart'; +import '../utils/platform_info.dart'; +import '../widgets/mesh_ui.dart'; class LinkHandler { static TextStyle defaultLinkStyle(BuildContext context, TextStyle base) { @@ -15,60 +21,153 @@ class LinkHandler { return base.copyWith(color: orange, decoration: TextDecoration.underline); } - /// The system text scale as a linear factor for [style]'s size. - /// - /// flutter_linkify only takes a `textScaleFactor` (default 1.0, which - /// ignores the system font size), so the ambient [TextScaler] is sampled - /// at the style's font size to keep Android's nonlinear scaling. The - /// in-app chat text scale is already part of `style.fontSize`. - static double systemTextScaleFactor(BuildContext context, TextStyle style) { - final fontSize = - style.fontSize ?? DefaultTextStyle.of(context).style.fontSize ?? 14; - if (fontSize <= 0) return 1.0; - return MediaQuery.textScalerOf(context).scale(fontSize) / fontSize; + static Color _inferBackground(BuildContext context, TextStyle base) { + final textColor = base.color; + if (textColor != null) { + return textColor.computeLuminance() > 0.5 + ? MeshPalette.bg2 + : Colors.white; + } + return Theme.of(context).colorScheme.surfaceContainerLow; } - /// Returns a [SelectableLinkify] on desktop or a [Linkify] on mobile. + static TextStyle defaultCoordinateStyle( + BuildContext context, + TextStyle base, { + Color? backgroundColor, + }) { + final scheme = Theme.of(context).colorScheme; + final effectiveBg = backgroundColor ?? _inferBackground(context, base); + final accent = readableAccent( + scheme.primary, + effectiveBg, + minContrast: 4.5, + ); + return base.copyWith( + color: accent, + decoration: TextDecoration.underline, + decorationColor: accent, + fontWeight: FontWeight.w600, + ); + } + + /// Returns an interactive rich-text widget (selectable on desktop) with URL, + /// email, and GPS coordinate detection. static Widget buildLinkifyText({ required BuildContext context, required String text, required TextStyle style, TextStyle? linkStyle, + TextStyle? coordinateStyle, + Color? backgroundColor, VoidCallback? onSecondaryTap, }) { - final effectiveLinkStyle = linkStyle ?? defaultLinkStyle(context, style); - const options = LinkifyOptions(humanize: false, defaultToHttps: false); - const linkifiers = [UrlLinkifier(), EmailLinkifier()]; - void onOpen(LinkableElement link) => handleLinkTap(context, link.url); - final textScaleFactor = systemTextScaleFactor(context, style); - - if (PlatformInfo.isDesktop) { - final linkify = SelectableLinkify( - text: text, - style: style, - linkStyle: effectiveLinkStyle, - options: options, - linkifiers: linkifiers, - onOpen: onOpen, - textScaleFactor: textScaleFactor, - ); - if (onSecondaryTap == null) return linkify; - return Listener( - onPointerDown: (event) { - if (event.buttons & kSecondaryMouseButton != 0) onSecondaryTap(); - }, - behavior: HitTestBehavior.translucent, - child: linkify, - ); - } - return Linkify( + return _InteractiveMessageText( text: text, style: style, - linkStyle: effectiveLinkStyle, - options: options, - linkifiers: linkifiers, - onOpen: onOpen, - textScaleFactor: textScaleFactor, + linkStyle: linkStyle, + coordinateStyle: coordinateStyle, + backgroundColor: backgroundColor, + onSecondaryTap: onSecondaryTap, + ); + } + + static void openCoordinateMap( + BuildContext context, + CoordinateElement coordinate, + ) { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => CoordinateMapScreen( + latitude: coordinate.latitude, + longitude: coordinate.longitude, + label: coordinate.text, + ), + ), + ); + } + + static Future copyCoordinateLocation( + BuildContext context, + String text, + ) async { + await Clipboard.setData(ClipboardData(text: text)); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.coordinate_copied), + ); + } + + static Future openCoordinateInExternalMaps( + BuildContext context, + double latitude, + double longitude, + ) async { + final uri = buildExternalMapUri(latitude, longitude); + try { + if (!await launchUrl(uri, mode: LaunchMode.externalApplication)) { + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_couldNotOpenLink(uri.toString())), + backgroundColor: Theme.of(context).colorScheme.error, + ); + } + } + } catch (_) { + if (context.mounted) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_couldNotOpenLink(uri.toString())), + backgroundColor: Theme.of(context).colorScheme.error, + ); + } + } + } + + static Future showCoordinateActionSheet( + BuildContext context, + CoordinateElement coordinate, + ) { + return showMeshSheet( + context, + builder: (sheetContext) { + final l10n = sheetContext.l10n; + return SafeArea( + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BottomSheetHeader( + title: coordinate.text, + subtitle: l10n.chat_location, + ), + ListTile( + leading: const Icon(Icons.copy), + title: Text(l10n.coordinate_copyLocation), + onTap: () { + Navigator.pop(sheetContext); + copyCoordinateLocation(context, coordinate.text); + }, + ), + ListTile( + leading: const Icon(Icons.open_in_new), + title: Text(l10n.coordinate_openInMaps), + onTap: () { + Navigator.pop(sheetContext); + openCoordinateInExternalMaps( + context, + coordinate.latitude, + coordinate.longitude, + ); + }, + ), + ], + ), + ), + ); + }, ); } @@ -139,3 +238,170 @@ class LinkHandler { } } } + +/// Extends [TapGestureRecognizer] so Flutter's paragraph/editable semantics +/// recognize it as a tappable link while also forwarding pointers to an owned +/// [LongPressGestureRecognizer] in the same gesture arena. +class _CoordinateGestureRecognizer extends TapGestureRecognizer { + final LongPressGestureRecognizer _longPress; + + _CoordinateGestureRecognizer({ + required VoidCallback onTap, + required VoidCallback onLongPress, + }) : _longPress = LongPressGestureRecognizer()..onLongPress = onLongPress { + this.onTap = onTap; + } + + @override + void addPointer(PointerDownEvent event) { + super.addPointer(event); + _longPress.addPointer(event); + } + + @override + void dispose() { + _longPress.dispose(); + super.dispose(); + } +} + +class _InteractiveMessageText extends StatefulWidget { + final String text; + final TextStyle style; + final TextStyle? linkStyle; + final TextStyle? coordinateStyle; + final Color? backgroundColor; + final VoidCallback? onSecondaryTap; + + const _InteractiveMessageText({ + required this.text, + required this.style, + this.linkStyle, + this.coordinateStyle, + this.backgroundColor, + this.onSecondaryTap, + }); + + @override + State<_InteractiveMessageText> createState() => + _InteractiveMessageTextState(); +} + +class _InteractiveMessageTextState extends State<_InteractiveMessageText> { + late List _elements; + final List _recognizers = []; + + @override + void initState() { + super.initState(); + _rebuildSpans(); + } + + @override + void didUpdateWidget(covariant _InteractiveMessageText oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.text != widget.text) { + _disposeRecognizers(); + _rebuildSpans(); + } + } + + @override + void dispose() { + _disposeRecognizers(); + super.dispose(); + } + + void _disposeRecognizers() { + for (final recognizer in _recognizers) { + recognizer.dispose(); + } + _recognizers.clear(); + } + + void _rebuildSpans() { + _elements = CoordinateParser.linkifyWithCoordinates(widget.text); + } + + InlineSpan _buildElementSpan( + LinkifyElement element, + TextStyle effectiveLinkStyle, + TextStyle effectiveCoordinateStyle, + ) { + if (element is CoordinateElement) { + final recognizer = _CoordinateGestureRecognizer( + onTap: () { + if (!mounted) return; + LinkHandler.openCoordinateMap(context, element); + }, + onLongPress: () { + if (!mounted) return; + LinkHandler.showCoordinateActionSheet(context, element); + }, + ); + _recognizers.add(recognizer); + return TextSpan( + text: element.text, + style: effectiveCoordinateStyle, + recognizer: recognizer, + mouseCursor: SystemMouseCursors.click, + ); + } + if (element is LinkableElement) { + final recognizer = TapGestureRecognizer() + ..onTap = () { + if (!mounted) return; + LinkHandler.handleLinkTap(context, element.url); + }; + _recognizers.add(recognizer); + return TextSpan( + text: element.text, + style: effectiveLinkStyle, + recognizer: recognizer, + mouseCursor: SystemMouseCursors.click, + ); + } + return TextSpan(text: element.text, style: widget.style); + } + + @override + Widget build(BuildContext context) { + _disposeRecognizers(); + final effectiveLinkStyle = + widget.linkStyle ?? LinkHandler.defaultLinkStyle(context, widget.style); + final effectiveCoordinateStyle = + widget.coordinateStyle ?? + LinkHandler.defaultCoordinateStyle( + context, + widget.style, + backgroundColor: widget.backgroundColor, + ); + final span = TextSpan( + style: widget.style, + children: [ + for (final element in _elements) + _buildElementSpan( + element, + effectiveLinkStyle, + effectiveCoordinateStyle, + ), + ], + ); + + if (PlatformInfo.isDesktop) { + final selectable = SelectableText.rich(span); + if (widget.onSecondaryTap == null) return selectable; + return Listener( + onPointerDown: (event) { + if (event.buttons & kSecondaryMouseButton != 0) { + widget.onSecondaryTap!(); + } + }, + behavior: HitTestBehavior.translucent, + child: selectable, + ); + } + + return Text.rich(span); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 9fdab531..fb372f12 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -4459,5 +4459,9 @@ "addContact_publicKeyInvalid": "Public key must be 64 hex characters (32 bytes)", "addContact_clipboardKeyLoaded": "Public key filled in. Choose a contact type, enter a name, and tap save.", "addContact_fromDiscovered": "Add from Discovered Contacts", - "addContact_saveFailed": "Failed to add contact." + "addContact_saveFailed": "Failed to add contact.", + "coordinateMap_title": "Location", + "coordinate_copyLocation": "Copy location", + "coordinate_openInMaps": "Open in maps", + "coordinate_copied": "Location copied" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 1a95b947..91f0e099 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -12957,6 +12957,30 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Failed to add contact.'** String get addContact_saveFailed; + + /// No description provided for @coordinateMap_title. + /// + /// In en, this message translates to: + /// **'Location'** + String get coordinateMap_title; + + /// No description provided for @coordinate_copyLocation. + /// + /// In en, this message translates to: + /// **'Copy location'** + String get coordinate_copyLocation; + + /// No description provided for @coordinate_openInMaps. + /// + /// In en, this message translates to: + /// **'Open in maps'** + String get coordinate_openInMaps; + + /// No description provided for @coordinate_copied. + /// + /// In en, this message translates to: + /// **'Location copied'** + String get coordinate_copied; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index a25835a8..c34ce131 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -7780,4 +7780,16 @@ class AppLocalizationsBg extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 3c21b58f..dd1c2f0e 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -7751,4 +7751,16 @@ class AppLocalizationsCs extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 9c2fc3d7..6ba0bdc1 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -7794,4 +7794,16 @@ class AppLocalizationsDe extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 5dc6ebe2..73403d34 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -7665,4 +7665,16 @@ class AppLocalizationsEn extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 13157491..d6decaeb 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -7772,4 +7772,16 @@ class AppLocalizationsEs extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 3412c216..3dc856b8 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -7800,4 +7800,16 @@ class AppLocalizationsFr extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 36b2559f..1b79ee96 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -7763,4 +7763,16 @@ class AppLocalizationsHu extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 85e42b74..b947fd5b 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -7783,4 +7783,16 @@ class AppLocalizationsIt extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 4000f470..2e4fb87e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -7425,4 +7425,16 @@ class AppLocalizationsJa extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index f6158ab6..0e8f68e0 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -7437,4 +7437,16 @@ class AppLocalizationsKo extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 460168ad..bab90146 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -7739,4 +7739,16 @@ class AppLocalizationsNl extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 36d2c8b8..8ff2a74f 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -7817,4 +7817,16 @@ class AppLocalizationsPl extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 7e8aa53b..df59f378 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -7761,6 +7761,18 @@ class AppLocalizationsPt extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } /// The translations for Portuguese, as used in Portugal (`pt_PT`). diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index ebc850d1..87c33317 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -7797,4 +7797,16 @@ class AppLocalizationsRu extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index b5fee2ba..f8d13492 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -7762,4 +7762,16 @@ class AppLocalizationsSk extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 7e60528f..2c807d71 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -7756,4 +7756,16 @@ class AppLocalizationsSl extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9b4b635c..64008f62 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -7716,4 +7716,16 @@ class AppLocalizationsSv extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index e2bbcf5f..552aeaae 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -7809,4 +7809,16 @@ class AppLocalizationsUk extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index dbc9d3b1..50dd22f5 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -7267,4 +7267,16 @@ class AppLocalizationsZh extends AppLocalizations { @override String get addContact_saveFailed => 'Failed to add contact.'; + + @override + String get coordinateMap_title => 'Location'; + + @override + String get coordinate_copyLocation => 'Copy location'; + + @override + String get coordinate_openInMaps => 'Open in maps'; + + @override + String get coordinate_copied => 'Location copied'; } diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dart index 3ae89ce9..2001db4a 100644 --- a/lib/screens/bookmarks_screen.dart +++ b/lib/screens/bookmarks_screen.dart @@ -96,6 +96,9 @@ class _BookmarksScreenState extends State { : bookmark.text, style: textStyle, originalStyle: textStyle.copyWith(fontStyle: FontStyle.italic), + backgroundColor: + Theme.of(context).cardTheme.color ?? + Theme.of(context).colorScheme.surfaceContainerLow, ); return Card( margin: const EdgeInsets.only(bottom: 10), diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 4daf7613..82641df4 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1204,6 +1204,7 @@ class _ChannelChatScreenState extends State fontStyle: FontStyle.italic, color: textColor.withValues(alpha: 0.72), ), + backgroundColor: colors.background, onSecondaryTap: PlatformInfo.isDesktop ? () => _showMessageActions(message) : null, @@ -1356,6 +1357,7 @@ class _ChannelChatScreenState extends State alpha: 0.72, ), ), + backgroundColor: colors.background, onSecondaryTap: PlatformInfo.isDesktop ? () => _showMessageActions(message) : null, diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 1276a95a..e8d3eba2 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -1686,6 +1686,7 @@ class _MessageBubble extends StatelessWidget { color: textColor.withValues(alpha: 0.72), fontSize: bodyFontSize * textScale, ), + backgroundColor: colors.background, onSecondaryTap: PlatformInfo.isDesktop ? onLongPress : null, ), ), @@ -1820,6 +1821,7 @@ class _MessageBubble extends StatelessWidget { ), fontSize: bodyFontSize * textScale, ), + backgroundColor: colors.background, onSecondaryTap: PlatformInfo.isDesktop ? onLongPress : null, diff --git a/lib/screens/coordinate_map_screen.dart b/lib/screens/coordinate_map_screen.dart new file mode 100644 index 00000000..da3240c1 --- /dev/null +++ b/lib/screens/coordinate_map_screen.dart @@ -0,0 +1,260 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:latlong2/latlong.dart'; +import 'package:provider/provider.dart'; + +import '../helpers/link_handler.dart'; +import '../l10n/l10n.dart'; +import '../services/map_tile_cache_service.dart'; +import '../theme/mesh_theme.dart'; +import '../widgets/adaptive_app_bar_title.dart'; +import '../widgets/mesh_ui.dart'; + +/// Dedicated full-screen map centered on a tapped GPS coordinate. +class CoordinateMapScreen extends StatefulWidget { + final double latitude; + final double longitude; + final String? label; + + const CoordinateMapScreen({ + super.key, + required this.latitude, + required this.longitude, + this.label, + }); + + @override + State createState() => _CoordinateMapScreenState(); +} + +class _CoordinateMapScreenState extends State { + static const double _initialZoom = 15.0; + static const double _minZoom = 2.0; + static const double _maxZoom = 18.0; + + final MapController _mapController = MapController(); + + LatLng get _position => LatLng(widget.latitude, widget.longitude); + + String get _coordinateText => widget.label?.trim().isNotEmpty == true + ? widget.label!.trim() + : '${widget.latitude}, ${widget.longitude}'; + + @override + void dispose() { + _mapController.dispose(); + super.dispose(); + } + + void _zoomBy(double delta) { + final camera = _mapController.camera; + final nextZoom = (camera.zoom + delta).clamp(_minZoom, _maxZoom).toDouble(); + _mapController.move(camera.center, nextZoom); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final mapTheme = MeshMapTheme.of(context); + final tileCache = context.read(); + final isDesktop = + defaultTargetPlatform == TargetPlatform.linux || + defaultTargetPlatform == TargetPlatform.windows || + defaultTargetPlatform == TargetPlatform.macOS; + final labelSurface = scheme.surfaceContainerLow; + final iconAccent = readableAccent( + scheme.primary, + labelSurface, + minContrast: 3, + ); + + return Scaffold( + appBar: AppBar( + centerTitle: true, + title: AdaptiveAppBarTitle(l10n.coordinateMap_title), + actions: [ + IconButton( + icon: const Icon(Icons.copy), + tooltip: l10n.coordinate_copyLocation, + onPressed: () => + LinkHandler.copyCoordinateLocation(context, _coordinateText), + ), + IconButton( + icon: const Icon(Icons.open_in_new), + tooltip: l10n.coordinate_openInMaps, + onPressed: () => LinkHandler.openCoordinateInExternalMaps( + context, + widget.latitude, + widget.longitude, + ), + ), + ], + ), + body: Stack( + children: [ + FlutterMap( + mapController: _mapController, + options: MapOptions( + initialCenter: _position, + initialZoom: _initialZoom, + minZoom: _minZoom, + maxZoom: _maxZoom, + interactionOptions: InteractionOptions( + flags: ~InteractiveFlag.rotate, + scrollWheelVelocity: isDesktop ? 0.012 : 0.005, + cursorKeyboardRotationOptions: + CursorKeyboardRotationOptions.disabled(), + keyboardOptions: isDesktop + ? const KeyboardOptions( + enableArrowKeysPanning: true, + enableWASDPanning: true, + enableRFZooming: true, + ) + : const KeyboardOptions.disabled(), + ), + ), + children: [ + tileCache.buildTileLayer(context), + MarkerLayer( + markers: [ + Marker( + point: _position, + width: 48, + height: 48, + child: IgnorePointer( + child: Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: mapTheme.followsTheme + ? mapTheme.accent + : MapPalette.batteryLow, + border: Border.all( + color: MapPalette.markerOutline, + width: 3, + ), + boxShadow: const [ + BoxShadow( + color: MapPalette.markerShadow, + blurRadius: 8, + offset: Offset(0, 3), + ), + ], + ), + child: const Icon( + Icons.location_on, + color: MapPalette.markerOutline, + size: 26, + ), + ), + ), + ), + ], + ), + ], + ), + Positioned( + top: 12, + right: 12, + child: Column( + children: [ + _CoordinateMapControlButton( + icon: Icons.add, + tooltip: l10n.map_zoomIn, + onPressed: () => _zoomBy(1), + ), + const SizedBox(height: 8), + _CoordinateMapControlButton( + icon: Icons.remove, + tooltip: l10n.map_zoomOut, + onPressed: () => _zoomBy(-1), + ), + const SizedBox(height: 8), + _CoordinateMapControlButton( + icon: Icons.my_location, + tooltip: l10n.map_centerMap, + onPressed: () => _mapController.move(_position, _initialZoom), + ), + ], + ), + ), + Positioned( + left: 16, + right: 16, + bottom: 16, + child: SafeArea( + top: false, + child: Material( + color: labelSurface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + side: BorderSide(color: scheme.outlineVariant), + ), + elevation: 2, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 10, + ), + child: Row( + children: [ + Icon( + Icons.location_on_outlined, + color: iconAccent, + size: 22, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + _coordinateText, + style: MeshTheme.mono( + fontSize: 14, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } +} + +class _CoordinateMapControlButton extends StatelessWidget { + final IconData icon; + final String tooltip; + final VoidCallback onPressed; + + const _CoordinateMapControlButton({ + required this.icon, + required this.tooltip, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Material( + color: scheme.surfaceContainerLow, + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(MeshRadii.md), + side: BorderSide(color: scheme.outlineVariant), + ), + clipBehavior: Clip.antiAlias, + child: IconButton( + icon: Icon(icon), + tooltip: tooltip, + onPressed: onPressed, + iconSize: 22, + ), + ); + } +} diff --git a/lib/widgets/translated_message_content.dart b/lib/widgets/translated_message_content.dart index a40bacf8..c015585e 100644 --- a/lib/widgets/translated_message_content.dart +++ b/lib/widgets/translated_message_content.dart @@ -7,6 +7,7 @@ class TranslatedMessageContent extends StatelessWidget { final String? originalText; final TextStyle style; final TextStyle? originalStyle; + final Color? backgroundColor; final bool showOriginalFirst; final VoidCallback? onSecondaryTap; @@ -16,6 +17,7 @@ class TranslatedMessageContent extends StatelessWidget { required this.style, this.originalText, this.originalStyle, + this.backgroundColor, this.showOriginalFirst = true, this.onSecondaryTap, }); @@ -38,6 +40,7 @@ class TranslatedMessageContent extends StatelessWidget { fontStyle: FontStyle.italic, fontSize: style.fontSize, ), + backgroundColor: backgroundColor, onSecondaryTap: onSecondaryTap, ) : null; @@ -45,6 +48,7 @@ class TranslatedMessageContent extends StatelessWidget { context: context, text: trimmedDisplay, style: style, + backgroundColor: backgroundColor, onSecondaryTap: onSecondaryTap, ); diff --git a/test/helpers/coordinate_parser_test.dart b/test/helpers/coordinate_parser_test.dart new file mode 100644 index 00000000..75e5caeb --- /dev/null +++ b/test/helpers/coordinate_parser_test.dart @@ -0,0 +1,219 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_linkify/flutter_linkify.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/coordinate_parser.dart'; + +void main() { + group('CoordinateParser.parse', () { + test('parses positive and negative decimal pairs', () { + const inputs = [ + ('37.7749,-122.4194', 37.7749, -122.4194), + ('38.722,-9.139', 38.722, -9.139), + ('-33.86882, 151.20929', -33.86882, 151.20929), + ('51.5074, -0.1278', 51.5074, -0.1278), + ('0.0, 0.0', 0.0, 0.0), + ('45.515232, -122.678385', 45.515232, -122.678385), + ('37.77491234, -122.41945678', 37.77491234, -122.41945678), + ]; + + for (final (text, expectedLat, expectedLon) in inputs) { + final parsed = CoordinateParser.parse(text); + expect(parsed, hasLength(1), reason: 'Failed for "$text"'); + expect(parsed.first.latitude, closeTo(expectedLat, 1e-12)); + expect(parsed.first.longitude, closeTo(expectedLon, 1e-12)); + expect(parsed.first.rawText, text); + expect(parsed.first.start, 0); + expect(parsed.first.end, text.length); + } + }); + + test('parses explicit + signs and optional whitespace after comma', () { + final parsed = CoordinateParser.parse( + 'Meet at +37.7749,+122.4194 or +45.5152,\t-122.6784', + ); + expect(parsed, hasLength(2)); + expect(parsed[0].rawText, '+37.7749,+122.4194'); + expect(parsed[0].latitude, 37.7749); + expect(parsed[0].longitude, 122.4194); + expect(parsed[1].rawText, '+45.5152,\t-122.6784'); + expect(parsed[1].latitude, 45.5152); + expect(parsed[1].longitude, -122.6784); + }); + + test('accepts WGS84 boundary coordinates and rejects out-of-range', () { + final validBounds = CoordinateParser.parse( + '90.0, 180.0 and -90.0, -180.0', + ); + expect(validBounds, hasLength(2)); + expect(validBounds[0].latitude, 90.0); + expect(validBounds[0].longitude, 180.0); + expect(validBounds[1].latitude, -90.0); + expect(validBounds[1].longitude, -180.0); + + const invalidBounds = [ + '90.0001, 0.0', + '-90.1, 0.0', + '0.0, 180.0001', + '0.0, -180.1', + '990.0, -180.0', + '123.45, 67.89', + ]; + for (final text in invalidBounds) { + expect( + CoordinateParser.parse(text), + isEmpty, + reason: 'Should reject "$text"', + ); + } + }); + + test('rejects plain integer pairs and mixed integer/decimal pairs', () { + const invalid = [ + '1,2', + '10, 20', + '-45, 122', + '37,-122.4194', + '37.7749,-122', + ]; + for (final text in invalid) { + expect( + CoordinateParser.parse(text), + isEmpty, + reason: 'Should reject "$text"', + ); + } + }); + + test('rejects version numbers and digits inside words or identifiers', () { + const invalid = [ + '1.2.3,4.5', + '1.2,3.4.5', + '1.2, 3.4.5', + '1.2.3, 4.5.6', + 'v1.2,3.4', + 'foo37.7749,-122.4194', + '37.7749,-122.4194bar', + 'id_37.7749,-122.4194', + '37.7749,-122.4194_end', + '--37.7749,-122.4194', + '+-37.7749,-122.4194', + '1.2,3.4-5', + ]; + for (final text in invalid) { + expect( + CoordinateParser.parse(text), + isEmpty, + reason: 'Should reject "$text"', + ); + } + }); + + test('handles punctuation boundaries around coordinates', () { + const text = + 'Camp (37.7749, -122.4194), ridge [45.5152,-122.6784], end 38.722,-9.139.'; + final parsed = CoordinateParser.parse(text); + expect(parsed, hasLength(3)); + expect(parsed[0].rawText, '37.7749, -122.4194'); + expect(text.substring(parsed[0].start, parsed[0].end), parsed[0].rawText); + expect(parsed[1].rawText, '45.5152,-122.6784'); + expect(text.substring(parsed[1].start, parsed[1].end), parsed[1].rawText); + expect(parsed[2].rawText, '38.722,-9.139'); + expect(text.substring(parsed[2].start, parsed[2].end), parsed[2].rawText); + }); + + test('parses multiple coordinates and #wardriving messages', () { + const wardriving = + '#wardriving 37.7749,-122.4194 SNR: 8.5dB -> (37.7812, -122.4111) ' + 'and 38.722,-9.139, 51.5074, -0.1278'; + final parsed = CoordinateParser.parse(wardriving); + expect(parsed, hasLength(4)); + expect(parsed.map((c) => c.rawText).toList(), [ + '37.7749,-122.4194', + '37.7812, -122.4111', + '38.722,-9.139', + '51.5074, -0.1278', + ]); + }); + + test('does not misparse coordinates inside URLs or emails', () { + const urlOnly = [ + 'https://maps.google.com/?q=37.7749,-122.4194', + 'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194', + 'https://example.com/@37.7749,-122.4194,15z', + 'geo:37.7749,-122.4194', + 'maps.google.com/?q=37.7749,-122.4194', + ]; + for (final text in urlOnly) { + expect( + CoordinateParser.parse(text), + isEmpty, + reason: 'Should not parse coordinate inside "$text"', + ); + } + + const mixed = + 'Route https://maps.google.com/?q=10.0,20.0 meet at 37.7749, -122.4194'; + final parsed = CoordinateParser.parse(mixed); + expect(parsed, hasLength(1)); + expect(parsed.first.rawText, '37.7749, -122.4194'); + + final elements = CoordinateParser.linkifyWithCoordinates(mixed); + expect(elements.whereType(), hasLength(1)); + expect(elements.whereType(), hasLength(1)); + }); + }); + + group('buildExternalMapUri', () { + test('builds platform-appropriate map URIs', () { + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.android, + isWeb: false, + ).toString(), + 'geo:37.7749,-122.4194?q=37.7749,-122.4194', + ); + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.iOS, + isWeb: false, + ).toString(), + 'https://maps.apple.com/?ll=37.7749,-122.4194&q=37.7749,-122.4194', + ); + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.macOS, + isWeb: false, + ).toString(), + 'https://maps.apple.com/?ll=37.7749,-122.4194&q=37.7749,-122.4194', + ); + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.linux, + isWeb: false, + ).toString(), + 'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194', + ); + expect( + buildExternalMapUri( + 37.7749, + -122.4194, + platform: TargetPlatform.windows, + isWeb: false, + ).toString(), + 'https://www.openstreetmap.org/?mlat=37.7749&mlon=-122.4194#map=16/37.7749/-122.4194', + ); + expect( + buildExternalMapUri(-0.0, -0.0, isWeb: true).toString(), + 'https://www.openstreetmap.org/?mlat=0.0&mlon=0.0#map=16/0.0/0.0', + ); + }); + }); +} diff --git a/test/screens/coordinate_messages_test.dart b/test/screens/coordinate_messages_test.dart new file mode 100644 index 00000000..2d5958ef --- /dev/null +++ b/test/screens/coordinate_messages_test.dart @@ -0,0 +1,484 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/custom_theme.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/screens/coordinate_map_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/utils/platform_info.dart'; + +final _l10n = lookupAppLocalizations(const Locale('en')); + +(MeshCoreConnector, List)? _shared; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync( + 'coordinate_messages_test', + ); + String? copiedText; + final launchedUrls = []; + + setUpAll(() async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') { + copiedText = + (call.arguments as Map)['text'] as String?; + } + return null; + }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/url_launcher'), + (call) async { + if (call.method == 'launch' || call.method == 'launchUrl') { + final args = call.arguments as Map; + launchedUrls.add(args['url'] as String); + return true; + } + if (call.method == 'canLaunch') { + return true; + } + return true; + }, + ); + + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDownAll(() { + _shared = null; + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + }); + + setUp(() { + copiedText = null; + launchedUrls.clear(); + }); + + /// Finds the global center of the first substring matching [target] inside + /// a [RenderParagraph] (mobile) or [RenderEditable] (desktop). + Offset findSpanOffset(WidgetTester tester, String target) { + for (final render in tester.renderObjectList( + find.byType(RichText), + )) { + final plain = render.text.toPlainText(); + final idx = plain.indexOf(target); + if (idx < 0) continue; + final boxes = render.getBoxesForSelection( + TextSelection(baseOffset: idx, extentOffset: idx + target.length), + ); + if (boxes.isNotEmpty) { + final localCenter = boxes.first.toRect().center; + return render.localToGlobal(localCenter); + } + } + for (final state in tester.stateList( + find.byType(EditableText), + )) { + final editable = state.renderEditable; + final plain = editable.plainText; + final idx = plain.indexOf(target); + if (idx < 0) continue; + final boxes = editable.getEndpointsForSelection( + TextSelection(baseOffset: idx, extentOffset: idx + target.length), + ); + if (boxes.isNotEmpty) { + final first = boxes.first.point; + final last = boxes.last.point; + final localCenter = Offset((first.dx + last.dx) / 2, first.dy - 6); + return editable.localToGlobal(localCenter); + } + } + fail('Could not locate rendered span for "$target"'); + } + + for (final isDesktop in [false, true]) { + final platformLabel = isDesktop ? 'desktop' : 'phone'; + + testWidgets( + 'DM message with URL and coordinate: tap opens map, Back preserves scroll, ' + 'long-press shows menu, non-coordinate gestures preserved ($platformLabel)', + (tester) async { + PlatformInfo.debugIsDesktopOverride = isDesktop; + addTearDown(() => PlatformInfo.debugIsDesktopOverride = null); + + final (connector, providers) = _shared ??= await _connect(tester); + final contact = connector.contacts.firstWhere( + (c) => c.type == advTypeChat, + ); + final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + const coord = '37.7749, -122.4194'; + const url = 'https://example.com/trail'; + const messageText = 'Check $url and meet at $coord soon'; + + await tester.runAsync(() async { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: messageText, + timestampSecs: nowSecs - 60, + ), + ); + for (var i = 0; i < 18; i++) { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: 'Filler message #$i', + timestampSecs: nowSecs - 30 + i, + ), + ); + } + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: 'Reply sent at 45.5152, -122.6784', + timestampSecs: nowSecs, + ), + ); + await Future.delayed(const Duration(milliseconds: 50)); + }); + + await _pumpApp(tester, providers, ChatScreen(contact: contact)); + + final scrollable = tester.widget( + find.byType(Scrollable).first, + ); + final controller = scrollable.controller!; + final targetFinder = find.textContaining(coord, findRichText: true); + if (targetFinder.evaluate().isEmpty) { + await tester.dragUntilVisible( + targetFinder, + find.byType(Scrollable).first, + const Offset(0, 200), + maxIteration: 30, + ); + } + await Scrollable.ensureVisible( + tester.element(targetFinder.first), + alignment: 0.5, + ); + await _settle(tester); + final savedOffset = controller.offset; + expect(savedOffset, greaterThan(0)); + + // 1. Tap coordinate -> opens CoordinateMapScreen with pin + label + centered AppBar. + final coordCenter = findSpanOffset(tester, coord); + await tester.tapAt(coordCenter); + await _settle(tester); + + expect(find.byType(CoordinateMapScreen), findsOneWidget); + expect(find.text(coord), findsOneWidget); + final appBar = tester.widget(find.byType(AppBar)); + expect(appBar.centerTitle, isTrue); + final flutterMap = tester.widget(find.byType(FlutterMap)); + expect( + flutterMap.options.initialCenter.latitude, + closeTo(37.7749, 1e-6), + ); + expect( + flutterMap.options.initialCenter.longitude, + closeTo(-122.4194, 1e-6), + ); + expect(find.byIcon(Icons.location_on), findsOneWidget); + + // 2. Pressing Back returns to exact same chat and scroll position. + await tester.pageBack(); + await _settle(tester); + expect(find.byType(CoordinateMapScreen), findsNothing); + expect(find.byType(ChatScreen), findsOneWidget); + expect(controller.offset, closeTo(savedOffset, 1.0)); + + // 3. Long-press coordinate -> opens Copy & Open in maps sheet (NOT bubble menu). + await tester.longPressAt(findSpanOffset(tester, coord)); + await _settle(tester); + expect(find.text(_l10n.coordinate_copyLocation), findsOneWidget); + expect(find.text(_l10n.coordinate_openInMaps), findsOneWidget); + expect(find.text(_l10n.chat_reply), findsNothing); + + // Copy location writes to clipboard and shows snackbar. + await tester.tap(find.text(_l10n.coordinate_copyLocation)); + await _settle(tester); + expect(copiedText, coord); + expect(find.text(_l10n.coordinate_copied), findsOneWidget); + + // Re-open long-press sheet and tap Open in maps. + await tester.longPressAt(findSpanOffset(tester, coord)); + await _settle(tester); + await tester.tap(find.text(_l10n.coordinate_openInMaps)); + await _settle(tester); + expect(launchedUrls, isNotEmpty); + expect(launchedUrls.last, contains('37.7749')); + expect(launchedUrls.last, contains('-122.4194')); + + // 4. Tapping URL still opens existing URL confirmation dialog. + await tester.tapAt(findSpanOffset(tester, url)); + await _settle(tester); + expect(find.text(_l10n.chat_openLink), findsOneWidget); + await tester.tap(find.text(_l10n.common_cancel)); + await _settle(tester); + + // 5. Long-pressing non-coordinate text in same message opens bubble actions. + if (!isDesktop) { + await tester.longPressAt(findSpanOffset(tester, 'Check')); + await _settle(tester); + expect(find.text(_l10n.chat_addReaction), findsOneWidget); + Navigator.of(tester.element(find.text(_l10n.chat_addReaction))).pop(); + await _settle(tester); + } + + await _tearDown(tester); + }, + ); + } + + testWidgets( + 'Channel messages render coordinates, support tap/long-press, and fit 320dp @ 1.3x & 2.0x', + (tester) async { + PlatformInfo.debugIsDesktopOverride = false; + addTearDown(() => PlatformInfo.debugIsDesktopOverride = null); + + final (connector, providers) = _shared ??= await _connect(tester); + final channel = connector.channels.first; + final nowSecs = DateTime.now().millisecondsSinceEpoch ~/ 1000; + + const channelCoord = '-33.86882, 151.20929'; + const channelMsg = + '#wardriving https://meshcore.co.uk at ($channelCoord) SNR 7.5dB'; + + await tester.runAsync(() async { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Maya', + message: channelMsg, + timestampSecs: nowSecs - 30, + ), + ); + await Future.delayed(const Duration(milliseconds: 50)); + }); + + final customTheme = MeshTheme.fromCustom( + CustomTheme( + id: 'test-forest', + name: 'Forest', + background: const Color(0xFF0E1A13), + accent: const Color(0xFF4ADE80), + ), + ); + + for (final scale in [1.3, 2.0]) { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final overflows = []; + final previousError = FlutterError.onError; + FlutterError.onError = (details) { + final text = details.exceptionAsString(); + if (text.contains('overflowed')) { + overflows.add(text.split('\n').first); + } else { + previousError?.call(details); + } + }; + addTearDown(() => FlutterError.onError = previousError); + + await _pumpApp( + tester, + providers, + ChannelChatScreen(channel: channel), + theme: customTheme, + textScaler: TextScaler.linear(scale), + ); + + final coordFinder = find.textContaining( + channelCoord, + findRichText: true, + ); + if (coordFinder.evaluate().isEmpty) { + await tester.dragUntilVisible( + coordFinder, + find.byType(Scrollable).first, + const Offset(0, 200), + maxIteration: 30, + ); + } + await Scrollable.ensureVisible( + tester.element(coordFinder.first), + alignment: 0.5, + ); + await _settle(tester); + + // Long-press coordinate in channel message -> bottom sheet fits 320dp without overflow. + await tester.longPressAt(findSpanOffset(tester, channelCoord)); + await _settle(tester); + expect(find.text(_l10n.coordinate_copyLocation), findsOneWidget); + expect(find.text(_l10n.coordinate_openInMaps), findsOneWidget); + Navigator.of( + tester.element(find.text(_l10n.coordinate_copyLocation)), + ).pop(); + await _settle(tester); + + // Tap coordinate -> CoordinateMapScreen fits 320dp without overflow. + await tester.tapAt(findSpanOffset(tester, channelCoord)); + await _settle(tester); + expect(find.byType(CoordinateMapScreen), findsOneWidget); + + // Verify 48dp touch targets on CoordinateMapScreen controls & AppBar buttons. + for (final iconButton in tester.widgetList( + find.byType(IconButton), + )) { + final box = tester.renderObject(find.byWidget(iconButton)); + expect(box.size.width, greaterThanOrEqualTo(48)); + expect(box.size.height, greaterThanOrEqualTo(48)); + } + + await tester.pageBack(); + await _settle(tester); + FlutterError.onError = previousError; + expect(overflows, isEmpty); + } + + await _tearDown(tester); + }, + ); +} + +Future _pumpApp( + WidgetTester tester, + List providers, + Widget home, { + ThemeData? theme, + TextScaler textScaler = TextScaler.noScaling, +}) async { + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: theme ?? MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child!, + ), + home: home, + ), + ), + ); + await _settle(tester); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((connector.contacts.isEmpty || + connector.channels.isEmpty || + !connector.channelMapConfirmed) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} diff --git a/test/screens/small_screen_layout_test.dart b/test/screens/small_screen_layout_test.dart index 1d4e40d9..e85b541e 100644 --- a/test/screens/small_screen_layout_test.dart +++ b/test/screens/small_screen_layout_test.dart @@ -26,6 +26,7 @@ import 'package:meshcore_open/screens/chat_screen.dart'; import 'package:meshcore_open/screens/chrome_required_screen.dart'; import 'package:meshcore_open/screens/companion_radio_stats_screen.dart'; import 'package:meshcore_open/screens/contacts_screen.dart'; +import 'package:meshcore_open/screens/coordinate_map_screen.dart'; import 'package:meshcore_open/screens/discovery_screen.dart'; import 'package:meshcore_open/screens/line_of_sight_map_screen.dart'; import 'package:meshcore_open/screens/map_cache_screen.dart'; @@ -223,6 +224,11 @@ final Map _screens = { LineOfSightEndpoint(label: 'B', point: LatLng(45.6, -122.7)), ], ), + 'CoordinateMap': (_) => const CoordinateMapScreen( + latitude: 45.515232, + longitude: -122.678385, + label: '45.515232, -122.678385', + ), }; void main() { diff --git a/test/widgets/translated_message_content_test.dart b/test/widgets/translated_message_content_test.dart index 118a194e..4af6feb4 100644 --- a/test/widgets/translated_message_content_test.dart +++ b/test/widgets/translated_message_content_test.dart @@ -1,16 +1,23 @@ import 'package:flutter/material.dart'; -import 'package:flutter_linkify/flutter_linkify.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/link_handler.dart'; +import 'package:meshcore_open/models/custom_theme.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/mesh_ui.dart'; +import 'package:meshcore_open/widgets/message_bubble_frame.dart'; import 'package:meshcore_open/widgets/translated_message_content.dart'; -double _renderedScaleFactor(WidgetTester tester) { - final linkify = find.byType(Linkify); - if (linkify.evaluate().isNotEmpty) { - return tester.widget(linkify.first).textScaleFactor; - } +List _renderedScaleFactors(WidgetTester tester) { + final editables = tester + .stateList(find.byType(EditableText)) + .map((s) => s.renderEditable.textScaler.scale(16) / 16) + .toList(); + if (editables.isNotEmpty) return editables; return tester - .widget(find.byType(SelectableLinkify).first) - .textScaleFactor; + .renderObjectList(find.byType(RichText)) + .map((p) => p.textScaler.scale(16) / 16) + .toList(); } Future _pump(WidgetTester tester, TextScaler scaler) { @@ -20,7 +27,7 @@ Future _pump(WidgetTester tester, TextScaler scaler) { data: MediaQueryData(textScaler: scaler), child: const Scaffold( body: TranslatedMessageContent( - displayText: 'hello https://example.com', + displayText: 'hello https://example.com at 37.7749, -122.4194', originalText: 'bonjour', style: TextStyle(fontSize: 16), ), @@ -33,23 +40,62 @@ Future _pump(WidgetTester tester, TextScaler scaler) { void main() { testWidgets('message body follows the system text scale', (tester) async { await _pump(tester, TextScaler.noScaling); - expect(_renderedScaleFactor(tester), 1.0); + expect(_renderedScaleFactors(tester), everyElement(1.0)); await _pump(tester, const TextScaler.linear(2)); - expect(_renderedScaleFactor(tester), 2.0); + expect(_renderedScaleFactors(tester), everyElement(2.0)); }); testWidgets('original and translated text both scale', (tester) async { await _pump(tester, const TextScaler.linear(1.5)); - final factors = [ - ...tester - .widgetList(find.byType(Linkify)) - .map((w) => w.textScaleFactor), - ...tester - .widgetList(find.byType(SelectableLinkify)) - .map((w) => w.textScaleFactor), - ]; + final factors = _renderedScaleFactors(tester); expect(factors, hasLength(2)); expect(factors, everyElement(1.5)); }); + + testWidgets( + 'coordinate style meets WCAG AA contrast across light, dark, and custom themes', + (tester) async { + final customForest = CustomTheme( + id: 'forest', + name: 'Forest', + background: const Color(0xFF0E1A13), + accent: const Color(0xFF4ADE80), + ); + final themes = [ + MeshTheme.light(), + MeshTheme.dark(), + MeshTheme.fromCustom(customForest), + ]; + + for (final theme in themes) { + for (final isOutgoing in [false, true]) { + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Builder( + builder: (context) { + final colors = MessageBubbleColors.of( + context, + isOutgoing: isOutgoing, + ); + final coordStyle = LinkHandler.defaultCoordinateStyle( + context, + TextStyle(color: colors.text, fontSize: 14), + backgroundColor: colors.background, + ); + expect(coordStyle.decoration, TextDecoration.underline); + expect( + meshContrastRatio(coordStyle.color!, colors.background), + greaterThanOrEqualTo(4.5), + ); + return const SizedBox.shrink(); + }, + ), + ), + ); + } + } + }, + ); } diff --git a/untranslated.json b/untranslated.json index 943fa85a..c7d4d570 100644 --- a/untranslated.json +++ b/untranslated.json @@ -51,7 +51,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "cs": [ @@ -106,7 +110,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "de": [ @@ -161,7 +169,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "es": [ @@ -216,7 +228,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "fr": [ @@ -271,7 +287,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "hu": [ @@ -326,7 +346,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "it": [ @@ -381,7 +405,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "ja": [ @@ -436,7 +464,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "ko": [ @@ -491,7 +523,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "nl": [ @@ -546,7 +582,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "pl": [ @@ -601,7 +641,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "pt": [ @@ -656,7 +700,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "pt_PT": [ @@ -711,7 +759,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "ru": [ @@ -766,7 +818,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "sk": [ @@ -821,7 +877,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "sl": [ @@ -876,7 +936,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "sv": [ @@ -931,7 +995,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "uk": [ @@ -986,7 +1054,11 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ], "zh": [ @@ -1041,6 +1113,10 @@ "addContact_publicKeyInvalid", "addContact_clipboardKeyLoaded", "addContact_fromDiscovered", - "addContact_saveFailed" + "addContact_saveFailed", + "coordinateMap_title", + "coordinate_copyLocation", + "coordinate_openInMaps", + "coordinate_copied" ] } From 11345d3bba9a4e988949f1d131c0b04544c3d183 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:14:33 -0700 Subject: [PATCH 2/2] Preserve link recognizers across rebuilds and document coordinates --- documentation/channels.md | 4 +- documentation/chat-and-messaging.md | 34 ++++- documentation/map-and-location.md | 6 +- lib/helpers/link_handler.dart | 69 +++++---- test/screens/coordinate_messages_test.dart | 165 +++++++++++++++++++++ 5 files changed, 242 insertions(+), 36 deletions(-) diff --git a/documentation/channels.md b/documentation/channels.md index bc6994f7..6f324f7d 100644 --- a/documentation/channels.md +++ b/documentation/channels.md @@ -101,7 +101,7 @@ Messages also show a region label when known, independently of message tracing. ### Message Types in Chat -- **Plain text** with linkified URLs +- **Plain text** with linkified URLs and interactive decimal GPS coordinates (tap to open the **Location** map, long-press for **Copy location** / **Open in maps**; see [Inline GPS Coordinates](chat-and-messaging.md#inline-gps-coordinates)) - **GIFs** (`g:{gifId}`) rendered inline via Giphy CDN - **Location pins** (`m:{lat},{lon}|{label}|`) shown as tappable location cards - **Mesh images** sent as GRP_DATA chunks and reconstructed locally ([setup and limitations](image-messages.md)) @@ -144,6 +144,8 @@ Where your radio only hears nearby repeaters, turn on **Also count different nea | Mark as Unread | Incoming messages only | Marks this message and all subsequent incoming messages as unread | | Delete | All messages | Removes locally (not from mesh) | +Long-pressing directly on a detected GPS coordinate opens the coordinate action sheet (**Copy location** and **Open in maps**) instead of this message menu; long-press non-coordinate text in the message (or right-click on desktop) for channel message actions. + ## Communities Communities are a layer above channels that provide a private namespace. diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 175eaabb..40826682 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -35,7 +35,7 @@ Below the app bar, above the messages, a strip shows **Compression: Off**, **SMA - **Incoming messages**: Left-aligned, grey background with a colored avatar (initial letter or first emoji of sender name; color is deterministic from a hash of the sender name) - Long-press a message and choose **Bookmark** to show a yellow bookmark on the bubble. **Show bookmarks** in the chat menu toggles a filter for bookmarked messages; use **Bookmarks** in the Channels screen menu to browse saved messages, including those from deleted contacts or channels. From the bookmarks list, copy a message with its copy button. It is ordered oldest-to-newest and opens at the newest message. The Export screen can save or share a dated Markdown file, grouped by contact and then channel, with linked URLs and URL-image embeds. Links remain tappable, and supported URL-image previews are shown when **Load images from links** is enabled in App Settings. - Bubble width capped at 72% of screen width -- Hyperlinks rendered as tappable green underlined text +- Hyperlinks rendered as tappable underlined text; inline decimal GPS coordinates are rendered as bold underlined links (see [Inline GPS Coordinates](#inline-gps-coordinates)) - Message text follows the system font size (Android/iOS accessibility text size); pinch-to-zoom scales on top of it - **Pinch-to-zoom**: Two-finger zoom (0.8x–1.8x) and double-tap to reset - **Jump to bottom**: Floating button appears when scrolled away from the bottom @@ -61,12 +61,40 @@ The composer is a rounded bubble at the bottom of the chat with one round button | Type | Wire Format | Display | |---|---|---| -| Plain text | Raw UTF-8 string | Inline text with link detection | +| Plain text | Raw UTF-8 string | Inline text with URL and decimal coordinate detection | | URL image preview | Image URL in text (per-contact opt-in; requires internet) | Downloaded inline preview | | GIF | `g:` | Inline GIF image from Giphy CDN | | Location pin | `m:,\|