diff --git a/documentation/settings.md b/documentation/settings.md index 91b2af5e..9600dd14 100644 --- a/documentation/settings.md +++ b/documentation/settings.md @@ -127,6 +127,7 @@ Individual channels can be muted from the channel chat bell icon, the channel li - **Reset Routing Algorithm to Default**: Restores the routing settings to their factory defaults - **Enable Message Tracing**: Shows path trace overlays and extra metadata on messages - **Region next to hop count** (default off): Shows a channel message's region chip on the same line as its hop count instead of below it +- **Compression indicator** (default off): Shows an icon on direct and channel messages that were compressed with SMAZ - **Resend channel messages until they travel far enough** (default off): If your channel message isn't heard coming back through enough repeaters, it's sent again. Uses more airtime. When on, it shows: - Required hops (1–8, default 2) - Resend up to (1–5 times, default 1) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 1b671f77..5df949aa 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5171,9 +5171,8 @@ class MeshCoreConnector extends ChangeNotifier { }) async { if (!isConnected || text.isEmpty) return; - final outboundBytes = utf8.encode( - prepareContactOutboundText(contact, text), - ); + final prepared = prepareContactOutbound(contact, text); + final outboundBytes = utf8.encode(prepared.text); if (outboundBytes.length > maxTextPayloadBytes) { debugPrint( 'sendMessage: dropping overlong message ' @@ -5222,6 +5221,7 @@ class MeshCoreConnector extends ChangeNotifier { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + isSmazCompressed: prepared.isSmazCompressed, ); } else { // Fallback to old behavior if retry service not initialized @@ -5234,11 +5234,11 @@ class MeshCoreConnector extends ChangeNotifier { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + isSmazCompressed: prepared.isSmazCompressed, ); _addMessage(contact.publicKeyHex, message); // recipient as "sender" notifyListeners(); - final outboundText = prepareContactOutboundText(contact, text); - await sendFrame(buildSendTextMsgFrame(contact.publicKey, outboundText)); + await sendFrame(buildSendTextMsgFrame(contact.publicKey, prepared.text)); } } @@ -5661,6 +5661,7 @@ class MeshCoreConnector extends ChangeNotifier { // we continue to process it normally. } + final prepared = prepareChannelOutbound(channel.index, text); final message = ChannelMessage.outgoing( text, _selfName ?? 'Me', @@ -5670,12 +5671,13 @@ class MeshCoreConnector extends ChangeNotifier { translationModelId: translationModelId, region: sendRegion, replyTo: replyTo, + isSmazCompressed: prepared.isSmazCompressed, ); _addChannelMessage(channel.index, message); _pendingChannelSentQueue.add(message.messageId); notifyListeners(); - final outboundText = prepareChannelOutboundText(channel.index, text); + final outboundText = prepared.text; // Resends reuse the timestamp, so they are the same packet: repeaters // that already forwarded it drop the copy and recipients see it once. Future transmit({bool isResend = false}) => @@ -8333,9 +8335,8 @@ class MeshCoreConnector extends ChangeNotifier { appLogger.warn('Received message with empty text, ignoring'); return null; } - final decodedText = isCli - ? msgText - : (Smaz.tryDecodePrefixed(msgText) ?? msgText); + final smazDecoded = isCli ? null : Smaz.tryDecodePrefixed(msgText); + final decodedText = smazDecoded ?? msgText; final contact = _contacts.cast().firstWhere( (c) => c != null && _matchesPrefix(c.publicKey, senderPrefix), @@ -8355,6 +8356,7 @@ class MeshCoreConnector extends ChangeNotifier { receivedAt: DateTime.now(), isOutgoing: false, isCli: isCli, + isSmazCompressed: smazDecoded != null, status: MessageStatus.delivered, pathLength: pathLength == 0xFF ? null : (pathLength & 0x3F), pathBytes: Uint8List(0), @@ -8484,7 +8486,13 @@ class MeshCoreConnector extends ChangeNotifier { /// Prepares contact outbound text by applying SMAZ encoding if enabled. /// This should be used to transform text before computing ACK hashes. - String prepareContactOutboundText(Contact contact, String text) { + String prepareContactOutboundText(Contact contact, String text) => + prepareContactOutbound(contact, text).text; + + ({String text, bool isSmazCompressed}) prepareContactOutbound( + Contact contact, + String text, + ) { final trimmed = text.trim(); final isStructuredPayload = trimmed.startsWith('g:') || @@ -8492,7 +8500,8 @@ class MeshCoreConnector extends ChangeNotifier { trimmed.startsWith('V1|'); if (!isStructuredPayload) { if (isContactSmazEnabled(contact.publicKeyHex)) { - return Smaz.encodeIfSmaller(text); + final encoded = Smaz.encodeIfSmaller(text); + return (text: encoded, isSmazCompressed: encoded != text); } else if (isContactCyr2LatEnabled(contact.publicKeyHex)) { final profileId = getContactCyr2LatProfileId(contact.publicKeyHex); final profile = profileId != null && _appSettingsService != null @@ -8508,19 +8517,26 @@ class MeshCoreConnector extends ChangeNotifier { Cyr2Lat.setCharMap(globalProfile.charMap); } } - return Cyr2Lat.encode(text); + return (text: Cyr2Lat.encode(text), isSmazCompressed: false); } } - return text; + return (text: text, isSmazCompressed: false); } - String prepareChannelOutboundText(int channelIndex, String text) { + String prepareChannelOutboundText(int channelIndex, String text) => + prepareChannelOutbound(channelIndex, text).text; + + ({String text, bool isSmazCompressed}) prepareChannelOutbound( + int channelIndex, + String text, + ) { final trimmed = text.trim(); final isStructuredPayload = trimmed.startsWith('g:') || trimmed.startsWith('m:'); if (!isStructuredPayload) { if (isChannelSmazEnabled(channelIndex)) { - return Smaz.encodeIfSmaller(text); + final encoded = Smaz.encodeIfSmaller(text); + return (text: encoded, isSmazCompressed: encoded != text); } else if (isChannelCyr2LatEnabled(channelIndex)) { final profileId = getChannelCyr2LatProfileId(channelIndex); final profile = profileId != null && _appSettingsService != null @@ -8536,10 +8552,10 @@ class MeshCoreConnector extends ChangeNotifier { Cyr2Lat.setCharMap(globalProfile.charMap); } } - return Cyr2Lat.encode(text); + return (text: Cyr2Lat.encode(text), isSmazCompressed: false); } } - return text; + return (text: text, isSmazCompressed: false); } // Falls back to the cached channel list, which stays populated while a @@ -8727,8 +8743,8 @@ class MeshCoreConnector extends ChangeNotifier { final text = decrypted.readCString(); final parsed = _splitSenderText(text); - final decodedText = - Smaz.tryDecodePrefixed(parsed.text) ?? parsed.text; + final smazDecoded = Smaz.tryDecodePrefixed(parsed.text); + final decodedText = smazDecoded ?? parsed.text; if (_shouldDropSelfChannelMessage( parsed.senderName, packet.pathBytes, @@ -8758,6 +8774,7 @@ class MeshCoreConnector extends ChangeNotifier { timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), receivedAt: DateTime.now(), isOutgoing: false, + isSmazCompressed: smazDecoded != null, status: ChannelMessageStatus.sent, pathLength: packet.isFlood ? packet.hopCount : 0, pathHashWidth: packet.pathHashWidth, @@ -9572,6 +9589,7 @@ class MeshCoreConnector extends ChangeNotifier { timestamp: message.timestamp, receivedAt: message.receivedAt, isOutgoing: message.isOutgoing, + isSmazCompressed: message.isSmazCompressed, status: message.status, repeats: message.repeats, repeatCount: message.repeatCount, @@ -9620,6 +9638,8 @@ class MeshCoreConnector extends ChangeNotifier { existing.status == ChannelMessageStatus.pending; messages[existingIndex] = existing.copyWith( repeatCount: newRepeatCount, + isSmazCompressed: + existing.isSmazCompressed || processedMessage.isSmazCompressed, pathLength: mergedPathLength, pathHashWidth: existing.pathHashWidth ?? processedMessage.pathHashWidth, pathBytes: mergedPathBytes, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 309e0f38..10861b8a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -601,6 +601,8 @@ "appSettings_enableMessageTracingSubtitle": "Also show repeat counts and trip times. Long-press a message and choose Path for full details.", "appSettings_regionOnHopsLine": "Region next to hop count", "appSettings_regionOnHopsLineSubtitle": "Show a channel message's region on the same line as its hop count instead of below it.", + "appSettings_showCompressionIndicator": "Compression indicator", + "appSettings_showCompressionIndicatorSubtitle": "Show an icon on messages compressed with SMAZ.", "appSettings_notifications": "Notifications", "appSettings_enableNotifications": "Enable Notifications", "appSettings_enableNotificationsSubtitle": "Receive notifications for messages and adverts", @@ -4359,5 +4361,6 @@ "chatCompression_cyr2latDescription": "Not lossless. Swaps some Cyrillic letters for lookalike Latin ones (А→A, З→3) to save bytes. Readable in any app with no decoding, but the exact characters change, including your own sent messages here. Copying, search and technical text may be affected. Results depend on the chosen profile.", "chatCompression_profile": "Cyr2Lat profile", "chatCompression_noStorageId": "Can't change compression until this channel has synced from the radio.", - "chatCompression_saveFailed": "Couldn't save the compression setting. Showing the saved setting." + "chatCompression_saveFailed": "Couldn't save the compression setting. Showing the saved setting.", + "messageMeta_smazCompressed": "SMAZ compressed" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index d8cd16a7..fece5be6 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2533,6 +2533,18 @@ abstract class AppLocalizations { /// **'Show a channel message\'s region on the same line as its hop count instead of below it.'** String get appSettings_regionOnHopsLineSubtitle; + /// No description provided for @appSettings_showCompressionIndicator. + /// + /// In en, this message translates to: + /// **'Compression indicator'** + String get appSettings_showCompressionIndicator; + + /// No description provided for @appSettings_showCompressionIndicatorSubtitle. + /// + /// In en, this message translates to: + /// **'Show an icon on messages compressed with SMAZ.'** + String get appSettings_showCompressionIndicatorSubtitle; + /// No description provided for @appSettings_notifications. /// /// In en, this message translates to: @@ -12693,6 +12705,12 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Couldn\'t save the compression setting. Showing the saved setting.'** String get chatCompression_saveFailed; + + /// No description provided for @messageMeta_smazCompressed. + /// + /// In en, this message translates to: + /// **'SMAZ compressed'** + String get messageMeta_smazCompressed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 9137083e..1a6d1a16 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1385,6 +1386,13 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Показвай региона на съобщението в канала на същия ред като броя хопове, а не под него.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Уведомления'; @@ -7618,4 +7626,7 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 7cdca68f..4dbc6eae 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1376,6 +1377,13 @@ class AppLocalizationsCs extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Zobrazit region zprávy kanálu na stejném řádku jako počet skoků místo pod ním.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Oznámení'; @@ -7589,4 +7597,7 @@ class AppLocalizationsCs extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index e0a989f5..7c6d745a 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1384,6 +1385,13 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Die Region einer Kanalnachricht in derselben Zeile wie die Hop-Anzahl anzeigen statt darunter.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Benachrichtigungen'; @@ -7633,4 +7641,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index fcf4103f..3b1b58fb 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1359,6 +1360,13 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Show a channel message\'s region on the same line as its hop count instead of below it.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notifications'; @@ -7505,4 +7513,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index bbb587a3..d48cca85 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1377,6 +1378,13 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Mostrar la región de un mensaje de canal en la misma línea que su número de saltos en lugar de debajo.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notificaciones'; @@ -7610,4 +7618,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index b5d3dd70..c6e838ba 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1383,6 +1384,13 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Afficher la région d\'un message de canal sur la même ligne que son nombre de sauts plutôt qu\'en dessous.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notifications'; @@ -7638,4 +7646,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 2fa18998..9e7624f3 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1376,6 +1377,13 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'A csatornaüzenet régiója az ugrásszámmal azonos sorban jelenik meg, nem alatta.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Értesítések'; @@ -7602,4 +7610,7 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index d3d64ae8..c1ff0afa 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1381,6 +1382,13 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Mostra la regione di un messaggio di canale sulla stessa riga del numero di salti invece che sotto.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notifiche'; @@ -7622,4 +7630,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index eab41908..8558cc9b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1316,6 +1317,13 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'チャンネルメッセージの地域を、ホップ数の下ではなく同じ行に表示します。'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => '通知'; @@ -7265,4 +7273,7 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 972fb14b..7f995d8f 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1319,6 +1320,13 @@ class AppLocalizationsKo extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => '채널 메시지의 지역을 홉 수 아래가 아닌 같은 줄에 표시합니다.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => '알림'; @@ -7278,4 +7286,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 63a93b81..e9990b6a 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1374,6 +1375,13 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Toon de regio van een kanaalbericht op dezelfde regel als het aantal hops in plaats van eronder.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notificaties'; @@ -7578,4 +7586,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index db206b72..50091540 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1387,6 +1388,13 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Pokaż region wiadomości kanału w tym samym wierszu co liczba hopów, zamiast pod nią.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Powiadomienia'; @@ -7656,4 +7664,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 8d001c90..6ed1cc4d 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1380,6 +1381,13 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Mostra a região de uma mensagem de canal na mesma linha da contagem de saltos, em vez de abaixo dela.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notificações'; @@ -7600,6 +7608,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } /// 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 cd25ee72..f3b1fc1d 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1379,6 +1380,13 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Показывать регион сообщения канала в одной строке с числом хопов, а не под ней.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Уведомления'; @@ -7636,4 +7644,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index eec52038..b421b418 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1374,6 +1375,13 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Zobraziť región správy kanála v rovnakom riadku ako počet skokov namiesto pod ním.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Upozornenia'; @@ -7601,4 +7609,7 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 700c7bb3..fdfee515 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1373,6 +1374,13 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Regijo sporočila kanala prikaži v isti vrstici kot število skokov, ne pod njim.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Obvestila'; @@ -7595,4 +7603,7 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 80813df9..f2ea9363 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1364,6 +1365,13 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Visa ett kanalmeddelandes region på samma rad som dess hoppantal i stället för under det.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Notifieringar'; @@ -7555,4 +7563,7 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index eccf45ef..2073194f 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1375,6 +1376,13 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => 'Показувати регіон повідомлення каналу в одному рядку з кількістю хопів, а не під ним.'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => 'Сповіщення'; @@ -7648,4 +7656,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 078822ce..b641b911 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1,5 +1,6 @@ // ignore: unused_import import 'package:intl/intl.dart' as intl; + import 'app_localizations.dart'; // ignore_for_file: type=lint @@ -1297,6 +1298,13 @@ class AppLocalizationsZh extends AppLocalizations { String get appSettings_regionOnHopsLineSubtitle => '将频道消息的地区与跳数显示在同一行,而不是在其下方。'; + @override + String get appSettings_showCompressionIndicator => 'Compression indicator'; + + @override + String get appSettings_showCompressionIndicatorSubtitle => + 'Show an icon on messages compressed with SMAZ.'; + @override String get appSettings_notifications => '通知'; @@ -7108,4 +7116,7 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chatCompression_saveFailed => 'Couldn\'t save the compression setting. Showing the saved setting.'; + + @override + String get messageMeta_smazCompressed => 'SMAZ compressed'; } diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 9b2b80b6..3b27ae72 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -120,6 +120,7 @@ class AppSettings { final bool mapClusterNodes; final bool enableMessageTracing; final bool regionOnHopsLine; + final bool showCompressionIndicator; final Map? mapCacheBounds; final int mapCacheMinZoom; final int mapCacheMaxZoom; @@ -274,6 +275,7 @@ class AppSettings { this.mapClusterNodes = true, this.enableMessageTracing = false, this.regionOnHopsLine = false, + this.showCompressionIndicator = false, this.mapCacheBounds, this.mapCacheMinZoom = 10, this.mapCacheMaxZoom = 15, @@ -371,6 +373,7 @@ class AppSettings { 'map_cluster_nodes': mapClusterNodes, 'enable_message_tracing': enableMessageTracing, 'region_on_hops_line': regionOnHopsLine, + 'show_compression_indicator': showCompressionIndicator, 'map_cache_bounds': mapCacheBounds, 'map_cache_min_zoom': mapCacheMinZoom, 'map_cache_max_zoom': mapCacheMaxZoom, @@ -508,6 +511,8 @@ class AppSettings { mapClusterNodes: json['map_cluster_nodes'] as bool? ?? true, enableMessageTracing: json['enable_message_tracing'] as bool? ?? false, regionOnHopsLine: json['region_on_hops_line'] as bool? ?? false, + showCompressionIndicator: + json['show_compression_indicator'] as bool? ?? false, mapCacheBounds: (json['map_cache_bounds'] as Map?)?.map( (key, value) => MapEntry(key.toString(), (value as num).toDouble()), ), @@ -681,6 +686,7 @@ class AppSettings { bool? mapClusterNodes, bool? enableMessageTracing, bool? regionOnHopsLine, + bool? showCompressionIndicator, Object? mapCacheBounds = _unset, int? mapCacheMinZoom, int? mapCacheMaxZoom, @@ -764,6 +770,8 @@ class AppSettings { mapClusterNodes: mapClusterNodes ?? this.mapClusterNodes, enableMessageTracing: enableMessageTracing ?? this.enableMessageTracing, regionOnHopsLine: regionOnHopsLine ?? this.regionOnHopsLine, + showCompressionIndicator: + showCompressionIndicator ?? this.showCompressionIndicator, mapCacheBounds: mapCacheBounds == _unset ? this.mapCacheBounds : mapCacheBounds as Map?, diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart index f3460138..861aa30a 100644 --- a/lib/models/channel_message.dart +++ b/lib/models/channel_message.dart @@ -1,4 +1,5 @@ import 'dart:typed_data'; + import '../connector/meshcore_protocol.dart'; import '../helpers/reaction_helper.dart'; import '../helpers/smaz.dart'; @@ -44,6 +45,7 @@ class ChannelMessage { final DateTime receivedAt; final bool isOutgoing; final bool isBookmarked; + final bool isSmazCompressed; final ChannelMessageStatus status; final List repeats; final int repeatCount; @@ -79,6 +81,7 @@ class ChannelMessage { DateTime? receivedAt, required this.isOutgoing, this.isBookmarked = false, + this.isSmazCompressed = false, this.status = ChannelMessageStatus.pending, this.repeats = const [], this.repeatCount = 0, @@ -120,6 +123,7 @@ class ChannelMessage { ChannelMessage copyWith({ ChannelMessageStatus? status, bool? isBookmarked, + bool? isSmazCompressed, List? repeats, int? repeatCount, int? pathLength, @@ -163,6 +167,7 @@ class ChannelMessage { receivedAt: receivedAt, isOutgoing: isOutgoing, isBookmarked: isBookmarked ?? this.isBookmarked, + isSmazCompressed: isSmazCompressed ?? this.isSmazCompressed, status: status ?? this.status, repeats: repeats ?? this.repeats, repeatCount: repeatCount ?? this.repeatCount, @@ -252,7 +257,8 @@ class ChannelMessage { } } - final decodedText = Smaz.tryDecodePrefixed(actualText) ?? actualText; + final smazDecoded = Smaz.tryDecodePrefixed(actualText); + final decodedText = smazDecoded ?? actualText; return ChannelMessage( senderKey: null, @@ -261,6 +267,7 @@ class ChannelMessage { timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), receivedAt: DateTime.now(), isOutgoing: false, + isSmazCompressed: smazDecoded != null, status: ChannelMessageStatus.sent, pathLength: pathLen, pathHashWidth: packetPathHashWidth, @@ -283,6 +290,7 @@ class ChannelMessage { String? translationModelId, String? region, ChannelMessage? replyTo, + bool isSmazCompressed = false, }) { return ChannelMessage( senderKey: null, @@ -296,6 +304,7 @@ class ChannelMessage { replyToText: replyTo?.text, timestamp: DateTime.now(), isOutgoing: true, + isSmazCompressed: isSmazCompressed, status: ChannelMessageStatus.pending, pathLength: null, pathBytes: Uint8List(0), diff --git a/lib/models/message.dart b/lib/models/message.dart index d180b33c..7aad608e 100644 --- a/lib/models/message.dart +++ b/lib/models/message.dart @@ -1,6 +1,8 @@ import 'dart:typed_data'; + import '../connector/meshcore_protocol.dart'; import '../helpers/reaction_helper.dart'; +import '../helpers/smaz.dart'; import 'translation_support.dart'; enum MessageStatus { pending, sent, delivered, failed } @@ -36,6 +38,7 @@ class Message { final bool isOutgoing; final bool isBookmarked; final bool isCli; + final bool isSmazCompressed; final MessageStatus status; final String? originalText; final String? translatedText; @@ -65,6 +68,7 @@ class Message { required this.isOutgoing, this.isBookmarked = false, this.isCli = false, + this.isSmazCompressed = false, this.status = MessageStatus.pending, String? messageId, this.originalText, @@ -110,6 +114,7 @@ class Message { int? pathLength, Uint8List? pathBytes, bool? isCli, + bool? isSmazCompressed, bool? isBookmarked, Object? originalText = _unset, Object? translatedText = _unset, @@ -128,6 +133,7 @@ class Message { isOutgoing: isOutgoing, isBookmarked: isBookmarked ?? this.isBookmarked, isCli: isCli ?? this.isCli, + isSmazCompressed: isSmazCompressed ?? this.isSmazCompressed, status: status ?? this.status, messageId: messageId, originalText: originalText == _unset @@ -173,7 +179,9 @@ class Message { if ((flags >> 2) != txtTypePlain) { return null; } - final text = reader.readCString(); + final rawText = reader.readCString(); + final smazDecoded = Smaz.tryDecodePrefixed(rawText); + final text = smazDecoded ?? rawText; return Message( senderKey: senderKey, @@ -182,6 +190,7 @@ class Message { receivedAt: DateTime.now(), isOutgoing: false, isCli: false, + isSmazCompressed: smazDecoded != null, status: MessageStatus.delivered, pathBytes: Uint8List(0), ); @@ -198,6 +207,7 @@ class Message { String? translationModelId, int? pathLength, Uint8List? pathBytes, + bool isSmazCompressed = false, }) { return Message( senderKey: recipientKey, @@ -208,6 +218,7 @@ class Message { timestamp: DateTime.now(), isOutgoing: true, isCli: false, + isSmazCompressed: isSmazCompressed, status: MessageStatus.pending, pathLength: pathLength, pathBytes: pathBytes, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 126216cb..aa749cd2 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -488,6 +488,20 @@ class AppSettingsScreen extends StatelessWidget { value: settingsService.settings.regionOnHopsLine, onChanged: settingsService.setRegionOnHopsLine, ), + const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.compress, size: 24), + title: Text(context.l10n.appSettings_showCompressionIndicator), + subtitle: Text( + context.l10n.appSettings_showCompressionIndicatorSubtitle, + ), + value: settingsService.settings.showCompressionIndicator, + onChanged: settingsService.setShowCompressionIndicator, + ), ], ); } diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 35bc8a71..acc29664 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1109,6 +1109,8 @@ class _ChannelChatScreenState extends State { final publicIpfsGateway = settingsService.settings.publicIpfsGateway; final enableTracing = settingsService.settings.enableMessageTracing; final regionOnHopsLine = settingsService.settings.regionOnHopsLine; + final showCompressionIndicator = + settingsService.settings.showCompressionIndicator; final isOutgoing = message.isOutgoing; final scheme = Theme.of(context).colorScheme; final gifId = GifHelper.parseGif(message.text); @@ -1423,8 +1425,10 @@ class _ChannelChatScreenState extends State { bottom: 4, ) : EdgeInsets.zero, - child: Row( - mainAxisSize: MainAxisSize.min, + child: Wrap( + spacing: 4, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, children: [ Text( formatChatTime(context, message.timestamp), @@ -1433,20 +1437,23 @@ class _ChannelChatScreenState extends State { color: metaColor, ), ), - if (message.hasFutureTimestamp) ...[ - const SizedBox(width: 4), + if (message.hasFutureTimestamp) FutureTimestampIndicator(size: 16 * textScale), - ], + if (showCompressionIndicator && + message.isSmazCompressed) + CompressionIndicator( + size: 14 * textScale, + color: metaColor, + ), if (enableTracing && !isOutgoing && message.repeatCount > 0) ...[ - const SizedBox(width: 6), + const SizedBox(width: 2), Icon( Icons.repeat, size: 14 * textScale, color: metaColor, ), - const SizedBox(width: 2), Text( '${message.repeatCount}', style: MeshTheme.mono( @@ -1455,8 +1462,7 @@ class _ChannelChatScreenState extends State { ), ), ], - if (isOutgoing) ...[ - const SizedBox(width: 4), + if (isOutgoing) MessageStatusIcon( size: 16 * textScale, isAcked: false, @@ -1476,7 +1482,6 @@ class _ChannelChatScreenState extends State { ChannelMessageStatus.failed, onColor: metaColor, ), - ], ], ), ), diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 45839b52..2136b488 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -1574,6 +1574,8 @@ class _MessageBubble extends StatelessWidget { Widget build(BuildContext context) { final settingsService = context.watch(); final enableTracing = settingsService.settings.enableMessageTracing; + final showCompressionIndicator = + settingsService.settings.showCompressionIndicator; final isOutgoing = message.isOutgoing; final scheme = Theme.of(context).colorScheme; final gifId = GifHelper.parseGif(message.text); @@ -1838,6 +1840,12 @@ class _MessageBubble extends StatelessWidget { FutureTimestampIndicator( size: 16 * textScale, ), + if (showCompressionIndicator && + message.isSmazCompressed) + CompressionIndicator( + size: 14 * textScale, + color: metaColor, + ), if (isOutgoing) ...[ const SizedBox(width: 2), MessageStatusIcon( diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index d0758681..d8e5c714 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'dart:convert'; + import 'package:flutter/foundation.dart'; + import '../models/app_settings.dart'; import '../models/custom_theme.dart'; import '../models/holiday_schedule.dart'; @@ -135,6 +137,10 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(regionOnHopsLine: value)); } + Future setShowCompressionIndicator(bool value) async { + await updateSettings(_settings.copyWith(showCompressionIndicator: value)); + } + Future setMapCacheBounds(Map? value) async { await updateSettings(_settings.copyWith(mapCacheBounds: value)); } diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart index 4495ce91..9b38b8c4 100644 --- a/lib/services/message_retry_service.dart +++ b/lib/services/message_retry_service.dart @@ -1,8 +1,10 @@ import 'dart:async'; import 'dart:convert'; + import 'package:flutter/foundation.dart'; import 'package:uuid/uuid.dart'; import 'package:crypto/crypto.dart'; + import '../connector/meshcore_protocol.dart'; import '../models/contact.dart'; import '../models/message.dart'; @@ -169,6 +171,7 @@ class MessageRetryService extends ChangeNotifier { String? translationModelId, Uint8List? pathBytes, int? pathLength, + bool isSmazCompressed = false, }) async { final messageId = const Uuid().v4(); final resolved = resolvePathSelection(contact); @@ -184,6 +187,7 @@ class MessageRetryService extends ChangeNotifier { translationModelId: translationModelId, timestamp: DateTime.now(), isOutgoing: true, + isSmazCompressed: isSmazCompressed, status: MessageStatus.pending, messageId: messageId, retryCount: 0, diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 5383b59a..7e6a7914 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:typed_data'; + import 'package:meshcore_open/utils/app_logger.dart'; import '../models/channel_message.dart'; @@ -160,6 +161,7 @@ class ChannelMessageStore { 'receivedAt': msg.receivedAt.millisecondsSinceEpoch, 'isOutgoing': msg.isOutgoing, 'isBookmarked': msg.isBookmarked, + 'isSmazCompressed': msg.isSmazCompressed, 'status': msg.status.index, 'channelIndex': msg.channelIndex, 'region': msg.region, @@ -186,9 +188,12 @@ class ChannelMessageStore { /// Convert JSON map to ChannelMessage ChannelMessage _messageFromJson(Map json) { final rawText = json['text'] as String; - final decodedText = json['plainText'] == true - ? rawText - : (Smaz.tryDecodePrefixed(rawText) ?? rawText); + final smazDecoded = json['plainText'] == true + ? null + : Smaz.tryDecodePrefixed(rawText); + final decodedText = smazDecoded ?? rawText; + final isSmazCompressed = + json['isSmazCompressed'] as bool? ?? (smazDecoded != null); final rawPathLength = json['pathLength'] as int?; final rawPathBytes = json['pathBytes'] != null @@ -238,6 +243,7 @@ class ChannelMessageStore { receivedAt: legacyAwareReceivedAt(json), isOutgoing: json['isOutgoing'] as bool? ?? false, isBookmarked: json['isBookmarked'] as bool? ?? false, + isSmazCompressed: isSmazCompressed, status: _statusAt(json['status']) ?? ChannelMessageStatus.failed, repeatCount: (json['repeatCount'] as int?) ?? 0, pathLength: decodedPathLength, diff --git a/lib/storage/message_store.dart b/lib/storage/message_store.dart index fec500d1..94ab883a 100644 --- a/lib/storage/message_store.dart +++ b/lib/storage/message_store.dart @@ -202,6 +202,7 @@ class MessageStore { 'isOutgoing': msg.isOutgoing, 'isBookmarked': msg.isBookmarked, 'isCli': msg.isCli, + 'isSmazCompressed': msg.isSmazCompressed, 'status': msg.status.index, 'messageId': msg.messageId, 'originalText': msg.originalText, @@ -233,9 +234,12 @@ class MessageStore { Message _messageFromJson(Map json) { final rawText = json['text'] as String; final isCli = json['isCli'] as bool? ?? false; - final decodedText = isCli || json['plainText'] == true - ? rawText - : (Smaz.tryDecodePrefixed(rawText) ?? rawText); + final smazDecoded = (isCli || json['plainText'] == true) + ? null + : Smaz.tryDecodePrefixed(rawText); + final decodedText = smazDecoded ?? rawText; + final isSmazCompressed = + json['isSmazCompressed'] as bool? ?? (smazDecoded != null); final rawPathLength = json['pathLength'] as int?; final rawPathBytes = json['pathBytes'] != null @@ -273,6 +277,7 @@ class MessageStore { isOutgoing: json['isOutgoing'] as bool? ?? false, isBookmarked: json['isBookmarked'] as bool? ?? false, isCli: isCli, + isSmazCompressed: isSmazCompressed, status: _statusAt(json['status']) ?? MessageStatus.failed, messageId: json['messageId'] as String?, originalText: json['originalText'] as String?, diff --git a/lib/widgets/message_bubble_frame.dart b/lib/widgets/message_bubble_frame.dart index 646eb344..976332c2 100644 --- a/lib/widgets/message_bubble_frame.dart +++ b/lib/widgets/message_bubble_frame.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; +import '../l10n/l10n.dart'; import '../theme/mesh_theme.dart'; /// Colours shared by the direct-message and channel chat bubbles. @@ -149,3 +150,25 @@ class MessageBubbleFrame extends StatelessWidget { ); } } + +/// Subtle indicator shown in a message bubble's metadata row when SMAZ +/// compression was applied to the message. +class CompressionIndicator extends StatelessWidget { + final double size; + final Color color; + + const CompressionIndicator({super.key, this.size = 14, required this.color}); + + @override + Widget build(BuildContext context) { + final label = context.l10n.messageMeta_smazCompressed; + return Tooltip( + message: label, + triggerMode: TooltipTriggerMode.tap, + child: Semantics( + label: label, + child: Icon(Icons.compress, size: size, color: color), + ), + ); + } +} diff --git a/test/models/compression_indicator_test.dart b/test/models/compression_indicator_test.dart new file mode 100644 index 00000000..173269d4 --- /dev/null +++ b/test/models/compression_indicator_test.dart @@ -0,0 +1,349 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/helpers/smaz.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/chat_compression_mode.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/services/app_settings_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/storage_service.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/history_store.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _deviceScope = 'abcdef012345'; +const _contactHex = + '1111111111111111111111111111111111111111111111111111111111111111'; +const _channelId = '0123456789abcdef'; +const _compressibleText = + 'This is a long enough English sentence that SMAZ compresses smaller.'; + +Uint8List _legacyDmFrame(Uint8List senderPubKey, String text, int timestamp) { + final writer = BufferWriter(); + writer.writeByte(respCodeContactMsgRecv); + writer.writeBytes(senderPubKey); + writer.writeInt32LE(timestamp); + writer.writeByte(txtTypePlain << 2); + writer.writeString(text); + writer.writeByte(0); + return writer.toBytes(); +} + +Future _waitFor(bool Function() condition) async { + final end = DateTime.now().add(const Duration(seconds: 8)); + while (!condition()) { + if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition'); + await Future.delayed(const Duration(milliseconds: 20)); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('AppSettings.showCompressionIndicator', () { + test('defaults to false, including for stored JSON without the key', () { + expect(AppSettings().showCompressionIndicator, isFalse); + final legacy = AppSettings().toJson() + ..remove('show_compression_indicator'); + expect(AppSettings.fromJson(legacy).showCompressionIndicator, isFalse); + }); + + test( + 'round-trips through JSON, copyWith, and AppSettingsService', + () async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + + final enabled = AppSettings().copyWith(showCompressionIndicator: true); + expect( + AppSettings.fromJson(enabled.toJson()).showCompressionIndicator, + isTrue, + ); + expect( + enabled.copyWith(enableMessageTracing: true).showCompressionIndicator, + isTrue, + ); + + final service = AppSettingsService(); + await service.loadSettings(); + expect(service.settings.showCompressionIndicator, isFalse); + + await service.setShowCompressionIndicator(true); + expect(service.settings.showCompressionIndicator, isTrue); + + final reloaded = AppSettingsService(); + await reloaded.loadSettings(); + expect(reloaded.settings.showCompressionIndicator, isTrue); + }, + ); + }); + + group('Message & MessageStore SMAZ flag', () { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + HistoryStore.reset(); + MessageStore().forgetArchive(); + }); + + test('Message.fromFrame decodes SMAZ and sets isSmazCompressed', () { + final sender = Uint8List.fromList(List.generate(32, (i) => i + 1)); + final encoded = Smaz.encodeIfSmaller(_compressibleText); + expect(encoded, startsWith('s:')); + + final compressedMsg = Message.fromFrame( + _legacyDmFrame(sender, encoded, 1700000000), + Uint8List(32), + )!; + expect(compressedMsg.text, _compressibleText); + expect(compressedMsg.isSmazCompressed, isTrue); + expect(compressedMsg.copyWith(retryCount: 1).isSmazCompressed, isTrue); + + final plainMsg = Message.fromFrame( + _legacyDmFrame(sender, 'plain hello', 1700000001), + Uint8List(32), + )!; + expect(plainMsg.text, 'plain hello'); + expect(plainMsg.isSmazCompressed, isFalse); + }); + + test( + 'MessageStore persists flag and defaults legacy rows to false', + () async { + final store = MessageStore()..setPublicKeyHex = _deviceScope; + final key = Uint8List.fromList(List.generate(32, (i) => i + 2)); + final compressed = Message.outgoing( + key, + _compressibleText, + isSmazCompressed: true, + ); + final plain = Message.outgoing(key, 'hi', isSmazCompressed: false); + + await store.saveMessages(_contactHex, [compressed, plain]); + final loaded = await store.loadMessages(_contactHex); + expect(loaded, hasLength(2)); + expect(loaded[0].isSmazCompressed, isTrue); + expect(loaded[1].isSmazCompressed, isFalse); + + // Legacy persisted message without `isSmazCompressed` key defaults to false. + await HistoryStore.instance.setString( + '${store.keyFor}$_contactHex', + jsonEncode([ + { + 'senderKey': base64Encode(key), + 'text': 'legacy plain', + 'timestamp': 1700000002000, + 'receivedAt': 1700000002000, + 'isOutgoing': false, + 'status': MessageStatus.delivered.index, + 'plainText': true, + }, + ]), + ); + final legacyLoaded = await store.loadMessages(_contactHex); + expect(legacyLoaded, hasLength(1)); + expect(legacyLoaded.first.isSmazCompressed, isFalse); + }, + ); + }); + + group('ChannelMessage & ChannelMessageStore SMAZ flag', () { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + HistoryStore.reset(); + ChannelMessageStore().forgetArchive(); + }); + + test('ChannelMessage.fromFrame decodes SMAZ and sets isSmazCompressed', () { + final encoded = Smaz.encodeIfSmaller(_compressibleText); + expect(encoded, startsWith('s:')); + + final compressed = ChannelMessage.fromFrame( + ReviewFrames.channelMessage( + channelIndex: 0, + sender: 'Maya', + message: encoded, + timestampSecs: 1700000000, + ), + )!; + expect(compressed.text, _compressibleText); + expect(compressed.isSmazCompressed, isTrue); + expect(compressed.copyWith(repeatCount: 2).isSmazCompressed, isTrue); + + final plain = ChannelMessage.fromFrame( + ReviewFrames.channelMessage( + channelIndex: 0, + sender: 'Maya', + message: 'hello camp', + timestampSecs: 1700000001, + ), + )!; + expect(plain.text, 'hello camp'); + expect(plain.isSmazCompressed, isFalse); + }); + + test( + 'ChannelMessageStore persists flag and defaults legacy rows to false', + () async { + final store = ChannelMessageStore()..setPublicKeyHex = _deviceScope; + final compressed = ChannelMessage.outgoing( + _compressibleText, + 'Me', + 0, + isSmazCompressed: true, + ); + final plain = ChannelMessage.outgoing( + 'short', + 'Me', + 0, + isSmazCompressed: false, + ); + + await store.saveChannelMessages(_channelId, [compressed, plain]); + final loaded = await store.loadChannelMessages(_channelId); + expect(loaded, hasLength(2)); + expect(loaded[0].isSmazCompressed, isTrue); + expect(loaded[1].isSmazCompressed, isFalse); + + await HistoryStore.instance.setString( + '${store.keyFor}_$_channelId', + jsonEncode([ + { + 'senderName': 'Maya', + 'text': 'legacy channel msg', + 'timestamp': 1700000002000, + 'receivedAt': 1700000002000, + 'isOutgoing': false, + 'status': ChannelMessageStatus.sent.index, + 'channelIndex': 0, + 'plainText': true, + }, + ]), + ); + final legacyLoaded = await store.loadChannelMessages(_channelId); + expect(legacyLoaded, hasLength(1)); + expect(legacyLoaded.first.isSmazCompressed, isFalse); + }, + ); + }); + + group('MeshCoreConnector SMAZ tracking', () { + late MeshCoreConnector connector; + late MessageRetryService retryService; + late ReviewRadio radio; + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + HistoryStore.reset(); + connector = MeshCoreConnector(); + retryService = MessageRetryService(); + connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + ); + connector.reviewRadioFactoryForTest = () { + radio = ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + return radio; + }; + await connector.connectReview(); + await _waitFor( + () => + connector.channelMapConfirmed && + connector.contacts.isNotEmpty && + connector.channels.isNotEmpty, + ); + addTearDown(() async { + await connector.disconnect(); + connector.dispose(); + retryService.dispose(); + }); + }); + + test( + 'records isSmazCompressed on outgoing DM and channel messages', + () async { + final contact = connector.contacts.first; + final channel = connector.channels.first; + + // Mode off: not SMAZ compressed. + await connector.setContactCompressionMode( + contact.publicKeyHex, + ChatCompressionMode.off, + ); + await connector.sendMessage(contact, _compressibleText); + + // Mode SMAZ: compressible text sets flag, tiny uncompressible text does not. + await connector.setContactCompressionMode( + contact.publicKeyHex, + ChatCompressionMode.smaz, + ); + await connector.sendMessage(contact, _compressibleText); + await connector.sendMessage(contact, 'ok'); + + // Mode Cyr2Lat: not SMAZ compressed. + await connector.setContactCompressionMode( + contact.publicKeyHex, + ChatCompressionMode.cyr2lat, + ); + await connector.sendMessage(contact, 'Привет мир'); + + final dmMessages = connector.getMessages(contact); + final recentDms = dmMessages.sublist(dmMessages.length - 4); + expect(recentDms[0].isSmazCompressed, isFalse); + expect(recentDms[1].isSmazCompressed, isTrue); + expect(recentDms[2].isSmazCompressed, isFalse); + expect(recentDms[3].isSmazCompressed, isFalse); + + // Channel outgoing messages. + await connector.setChannelCompressionMode( + channel.index, + ChatCompressionMode.off, + ); + await connector.sendChannelMessage(channel, _compressibleText); + + await connector.setChannelCompressionMode( + channel.index, + ChatCompressionMode.smaz, + ); + await connector.sendChannelMessage(channel, _compressibleText); + await connector.sendChannelMessage(channel, 'ok'); + + await connector.setChannelCompressionMode( + channel.index, + ChatCompressionMode.cyr2lat, + ); + await connector.sendChannelMessage(channel, 'Привет мир'); + + final chMessages = connector.getChannelMessages(channel); + final recentCh = chMessages.sublist(chMessages.length - 4); + expect(recentCh[0].isSmazCompressed, isFalse); + expect(recentCh[1].isSmazCompressed, isTrue); + expect(recentCh[2].isSmazCompressed, isFalse); + expect(recentCh[3].isSmazCompressed, isFalse); + + // Ensure radio reference stays live without lint warnings. + expect(radio, isNotNull); + }, + ); + }); +} diff --git a/test/widgets/compression_indicator_test.dart b/test/widgets/compression_indicator_test.dart new file mode 100644 index 00000000..2765d24d --- /dev/null +++ b/test/widgets/compression_indicator_test.dart @@ -0,0 +1,584 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.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/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/custom_theme.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/screens/app_settings_screen.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_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/network_map/network_map_upload_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/channel_message_store.dart'; +import 'package:meshcore_open/storage/channel_store.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/history_store.dart'; +import 'package:meshcore_open/storage/last_radio_store.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/message_bubble_frame.dart'; +import 'package:meshcore_open/widgets/message_status_icon.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +final _radioKey = Uint8List.fromList(List.generate(32, (i) => 0xA0 + i)); +final _radioHex = pubKeyToHex(_radioKey); +final _aliceKey = Uint8List.fromList(List.generate(32, (i) => 0x10 + i)); +final _psk = Uint8List.fromList(List.generate(16, (i) => 0x40 + i)); +final _l10n = lookupAppLocalizations(const Locale('en')); + +Future _seedMessages() async { + final alice = Contact( + publicKey: _aliceKey, + name: 'Alice', + type: advTypeChat, + pathLength: 1, + path: Uint8List.fromList([0x22]), + lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ); + await (ContactStore()..setPublicKeyHex = _radioHex).saveContacts([alice]); + final channel = Channel(index: 0, name: 'Base Camp', psk: _psk); + final channelStore = ChannelStore()..setPublicKeyHex = _radioHex; + await channelStore.saveChannels([channel]); + await channelStore.saveSlotChannelIds({0: channel.storageId!}); + + await (MessageStore()..setPublicKeyHex = _radioHex) + .saveMessages(alice.publicKeyHex, [ + Message( + senderKey: _aliceKey, + text: 'DM incoming compressed', + timestamp: DateTime(2026, 11, 21, 10, 11), + receivedAt: DateTime(2026, 11, 21, 10, 11), + isOutgoing: false, + isSmazCompressed: true, + status: MessageStatus.delivered, + ), + Message( + senderKey: _aliceKey, + text: 'DM incoming plain', + timestamp: DateTime(2026, 11, 21, 10, 12), + receivedAt: DateTime(2026, 11, 21, 10, 12), + isOutgoing: false, + isSmazCompressed: false, + status: MessageStatus.delivered, + ), + Message( + senderKey: _aliceKey, + text: 'DM outgoing plain', + timestamp: DateTime(2026, 11, 21, 10, 13), + receivedAt: DateTime(2026, 11, 21, 10, 13), + isOutgoing: true, + isSmazCompressed: false, + status: MessageStatus.delivered, + ), + Message( + senderKey: _aliceKey, + text: 'DM outgoing compressed', + timestamp: DateTime(2026, 11, 21, 10, 14), + receivedAt: DateTime(2026, 11, 21, 10, 14), + isOutgoing: true, + isSmazCompressed: true, + status: MessageStatus.delivered, + ), + ]); + + await (ChannelMessageStore()..setPublicKeyHex = _radioHex) + .saveChannelMessages(channel.storageId!, [ + ChannelMessage( + senderName: 'Bob', + text: 'Channel incoming compressed', + timestamp: DateTime(2026, 11, 21, 11, 11), + receivedAt: DateTime(2026, 11, 21, 11, 11), + isOutgoing: false, + isSmazCompressed: true, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ChannelMessage( + senderName: 'Bob', + text: 'Channel incoming plain', + timestamp: DateTime(2026, 11, 21, 11, 12), + receivedAt: DateTime(2026, 11, 21, 11, 12), + isOutgoing: false, + isSmazCompressed: false, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ChannelMessage( + senderName: 'Me', + text: 'Channel outgoing plain', + timestamp: DateTime(2026, 11, 21, 11, 13), + receivedAt: DateTime(2026, 11, 21, 11, 13), + isOutgoing: true, + isSmazCompressed: false, + repeatCount: 1, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ChannelMessage( + senderName: 'Me', + text: 'Channel outgoing compressed', + timestamp: DateTime(2026, 11, 21, 11, 14), + receivedAt: DateTime(2026, 11, 21, 11, 14), + isOutgoing: true, + isSmazCompressed: true, + repeatCount: 2, + status: ChannelMessageStatus.sent, + channelIndex: 0, + ), + ]); + + await LastRadioStore().save( + LastRadio( + publicKeyHex: _radioHex, + name: 'Base', + transport: LastRadio.transportBle, + bleRemoteId: 'AA:BB:CC:DD:EE:FF', + savedAt: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ), + ); +} + +class _Harness { + final MeshCoreConnector connector; + final AppSettingsService settings; + final List disposables; + + _Harness(this.connector, this.settings, this.disposables); + + List> get _unused => const []; + + Widget wrap(Widget home, {ThemeData? theme, double textScale = 1.0}) { + final storage = StorageService(); + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value( + value: disposables[0] as MessageRetryService, + ), + ChangeNotifierProvider.value( + value: disposables[1] as PathHistoryService, + ), + ChangeNotifierProvider.value( + value: disposables[2] as BleDebugLogService, + ), + ChangeNotifierProvider.value( + value: disposables[3] as AppDebugLogService, + ), + ChangeNotifierProvider.value( + value: disposables[4] as ChatTextScaleService, + ), + ChangeNotifierProvider.value( + value: disposables[5] as TranslationService, + ), + ChangeNotifierProvider.value( + value: disposables[6] as UiViewStateService, + ), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: disposables[7] as MapTileCacheService, + ), + ChangeNotifierProvider.value( + value: disposables[8] as TimeoutPredictionService, + ), + ChangeNotifierProvider.value( + value: disposables[9] as ImageCodecService, + ), + ChangeNotifierProvider.value( + value: disposables[10] as ReceivedImageStore, + ), + ChangeNotifierProvider.value( + value: disposables[11] as NetworkMapUploadService, + ), + ], + 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.linear(textScale), + alwaysUse24HourFormat: true, + ), + child: child!, + ), + home: home, + ), + ); + } + + void dispose() { + assert(_unused.isEmpty); + connector.dispose(); + settings.dispose(); + for (final d in disposables) { + if (d is ChangeNotifier) d.dispose(); + } + } +} + +Future<_Harness> _createHarness({bool showIndicator = false}) async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + HistoryStore.reset(); + MessageStore().forgetArchive(); + ChannelMessageStore().forgetArchive(); + await _seedMessages(); + + final storage = StorageService(); + final settings = AppSettingsService(); + await settings.loadSettings(); + if (showIndicator) { + await settings.setShowCompressionIndicator(true); + } + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final pathHistory = PathHistoryService(storage); + final bleLog = BleDebugLogService(); + final appLog = AppDebugLogService(); + final textScale = ChatTextScaleService(); + final translation = TranslationService(settings); + final uiView = UiViewStateService(); + final tileCache = MapTileCacheService(appSettingsService: settings); + final timeoutPred = TimeoutPredictionService(storage); + final imageCodec = ImageCodecService(settings); + final receivedImage = ReceivedImageStore(); + final networkMap = NetworkMapUploadService( + connector: connector, + settings: settings, + ); + await connector.restoreLastRadio(); + return _Harness(connector, settings, [ + retry, + pathHistory, + bleLog, + appLog, + textScale, + translation, + uiView, + tileCache, + timeoutPred, + imageCodec, + receivedImage, + networkMap, + ]); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync( + 'compression_indicator_test', + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + testWidgets( + 'AppSettingsScreen shows Compression indicator switch and toggles', + (tester) async { + late _Harness harness; + await tester.runAsync(() async { + harness = await _createHarness(); + await harness.settings.setAutoRouteRotationEnabled(false); + }); + addTearDown(harness.dispose); + + tester.view.physicalSize = const Size(390, 720); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await tester.pumpWidget(harness.wrap(const AppSettingsScreen())); + await tester.pumpAndSettle(); + + final tileFinder = find.widgetWithText( + SwitchListTile, + _l10n.appSettings_showCompressionIndicator, + ); + await tester.scrollUntilVisible( + tileFinder, + 60, + scrollable: find.byType(Scrollable).first, + ); + await tester.pumpAndSettle(); + + final tile = tester.widget(tileFinder); + expect(tile.value, isFalse); + expect( + find.descendant(of: tileFinder, matching: find.byIcon(Icons.compress)), + findsOneWidget, + ); + + await tester.tap(tileFinder); + await tester.pumpAndSettle(); + expect(harness.settings.settings.showCompressionIndicator, isTrue); + }, + ); + + testWidgets( + 'DM ChatScreen hides icon when off, shows only on compressed when on', + (tester) async { + final semantics = tester.ensureSemantics(); + try { + late _Harness harness; + await tester.runAsync(() async { + harness = await _createHarness(showIndicator: false); + }); + addTearDown(harness.dispose); + + final contact = harness.connector.contacts.first; + await tester.pumpWidget(harness.wrap(ChatScreen(contact: contact))); + await tester.pumpAndSettle(); + + expect(find.byType(CompressionIndicator), findsNothing); + + await tester.runAsync( + () => harness.settings.setShowCompressionIndicator(true), + ); + await tester.pumpAndSettle(); + + // Two compressed messages (1 incoming, 1 outgoing); two plain have none. + expect(find.byType(CompressionIndicator), findsNWidgets(2)); + expect( + find.byTooltip(_l10n.messageMeta_smazCompressed), + findsNWidgets(2), + ); + expect( + find.bySemanticsLabel(RegExp(_l10n.messageMeta_smazCompressed)), + findsNWidgets(2), + ); + + // Incoming compressed message: CompressionIndicator sits after timestamp, no ticks. + final incomingBubble = find.ancestor( + of: find.text('DM incoming compressed'), + matching: find.byType(MessageBubbleFrame), + ); + final incomingIndicator = find.descendant( + of: incomingBubble, + matching: find.byType(CompressionIndicator), + ); + final incomingTime = find.descendant( + of: incomingBubble, + matching: find.text('10:11'), + ); + expect(incomingIndicator, findsOneWidget); + expect( + tester.getTopLeft(incomingIndicator).dx, + greaterThan(tester.getTopRight(incomingTime).dx), + ); + expect( + find.descendant( + of: incomingBubble, + matching: find.byType(MessageStatusIcon), + ), + findsNothing, + ); + + // Outgoing compressed message: CompressionIndicator sits between timestamp and ticks. + final outgoingBubble = find.ancestor( + of: find.text('DM outgoing compressed'), + matching: find.byType(MessageBubbleFrame), + ); + final outgoingIndicator = find.descendant( + of: outgoingBubble, + matching: find.byType(CompressionIndicator), + ); + final outgoingTime = find.descendant( + of: outgoingBubble, + matching: find.text('10:14'), + ); + final outgoingTicks = find.descendant( + of: outgoingBubble, + matching: find.byType(MessageStatusIcon), + ); + expect(outgoingIndicator, findsOneWidget); + expect( + tester.getTopLeft(outgoingIndicator).dx, + greaterThan(tester.getTopRight(outgoingTime).dx), + ); + expect( + tester.getTopRight(outgoingIndicator).dx, + lessThanOrEqualTo(tester.getTopLeft(outgoingTicks).dx), + ); + + // Plain messages never show the icon. + final plainBubble = find.ancestor( + of: find.text('DM outgoing plain'), + matching: find.byType(MessageBubbleFrame), + ); + expect( + find.descendant( + of: plainBubble, + matching: find.byType(CompressionIndicator), + ), + findsNothing, + ); + } finally { + semantics.dispose(); + } + }, + ); + + testWidgets( + 'ChannelChatScreen hides icon when off, shows between time and ticks when on', + (tester) async { + late _Harness harness; + await tester.runAsync(() async { + harness = await _createHarness(showIndicator: false); + }); + addTearDown(harness.dispose); + + final channel = harness.connector.channels.first; + await tester.pumpWidget( + harness.wrap(ChannelChatScreen(channel: channel)), + ); + await tester.pumpAndSettle(); + + expect(find.byType(CompressionIndicator), findsNothing); + + await tester.runAsync( + () => harness.settings.setShowCompressionIndicator(true), + ); + await tester.pumpAndSettle(); + + expect(find.byType(CompressionIndicator), findsNWidgets(2)); + + // Outgoing compressed channel message: icon between timestamp and repeat ticks. + final outgoingBubble = find.ancestor( + of: find.text('Channel outgoing compressed'), + matching: find.byType(MessageBubbleFrame), + ); + final outgoingIndicator = find.descendant( + of: outgoingBubble, + matching: find.byType(CompressionIndicator), + ); + final outgoingTime = find.descendant( + of: outgoingBubble, + matching: find.text('11:14'), + ); + final outgoingTicks = find.descendant( + of: outgoingBubble, + matching: find.byType(MessageStatusIcon), + ); + expect(outgoingIndicator, findsOneWidget); + expect( + tester.getTopLeft(outgoingIndicator).dx, + greaterThan(tester.getTopRight(outgoingTime).dx), + ); + expect( + tester.getTopRight(outgoingIndicator).dx, + lessThanOrEqualTo(tester.getTopLeft(outgoingTicks).dx), + ); + + // Incoming compressed channel message: icon right after timestamp. + final incomingBubble = find.ancestor( + of: find.text('Channel incoming compressed'), + matching: find.byType(MessageBubbleFrame), + ); + final incomingIndicator = find.descendant( + of: incomingBubble, + matching: find.byType(CompressionIndicator), + ); + final incomingTime = find.descendant( + of: incomingBubble, + matching: find.text('11:11'), + ); + expect(incomingIndicator, findsOneWidget); + expect( + tester.getTopLeft(incomingIndicator).dx, + greaterThan(tester.getTopRight(incomingTime).dx), + ); + }, + ); + + testWidgets('No overflow at 320dp width and 2.0x text scale across themes', ( + tester, + ) async { + late _Harness harness; + await tester.runAsync(() async { + harness = await _createHarness(showIndicator: true); + }); + addTearDown(harness.dispose); + + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final overflows = []; + final previous = FlutterError.onError; + FlutterError.onError = (details) { + final text = details.exceptionAsString(); + if (text.contains('overflowed')) { + overflows.add(text.split('\n').first); + } else { + previous?.call(details); + } + }; + addTearDown(() => FlutterError.onError = previous); + + final contact = harness.connector.contacts.first; + final channel = harness.connector.channels.first; + + final themes = [ + MeshTheme.light(), + MeshTheme.dark(), + MeshTheme.fromCustom(CustomTheme.presets.first), + ]; + + for (final theme in themes) { + await tester.pumpWidget( + harness.wrap( + ChatScreen(contact: contact), + theme: theme, + textScale: 2.0, + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(CompressionIndicator), findsAtLeastNWidgets(1)); + + await tester.pumpWidget( + harness.wrap( + ChannelChatScreen(channel: channel), + theme: theme, + textScale: 2.0, + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(CompressionIndicator), findsAtLeastNWidgets(1)); + } + + FlutterError.onError = previous; + expect(overflows, isEmpty, reason: overflows.join('\n')); + }); +}