Merge upstream/dev (35 commits) into tth

Conflicts in lib/widgets/mesh_nav_tile.dart and lib/widgets/mesh_ui.dart:
took upstream's iconSlot/ThemedIcon, busy spinner and SectionHeader
description, and re-applied the terminal theme on top (18 dp icons,
narrower gaps and padding, mono section labels).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-24 11:47:28 +01:00
commit ceab62428a
103 files changed
+13328 -5463

No files matched your search

@@ -0,0 +1,33 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
void main() {
// CMD_SET_AUTOADD_CONFIG: [cmd][flags][autoadd_max_hops?]. Firmware stores
// the third byte (capped at 64) only when it is present.
group('buildSetAutoAddConfigFrame', () {
Iterable<int> frame({int? maxHops}) => buildSetAutoAddConfigFrame(
autoAddChat: true,
autoAddRepeater: false,
autoAddRoomServer: true,
autoAddSensor: false,
overwriteOldest: true,
maxHops: maxHops,
);
const flags =
autoAddChatFlag | autoAddRoomServerFlag | autoAddOverwriteOldestFlag;
test('omits the hop limit when not given', () {
expect(frame(), [cmdSetAutoAddConfig, flags]);
});
test('appends the hop limit, including 0 (no limit)', () {
expect(frame(maxHops: 8), [cmdSetAutoAddConfig, flags, 8]);
expect(frame(maxHops: 0), [cmdSetAutoAddConfig, flags, 0]);
});
test('caps the hop limit at 64', () {
expect(frame(maxHops: 200), [cmdSetAutoAddConfig, flags, 64]);
});
});
}
@@ -0,0 +1,191 @@
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/message_url_image_helper.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
Future<ui.Image> _solid(int w, int h) {
final c = Completer<ui.Image>();
ui.decodeImageFromPixels(
Uint8List(w * h * 4),
w,
h,
ui.PixelFormat.rgba8888,
c.complete,
);
return c.future;
}
class _FailingProvider extends ImageProvider<_FailingProvider> {
@override
Future<_FailingProvider> obtainKey(ImageConfiguration c) =>
SynchronousFuture(this);
@override
ImageStreamCompleter loadImage(
_FailingProvider key,
ImageDecoderCallback decode,
) => OneFrameImageStreamCompleter(Future.error(Exception('nope')));
}
Widget _host(Widget child, {double width = 320, double scale = 1.0}) {
return MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: MediaQuery(
data: MediaQueryData(
size: Size(width, 800),
textScaler: TextScaler.linear(scale),
),
child: Scaffold(
body: Align(
alignment: Alignment.topLeft,
// Mimics a bubble: bounded width, tight-to-content otherwise.
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: width - 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Align(alignment: Alignment.centerLeft, child: child),
const Text('caption text that follows the image'),
],
),
),
),
),
),
);
}
Future<Size> _previewSize(WidgetTester tester, int w, int h) async {
final image = await tester.runAsync(() => _solid(w, h));
await tester.pumpWidget(
_host(
MessageUrlImagePreview(
imageUrl: 'https://example.com/a.png',
imageProvider: _ImageProviderOf(image!),
),
),
);
await tester.pump();
return tester.getSize(find.byType(RawImage));
}
class _ImageProviderOf extends ImageProvider<_ImageProviderOf> {
_ImageProviderOf(this.image);
final ui.Image image;
@override
Future<_ImageProviderOf> obtainKey(ImageConfiguration c) =>
SynchronousFuture(this);
@override
ImageStreamCompleter loadImage(
_ImageProviderOf key,
ImageDecoderCallback decode,
) => OneFrameImageStreamCompleter(
SynchronousFuture(ImageInfo(image: image.clone())),
);
}
void main() {
test('urlImagePreviewSize keeps aspect ratio and caps height', () {
expect(urlImagePreviewSize(400, 100, 280), const Size(280, 70));
expect(urlImagePreviewSize(300, 300, 280), const Size(280, 280));
final tall = urlImagePreviewSize(100, 1000, 280);
expect(tall.height, MessageUrlImagePreview.maxHeight);
expect(tall.width, closeTo(40, 0.001));
});
testWidgets('4:1 image fills width with height width/4', (tester) async {
final size = await _previewSize(tester, 400, 100);
expect(size.width, 280);
expect(size.height, closeTo(70, 0.001));
});
testWidgets('square image is 1:1 at full width', (tester) async {
final size = await _previewSize(tester, 300, 300);
expect(size, const Size(280, 280));
});
testWidgets('tall image is capped and shown whole', (tester) async {
final size = await _previewSize(tester, 100, 1000);
expect(size.height, MessageUrlImagePreview.maxHeight);
expect(size.width, closeTo(40, 0.001));
});
testWidgets('unbounded width falls back to 320', (tester) async {
final image = await tester.runAsync(() => _solid(640, 320));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: MessageUrlImagePreview(
imageUrl: 'x',
imageProvider: _ImageProviderOf(image!),
),
),
),
),
);
await tester.pump();
expect(tester.getSize(find.byType(RawImage)), const Size(320, 160));
});
for (final scale in [1.3, 2.0]) {
testWidgets('error state is compact without overflow at ${scale}x', (
tester,
) async {
await tester.pumpWidget(
_host(
MessageUrlImagePreview(
imageUrl: 'x',
imageProvider: _FailingProvider(),
),
scale: scale,
),
);
await tester.pump();
await tester.pump();
expect(find.text('Unable to load image'), findsOneWidget);
expect(tester.takeException(), isNull);
});
}
testWidgets('loading placeholder is compact and full width', (tester) async {
await tester.pumpWidget(
_host(
MessageUrlImagePreview(imageUrl: 'x', imageProvider: _NeverProvider()),
),
);
final box = find.ancestor(
of: find.byType(CircularProgressIndicator),
matching: find.byType(SizedBox),
);
final size = tester.getSize(box.first);
expect(size.width, 280);
expect(size.height, MessageUrlImagePreview.statusHeight);
});
}
class _NeverProvider extends ImageProvider<_NeverProvider> {
@override
Future<_NeverProvider> obtainKey(ImageConfiguration c) =>
SynchronousFuture(this);
@override
ImageStreamCompleter loadImage(
_NeverProvider key,
ImageDecoderCallback decode,
) => OneFrameImageStreamCompleter(Completer<ImageInfo>().future);
}
+172
View File
@@ -0,0 +1,172 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/smaz.dart';
int _utf8Len(String s) => utf8.encode(s).length;
Uint8List _raw(String s) =>
Smaz.compressBytes(Uint8List.fromList(utf8.encode(s)));
/// Sent size, raw SMAZ size and base64 wire size for [text].
({int plain, int raw, int wire, int sent}) _measure(String text) {
final raw = _raw(text);
return (
plain: _utf8Len(text),
raw: raw.length,
wire: _utf8Len('s:${base64Encode(raw)}'),
sent: _utf8Len(Smaz.encodeIfSmaller(text)),
);
}
void main() {
group('compression results', () {
test('lowercase English compresses well', () {
const text = 'hello there, how are you doing today?';
final m = _measure(text);
expect((m.plain, m.raw, m.wire, m.sent), (37, 20, 30, 30));
expect(Smaz.encodeIfSmaller(text), startsWith('s:'));
});
test('sentence case compresses, a little less', () {
const text = 'Hello there, how are you doing today?';
final m = _measure(text);
expect((m.plain, m.raw, m.wire, m.sent), (37, 22, 34, 34));
expect(Smaz.encodeIfSmaller(text), startsWith('s:'));
});
test('mixed case with many capitals barely compresses', () {
const mixed = 'Meeting at Headquarters on Monday afternoon';
const lower = 'meeting at headquarters on monday afternoon';
expect(_measure(mixed).wire, 42);
expect(_measure(mixed).plain, 43);
expect(Smaz.encodeIfSmaller(mixed), startsWith('s:'));
// The same words in lowercase save far more.
expect(_measure(lower).wire, 34);
expect(_measure(lower).raw, 24);
// Each capital that is not in the codebook costs 2 bytes.
expect(_measure(mixed).raw - _measure(lower).raw, 4);
});
test('all caps is longer than the plain text, so it is sent plain', () {
const text = 'HELLO THERE, HOW ARE YOU DOING TODAY?';
final m = _measure(text);
expect((m.plain, m.raw, m.wire, m.sent), (37, 50, 70, 37));
expect(Smaz.encodeIfSmaller(text), text);
});
test('a reply prefix costs the same in either case', () {
expect(
_raw('@[Alice] hello there, how are you?').length,
_raw('@[alice] hello there, how are you?').length,
);
// 34 bytes plain, 34 bytes encoded: not strictly smaller, sent plain.
const text = '@[Alice] hello there, how are you?';
expect(_measure(text).wire, _measure(text).plain);
expect(Smaz.encodeIfSmaller(text), text);
});
});
group('non-ASCII text', () {
test('Cyrillic round-trips as raw bytes but is sent plain', () {
const text = 'Привет, как дела сегодня?';
final m = _measure(text);
expect((m.plain, m.raw, m.wire, m.sent), (45, 52, 74, 45));
expect(Smaz.encodeIfSmaller(text), text);
// The byte-level codec is still lossless.
expect(utf8.decode(Smaz.decompressBytes(_raw(text))), text);
});
test('emoji survives a compressed round trip', () {
const text =
'see you soon 😀 the best of luck with the new house and the garden';
final encoded = Smaz.encodeIfSmaller(text);
expect(encoded, startsWith('s:'));
expect(_utf8Len(encoded), lessThan(_utf8Len(text)));
expect(Smaz.tryDecodePrefixed(encoded), text);
});
test('a short emoji message is not smaller, so it is sent plain', () {
const text = 'see you soon 😀 the best';
final m = _measure(text);
expect((m.plain, m.raw, m.wire, m.sent), (26, 17, 26, 26));
expect(Smaz.encodeIfSmaller(text), text);
});
});
group('encodeIfSmaller falls back to plain text', () {
test('short strings', () {
for (final text in ['hi', 'ok', 'Hello', 'the']) {
expect(Smaz.encodeIfSmaller(text), text, reason: text);
}
});
test('empty string', () {
expect(Smaz.encodeIfSmaller(''), '');
});
test('sent form is never longer than the plain text', () {
for (final text in [
'a',
'Hello',
'HELLO THERE, HOW ARE YOU DOING TODAY?',
'the quick brown fox jumps over the lazy dog',
'Привет, как дела?',
'12345 67890',
]) {
expect(
_utf8Len(Smaz.encodeIfSmaller(text)),
lessThanOrEqualTo(_utf8Len(text)),
reason: text,
);
}
});
});
group('round trip', () {
test('tryDecodePrefixed restores what encodeIfSmaller produced', () {
for (final text in [
'hello there, how are you doing today?',
'Hello there, how are you doing today?',
'Meeting at Headquarters on Monday afternoon',
'the quick brown fox jumps over the lazy dog',
'@[Alice] hello there, how are you doing today my friend?',
]) {
final encoded = Smaz.encodeIfSmaller(text);
expect(encoded, startsWith('s:'), reason: text);
expect(Smaz.tryDecodePrefixed(encoded), text, reason: text);
}
});
test('the decoder ignores leading whitespace', () {
const text = 'hello there, how are you doing today?';
expect(Smaz.tryDecodePrefixed(' ${Smaz.encodeIfSmaller(text)}'), text);
});
test('plain text is not a compressed payload', () {
expect(Smaz.tryDecodePrefixed('hello there'), isNull);
expect(Smaz.tryDecodePrefixed('s:'), isNull);
});
});
group('"s:" guard', () {
test('text that already starts with "s:" is never re-encoded', () {
const text = 's:hello there, how are you doing today?';
expect(Smaz.encodeIfSmaller(text), text);
});
test('plain "s:" text is not mistaken for a compressed payload', () {
expect(Smaz.tryDecodePrefixed('s:test'), isNull);
expect(Smaz.tryDecodePrefixed('s:hello'), isNull);
// Valid base64 that is not what the encoder would have produced.
expect(Smaz.tryDecodePrefixed('s:AAAA'), isNull);
});
test('malformed payloads return null instead of throwing', () {
expect(Smaz.tryDecodePrefixed('s:!!!!'), isNull);
// Truncated verbatim escape (0xFE with no byte after it).
expect(Smaz.tryDecodePrefixed('s:${base64Encode([254])}'), isNull);
});
});
}
+1 -1
View File
@@ -78,7 +78,7 @@ void main() {
expect(reader.readInt32LE(), ReviewScript.selfLatitudeE6);
expect(reader.readInt32LE(), ReviewScript.selfLongitudeE6);
reader.skipBytes(4);
expect(reader.readUInt32LE(), 910525000);
expect(reader.readUInt32LE(), 910525);
expect(reader.readUInt32LE(), 62500);
expect(reader.readByte(), 7);
expect(reader.readByte(), 5);
+752
View File
@@ -0,0 +1,752 @@
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:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/bookmarked_message.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/bookmarks_screen.dart';
import 'package:meshcore_open/screens/channel_chat_screen.dart';
import 'package:meshcore_open/screens/chat_screen.dart';
import 'package:meshcore_open/screens/contacts_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/prefs_manager.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';
final _l10n = lookupAppLocalizations(const Locale('en'));
class _TestEnv {
final MeshCoreConnector connector;
final Widget Function(Widget home, {double textScale}) wrap;
_TestEnv({required this.connector, required this.wrap});
}
_TestEnv? _sharedEnv;
Future<T> _pumpFuture<T>(WidgetTester tester, Future<T> future) async {
var done = false;
late T result;
Object? error;
StackTrace? stack;
future.then(
(value) {
result = value;
done = true;
},
onError: (Object e, StackTrace s) {
error = e;
stack = s;
done = true;
},
);
for (var i = 0; i < 50 && !done; i++) {
await tester.pump(const Duration(milliseconds: 10));
}
if (!done) {
throw StateError('Timed out pumping future in FakeAsync');
}
if (error != null) Error.throwWithStackTrace(error!, stack!);
return result;
}
Future<_TestEnv> _createEnv(WidgetTester tester) async {
if (_sharedEnv != null) {
final existing = _sharedEnv!;
final bookmarks = await _pumpFuture(
tester,
existing.connector.loadBookmarkedMessages(),
);
for (final bookmark in bookmarks) {
await _pumpFuture(
tester,
existing.connector.setBookmarkedMessage(bookmark, isBookmarked: false),
);
}
for (final channel in existing.connector.channels) {
for (final msg in existing.connector.getChannelMessages(channel)) {
if (msg.isBookmarked) {
await _pumpFuture(
tester,
existing.connector.setBookmarkedMessage(
BookmarkedMessage.fromChannel(
message: msg,
channelId: channel.storageId ?? 'slot:${channel.index}',
channelName: channel.name,
senderName: msg.senderName,
),
isBookmarked: false,
),
);
}
}
}
return existing;
}
late final StorageService storage;
late final MeshCoreConnector connector;
late final MessageRetryService retry;
late final AppSettingsService settings;
late final TranslationService translation;
late final UiViewStateService viewState;
await tester.runAsync(() async {
storage = StorageService();
connector = MeshCoreConnector();
retry = MessageRetryService();
settings = AppSettingsService();
translation = TranslationService(settings);
viewState = UiViewStateService();
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<void>.delayed(const Duration(milliseconds: 25));
}
await Future<void>.delayed(const Duration(milliseconds: 1200));
});
final providers = [
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: viewState),
Provider.value(value: storage),
ChangeNotifierProvider.value(
value: MapTileCacheService(appSettingsService: settings),
),
ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)),
ChangeNotifierProvider.value(value: ImageCodecService(settings)),
ChangeNotifierProvider.value(value: ReceivedImageStore()),
ChangeNotifierProvider.value(
value: NetworkMapUploadService(connector: connector, settings: settings),
),
];
Widget wrap(Widget home, {double textScale = 1.0}) {
return MultiProvider(
providers: providers,
child: MaterialApp(
key: UniqueKey(),
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)),
child: child!,
),
home: home,
),
);
}
return _sharedEnv = _TestEnv(connector: connector, wrap: wrap);
}
Future<void> _pumpFrames(WidgetTester tester, [int count = 8]) async {
for (var i = 0; i < count; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
Finder _segmentByText(String label) =>
find.byWidgetPredicate((w) => w is MeshSegmentLabel && w.text == label);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('bookmarks_screen_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
testWidgets(
'Contacts overflow menu includes Bookmarks after Discovered Contacts and opens BookmarksScreen',
(tester) async {
final env = await _createEnv(tester);
await tester.pumpWidget(env.wrap(const ContactsScreen()));
await _pumpFrames(tester);
await tester.tap(find.byIcon(Icons.more_vert));
await _pumpFrames(tester);
expect(find.text(_l10n.discoveredContacts_Title), findsOneWidget);
expect(find.text(_l10n.bookmarks_title), findsOneWidget);
await tester.tap(find.text(_l10n.bookmarks_title));
await _pumpFrames(tester);
expect(find.byType(BookmarksScreen), findsOneWidget);
// No split pill when opened from main Contacts screen.
expect(find.byType(SegmentedButton<bool>), findsNothing);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
},
);
testWidgets(
'ChannelChatScreen and ChatScreen overflow menus open BookmarksScreen with split pill filter',
(tester) async {
final env = await _createEnv(tester);
final channel = env.connector.channels.firstWhere(
(c) => c.name == 'Public',
);
final contact = env.connector.contacts.firstWhere(
(c) => c.name == 'Maya',
);
final channelBookmark = BookmarkedMessage(
sourceType: BookmarkSourceType.channel,
sourceId: channel.storageId ?? 'slot:${channel.index}',
sourceName: channel.name,
messageId: 'ch-msg-1',
senderName: 'Maya',
text: 'Public channel bookmarked note',
timestamp: DateTime(2026, 1, 1, 10),
receivedAt: DateTime(2026, 1, 1, 10),
isOutgoing: false,
);
final contactBookmark = BookmarkedMessage(
sourceType: BookmarkSourceType.contact,
sourceId: contact.publicKeyHex,
sourceName: contact.name,
messageId: 'dm-msg-1',
senderName: contact.name,
text: 'Direct message bookmarked note',
timestamp: DateTime(2026, 1, 1, 11),
receivedAt: DateTime(2026, 1, 1, 11),
isOutgoing: false,
);
await _pumpFuture(
tester,
env.connector.setBookmarkedMessage(channelBookmark, isBookmarked: true),
);
await _pumpFuture(
tester,
env.connector.setBookmarkedMessage(contactBookmark, isBookmarked: true),
);
// 1. Open from ChannelChatScreen
await tester.pumpWidget(env.wrap(ChannelChatScreen(channel: channel)));
await _pumpFrames(tester);
await tester.tap(find.byIcon(Icons.more_vert));
await _pumpFrames(tester);
expect(find.text(_l10n.bookmarks_title), findsOneWidget);
await tester.tap(find.text(_l10n.bookmarks_title));
await _pumpFrames(tester);
expect(find.byType(BookmarksScreen), findsOneWidget);
expect(find.byType(SegmentedButton<bool>), findsOneWidget);
expect(_segmentByText(_l10n.listFilter_all), findsOneWidget);
expect(_segmentByText('#Public'), findsOneWidget);
// Defaults to current channel's bookmarks only.
expect(find.text('Public channel bookmarked note'), findsOneWidget);
expect(find.text('Direct message bookmarked note'), findsNothing);
// Tap "All" segment to view all bookmarks across the app.
await tester.tap(_segmentByText(_l10n.listFilter_all));
await _pumpFrames(tester);
expect(find.text('Public channel bookmarked note'), findsOneWidget);
expect(find.text('Direct message bookmarked note'), findsOneWidget);
// Tap "#Public" segment to scope back to channel.
await tester.tap(_segmentByText('#Public'));
await _pumpFrames(tester);
expect(find.text('Public channel bookmarked note'), findsOneWidget);
expect(find.text('Direct message bookmarked note'), findsNothing);
// 2. Open from ChatScreen (contact DM)
await tester.pumpWidget(env.wrap(ChatScreen(contact: contact)));
await _pumpFrames(tester);
await tester.tap(find.byIcon(Icons.more_vert));
await _pumpFrames(tester);
expect(find.text(_l10n.bookmarks_title), findsOneWidget);
await tester.tap(find.text(_l10n.bookmarks_title));
await _pumpFrames(tester);
expect(find.byType(BookmarksScreen), findsOneWidget);
expect(_segmentByText(_l10n.listFilter_all), findsOneWidget);
expect(_segmentByText('Maya'), findsOneWidget);
expect(find.text('Direct message bookmarked note'), findsOneWidget);
expect(find.text('Public channel bookmarked note'), findsNothing);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
},
);
testWidgets(
'Search in BookmarksScreen finds matching bookmarks and jumping scrolls to and highlights offscreen target card',
(tester) async {
final env = await _createEnv(tester);
for (var i = 1; i <= 25; i++) {
final bookmark = BookmarkedMessage(
sourceType: i.isEven
? BookmarkSourceType.contact
: BookmarkSourceType.channel,
sourceId: i.isEven ? 'contact-1' : 'slot:0',
sourceName: i.isEven ? 'Maya' : 'Public',
messageId: 'm$i',
senderName: i.isEven ? 'Maya' : 'Sam',
text: i == 1
? 'Oldest offscreen solar telemetry beacon check #1'
: 'Recent repeater status update #$i',
timestamp: DateTime(2026, 1, 1, 9).add(Duration(minutes: i)),
receivedAt: DateTime(2026, 1, 1, 9).add(Duration(minutes: i)),
isOutgoing: false,
);
await _pumpFuture(
tester,
env.connector.setBookmarkedMessage(bookmark, isBookmarked: true),
);
}
await tester.pumpWidget(env.wrap(const BookmarksScreen()));
await _pumpFrames(tester);
// Reversed ListView opens at the newest bookmarks (offset 0), so the oldest (#1) is offscreen.
final scrollableState = tester.state<ScrollableState>(
find.byType(Scrollable),
);
expect(scrollableState.position.pixels, 0);
expect(
find.text('Oldest offscreen solar telemetry beacon check #1'),
findsNothing,
);
await tester.tap(find.byIcon(Icons.search));
await _pumpFrames(tester);
await tester.enterText(find.byType(TextField), 'solar');
await tester.pump(const Duration(milliseconds: 350));
await _pumpFrames(tester);
expect(
find.textContaining('Oldest offscreen solar telemetry beacon check #1'),
findsOneWidget,
);
expect(
find.textContaining('Recent repeater status update #25'),
findsNothing,
);
// Tap the search result to close search, scroll the restored list to the offscreen bookmark, and highlight it.
await tester.tap(
find.textContaining('Oldest offscreen solar telemetry beacon check #1'),
);
await _pumpFrames(tester, 12);
// Search field closed, list scrolled to the offscreen card, and AnimatedContainer highlight is active.
expect(find.byType(TextField), findsNothing);
final restoredScrollable = tester.state<ScrollableState>(
find.byType(Scrollable),
);
expect(restoredScrollable.position.pixels, greaterThan(0));
expect(
find.text('Oldest offscreen solar telemetry beacon check #1'),
findsOneWidget,
);
expect(find.byType(AnimatedContainer), findsOneWidget);
// Highlight clears after 2 seconds.
await tester.pump(const Duration(seconds: 3));
expect(find.byType(AnimatedContainer), findsNothing);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
},
);
testWidgets(
'Single removal and bulk removal in BookmarksScreen show confirmation AlertDialog',
(tester) async {
final env = await _createEnv(tester);
final b1 = BookmarkedMessage(
sourceType: BookmarkSourceType.channel,
sourceId: 'slot:0',
sourceName: 'Public',
messageId: 'm1',
senderName: 'Sam',
text: 'First bookmarked message',
timestamp: DateTime(2026, 1, 1, 9),
receivedAt: DateTime(2026, 1, 1, 9),
isOutgoing: false,
);
final b2 = BookmarkedMessage(
sourceType: BookmarkSourceType.channel,
sourceId: 'slot:0',
sourceName: 'Public',
messageId: 'm2',
senderName: 'Maya',
text: 'Second bookmarked message',
timestamp: DateTime(2026, 1, 1, 10),
receivedAt: DateTime(2026, 1, 1, 10),
isOutgoing: false,
);
final b3 = BookmarkedMessage(
sourceType: BookmarkSourceType.contact,
sourceId: 'contact-1',
sourceName: 'Maya',
messageId: 'm3',
senderName: 'Maya',
text: 'Third bookmarked message',
timestamp: DateTime(2026, 1, 1, 11),
receivedAt: DateTime(2026, 1, 1, 11),
isOutgoing: false,
);
await _pumpFuture(
tester,
env.connector.setBookmarkedMessage(b1, isBookmarked: true),
);
await _pumpFuture(
tester,
env.connector.setBookmarkedMessage(b2, isBookmarked: true),
);
await _pumpFuture(
tester,
env.connector.setBookmarkedMessage(b3, isBookmarked: true),
);
await tester.pumpWidget(env.wrap(const BookmarksScreen()));
await _pumpFrames(tester);
expect(find.text('Third bookmarked message'), findsOneWidget);
// 1. Single remove -> Cancel keeps bookmark intact.
await tester.tap(find.byIcon(Icons.bookmark_remove_outlined).first);
await _pumpFrames(tester);
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text(_l10n.bookmarks_removeConfirmTitle), findsOneWidget);
expect(find.text(_l10n.bookmarks_removeConfirmMessage), findsOneWidget);
await tester.tap(find.text(_l10n.common_cancel));
await _pumpFrames(tester);
expect(find.byType(AlertDialog), findsNothing);
expect(find.text('Third bookmarked message'), findsOneWidget);
// 2. Single remove -> Confirm removes bookmark.
await tester.tap(find.byIcon(Icons.bookmark_remove_outlined).first);
await _pumpFrames(tester);
await tester.tap(find.text(_l10n.common_remove));
await _pumpFrames(tester);
expect(find.text('Third bookmarked message'), findsNothing);
expect(find.text('Second bookmarked message'), findsOneWidget);
expect(find.text('First bookmarked message'), findsOneWidget);
// 3. Long-press to enter bulk selection mode and select both remaining bookmarks.
await tester.longPress(find.text('Second bookmarked message'));
await _pumpFrames(tester);
expect(find.text(_l10n.chat_selectedCount(1)), findsOneWidget);
await tester.tap(
find.text('First bookmarked message'),
warnIfMissed: false,
);
await _pumpFrames(tester);
expect(find.text(_l10n.chat_selectedCount(2)), findsOneWidget);
// Tap bulk delete icon -> Cancel keeps both bookmarks.
await tester.tap(find.byIcon(Icons.delete_outline));
await _pumpFrames(tester);
expect(find.byType(AlertDialog), findsOneWidget);
expect(
find.text(_l10n.bookmarks_removeSelectedConfirmTitle),
findsOneWidget,
);
expect(
find.text(_l10n.bookmarks_removeSelectedConfirmMessage(2)),
findsOneWidget,
);
await tester.tap(find.text(_l10n.common_cancel));
await _pumpFrames(tester);
expect(find.text('Second bookmarked message'), findsOneWidget);
expect(find.text('First bookmarked message'), findsOneWidget);
// Tap bulk delete icon -> Confirm removes selected bookmarks.
await tester.tap(find.byIcon(Icons.delete_outline));
await _pumpFrames(tester);
await tester.tap(find.text(_l10n.common_remove));
await _pumpFrames(tester);
expect(find.text(_l10n.bookmarks_empty), findsOneWidget);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
},
);
testWidgets(
'ChannelChatScreen bulk selection bookmarks selected messages and in-chat remove prompts for confirmation',
(tester) async {
final env = await _createEnv(tester);
final channel = env.connector.channels.firstWhere(
(c) => c.name == 'Hiking Group',
);
await tester.pumpWidget(env.wrap(ChannelChatScreen(channel: channel)));
await _pumpFrames(tester);
final messages = env.connector.getChannelMessages(channel);
expect(messages.length, greaterThanOrEqualTo(2));
final firstMsg = messages[messages.length - 1];
final secondMsg = messages[messages.length - 2];
Future<void> longPressBubble(String text) async {
final bubble = find.ancestor(
of: find.text(text),
matching: find.byType(MessageBubbleFrame),
);
await tester.longPressAt(
tester.getTopLeft(bubble) + const Offset(8, 8),
);
await _pumpFrames(tester);
}
// Long-press newest message to open action sheet -> Select messages
await longPressBubble(firstMsg.text);
await tester.tap(find.text(_l10n.chat_selectMessages));
await _pumpFrames(tester);
// Select second message too
await tester.tap(find.text(secondMsg.text), warnIfMissed: false);
await _pumpFrames(tester);
expect(find.text(_l10n.chat_selectedCount(2)), findsOneWidget);
// Tap bulk Bookmark action in selection AppBar
final bookmarkBtn = find.byTooltip(_l10n.chat_bookmark);
expect(bookmarkBtn, findsOneWidget);
await tester.tap(bookmarkBtn);
await _pumpFrames(tester);
final saved = await _pumpFuture(
tester,
env.connector.loadBookmarkedMessages(),
);
expect(saved, hasLength(2));
// Now long-press the bookmarked message in ChannelChatScreen and tap "Remove bookmark"
await longPressBubble(firstMsg.text);
expect(find.text(_l10n.chat_removeBookmark), findsOneWidget);
await tester.tap(find.text(_l10n.chat_removeBookmark));
await _pumpFrames(tester);
// Confirmation dialog appears
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text(_l10n.bookmarks_removeConfirmTitle), findsOneWidget);
// Cancel keeps it bookmarked
await tester.tap(find.text(_l10n.common_cancel));
await _pumpFrames(tester);
expect(
await _pumpFuture(tester, env.connector.loadBookmarkedMessages()),
hasLength(2),
);
// Confirm removes the bookmark
await longPressBubble(firstMsg.text);
await tester.tap(find.text(_l10n.chat_removeBookmark));
await _pumpFrames(tester);
await tester.tap(find.text(_l10n.common_remove));
await _pumpFrames(tester);
expect(
await _pumpFuture(tester, env.connector.loadBookmarkedMessages()),
hasLength(1),
);
// Also verify ChatScreen (direct message) bookmark removal confirmation dialog
final contact = env.connector.contacts.firstWhere(
(c) => c.name == 'Maya',
);
await tester.pumpWidget(env.wrap(ChatScreen(contact: contact)));
await _pumpFrames(tester);
final dmMessages = env.connector.getMessages(contact);
expect(dmMessages, isNotEmpty);
final dmMsg = dmMessages.last;
// Bookmark the DM first
await longPressBubble(dmMsg.text);
await tester.tap(find.text(_l10n.chat_bookmark));
await _pumpFrames(tester);
expect(
await _pumpFuture(tester, env.connector.loadBookmarkedMessages()),
hasLength(2),
);
// Long-press and tap Remove bookmark -> Cancel keeps it
await longPressBubble(dmMsg.text);
await tester.tap(find.text(_l10n.chat_removeBookmark));
await _pumpFrames(tester);
expect(find.byType(AlertDialog), findsOneWidget);
await tester.tap(find.text(_l10n.common_cancel));
await _pumpFrames(tester);
expect(
await _pumpFuture(tester, env.connector.loadBookmarkedMessages()),
hasLength(2),
);
// Confirm removes it
await longPressBubble(dmMsg.text);
await tester.tap(find.text(_l10n.chat_removeBookmark));
await _pumpFrames(tester);
await tester.tap(find.text(_l10n.common_remove));
await _pumpFrames(tester);
expect(
await _pumpFuture(tester, env.connector.loadBookmarkedMessages()),
hasLength(1),
);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
},
);
group('BookmarksScreen fits 320dp at 1.3x and 2.0x text scale', () {
for (final scale in [1.3, 2.0]) {
testWidgets('no layout overflow at 320dp and ${scale}x text scale', (
tester,
) async {
tester.view.physicalSize = const Size(320, 568);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
final env = await _createEnv(tester);
final channel = env.connector.channels.firstWhere(
(c) => c.name == 'Hiking Group',
);
await _pumpFuture(
tester,
env.connector.setBookmarkedMessage(
BookmarkedMessage(
sourceType: BookmarkSourceType.channel,
sourceId: channel.storageId ?? 'slot:${channel.index}',
sourceName: channel.name,
messageId: 'scale-msg-1',
senderName: 'Ranger Pat',
text:
'Checking layout on 320dp screen with large text scale enabled.',
timestamp: DateTime(2026, 1, 1, 12),
receivedAt: DateTime(2026, 1, 1, 12),
isOutgoing: false,
),
isBookmarked: true,
),
);
final overflows = <String>[];
final previous = FlutterError.onError;
FlutterError.onError = (details) {
final text = details.exceptionAsString();
if (!text.contains('overflowed')) {
previous?.call(details);
return;
}
overflows.add(text.split('\n').first);
};
addTearDown(() => FlutterError.onError = previous);
await tester.pumpWidget(
env.wrap(
BookmarksScreen(
initialSourceType: BookmarkSourceType.channel,
initialSourceId: channel.storageId ?? 'slot:${channel.index}',
sourceIdAliases: [?channel.storageId, 'slot:${channel.index}'],
initialSourceName: '#${channel.name}',
),
textScale: scale,
),
);
await _pumpFrames(tester);
// Enter bulk selection mode and open remove confirmation dialog at scale
await tester.longPress(
find.textContaining('Checking layout on 320dp screen'),
);
await _pumpFrames(tester);
await tester.tap(find.byIcon(Icons.delete_outline));
await _pumpFrames(tester);
await tester.tap(find.text(_l10n.common_cancel));
await _pumpFrames(tester);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(minutes: 1));
FlutterError.onError = previous;
expect(overflows, isEmpty, reason: overflows.join('\n'));
});
}
});
}
@@ -0,0 +1,627 @@
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: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/contact.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/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';
/// Multi-select in channels, direct chats and rooms: taps must register
/// within 250 ms (no double-tap recognizer may hold them back), and direct
/// and room chats offer the same bulk actions as channels.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('bulk_selection_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
setUp(() {
clipboard = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.setData') {
clipboard = (call.arguments as Map)['text'] as String?;
}
return null;
});
});
testWidgets('direct and room chats: bulk bookmark saves every selected '
'message', (tester) async {
// One test for both: a bookmark write started in fake time only finishes
// inside that test, and the next write queues behind it.
for (final room in [false, true]) {
final p = room ? 'room' : 'dm';
_view(tester, const Size(400, 800));
final (connector, chat) = await _pumpChat(tester, room: room);
// Room posts name their author by key prefix; the bookmark must carry
// that author's name, not the room server's.
final authors = connector.contacts
.where((c) => c.type == advTypeChat)
.take(2)
.toList();
final posts = ['by author one', 'by author two'];
if (room) {
expect(authors, hasLength(2));
for (var i = 0; i < 2; i++) {
connector.handleFrameForTest(
_roomPost(chat, authors[i], posts[i], _stamp++),
);
}
await _settle(tester);
}
await _enterChatSelection(tester, '$p 8');
await tester.tap(
find.textContaining('$p 9', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
if (room) {
for (final post in posts) {
await tester.tap(
find.textContaining(post, findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
}
}
await tester.tap(find.byTooltip('Bookmark'));
await _settle(tester);
// Bookmarks are stored per radio in the preferences; the writes
// started in fake time need real time to finish.
final prefs = PrefsManager.instance;
String stored() => [
for (final key in prefs.getKeys())
if (key.startsWith('message_bookmarks_')) prefs.getString(key) ?? '',
].join();
for (
var i = 0;
i < 200 && !stored().contains(room ? posts[1] : '$p 9');
i++
) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 50)),
);
await tester.pump(const Duration(milliseconds: 50));
}
final saved = stored();
expect(saved, contains('"text":"$p 8"'));
expect(saved, contains('"text":"$p 9"'));
expect(saved, isNot(contains('"text":"$p 7"')));
if (room) {
for (var i = 0; i < 2; i++) {
final entry = RegExp(
'\\{[^{}]*"text":"${posts[i]}"[^{}]*\\}',
).firstMatch(saved)?.group(0);
expect(entry, isNotNull, reason: 'missing ${posts[i]}');
expect(entry, contains('"senderName":"${authors[i].name}"'));
expect(entry, isNot(contains('"senderName":"${chat.name}"')));
}
}
expect(find.textContaining('selected'), findsNothing);
await tester.pumpWidget(const SizedBox());
}
await _tearDown(tester);
});
group('instant selection taps', () {
testWidgets('channel: a tap selects within 250 ms and two taps 100 ms '
'apart both select', (tester) async {
_view(tester, const Size(400, 800));
await _pumpChannel(tester);
await _enterChannelSelection(tester);
expect(find.text('1 selected'), findsOneWidget);
await tester.tap(
find.textContaining('History 38', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 100));
await tester.tap(
find.textContaining('History 37', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
expect(find.text('3 selected'), findsOneWidget);
expect(find.byIcon(Icons.check_circle), findsNWidgets(3));
// A lone tap needs no extra time either.
await tester.tap(
find.textContaining('History 36', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
expect(find.byIcon(Icons.check_circle), findsNWidgets(4));
await _tearDown(tester);
});
testWidgets('channel: a single frame after the tap already shows it', (
tester,
) async {
_view(tester, const Size(400, 800));
await _pumpChannel(tester);
await _enterChannelSelection(tester);
await tester.tap(
find.textContaining('History 38', findRichText: true),
warnIfMissed: false,
);
await tester.pump();
expect(find.byIcon(Icons.check_circle), findsNWidgets(2));
await _tearDown(tester);
});
testWidgets('direct chat: taps select within 250 ms', (tester) async {
_view(tester, const Size(400, 800));
final dm = await _pumpChat(tester, room: false);
await _enterChatSelection(tester, 'dm 9');
await tester.tap(
find.textContaining('dm 8', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 100));
await tester.tap(
find.textContaining('dm 7', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
expect(find.text('3 selected'), findsOneWidget);
expect(find.byIcon(Icons.check_circle), findsNWidgets(3));
expect(dm.$1.getMessages(dm.$2), isNotEmpty);
await _tearDown(tester);
});
testWidgets('room chat: taps select within 250 ms', (tester) async {
_view(tester, const Size(400, 800));
await _pumpChat(tester, room: true);
await _enterChatSelection(tester, 'room 9');
await tester.tap(
find.textContaining('room 8', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 100));
await tester.tap(
find.textContaining('room 7', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
expect(find.text('3 selected'), findsOneWidget);
await _tearDown(tester);
});
testWidgets('long press on a row toggles it while selecting', (
tester,
) async {
_view(tester, const Size(400, 800));
await _pumpChat(tester, room: false);
await _enterChatSelection(tester, 'dm 9');
await tester.longPress(
find.textContaining('dm 8', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
expect(find.text('2 selected'), findsOneWidget);
await tester.longPress(
find.textContaining('dm 8', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
expect(find.text('1 selected'), findsOneWidget);
await _tearDown(tester);
});
});
for (final room in [false, true]) {
final name = room ? 'room chat' : 'direct chat';
final p = room ? 'room' : 'dm';
group('$name bulk actions', () {
testWidgets('back clears the selection instead of leaving', (
tester,
) async {
_view(tester, const Size(400, 800));
await _pumpChat(tester, room: room);
await _enterChatSelection(tester, '$p 9');
await tester.tap(
find.textContaining('$p 8', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
expect(find.text('2 selected'), findsOneWidget);
await tester.binding.handlePopRoute();
await tester.pump(const Duration(milliseconds: 250));
expect(find.textContaining('selected'), findsNothing);
expect(find.byType(ChatScreen), findsOneWidget);
await _tearDown(tester);
});
testWidgets('copy puts the selected messages oldest first', (
tester,
) async {
_view(tester, const Size(400, 800));
await _pumpChat(tester, room: room);
await _enterChatSelection(tester, '$p 8');
await tester.tap(
find.textContaining('$p 5', findRichText: true),
warnIfMissed: false,
);
await tester.tap(
find.textContaining('$p 9', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
await tester.tap(find.byTooltip('Copy'));
await tester.pump(const Duration(milliseconds: 250));
expect(clipboard, '$p 5\n$p 8\n$p 9');
expect(find.textContaining('selected'), findsNothing);
await _tearDown(tester);
});
testWidgets('delete asks first, then removes the selected messages', (
tester,
) async {
_view(tester, const Size(400, 800));
final (connector, contact) = await _pumpChat(tester, room: room);
await _enterChatSelection(tester, '$p 8');
await tester.tap(
find.textContaining('$p 9', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
await tester.tap(find.byTooltip('Delete'));
await tester.pump(const Duration(milliseconds: 250));
expect(
find.text('Delete 2 messages from this device?'),
findsOneWidget,
);
await tester.tap(find.text('Delete'));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pump(const Duration(milliseconds: 250));
final texts = connector.getMessages(contact).map((m) => m.text);
expect(texts, isNot(contains('$p 8')));
expect(texts, isNot(contains('$p 9')));
expect(texts, contains('$p 7'));
await _tearDown(tester);
});
testWidgets('resend confirms, cancel does nothing, confirm resends', (
tester,
) async {
_view(tester, const Size(400, 800));
final (connector, contact) = await _pumpChat(
tester,
room: room,
outgoing: true,
);
List<String> ids() => [
for (final m in connector.getMessages(contact))
if (m.isOutgoing) m.messageId,
];
final before = ids();
expect(before, hasLength(2));
await _enterChatSelection(tester, '$p out 1');
await tester.tap(
find.textContaining('$p out 2', findRichText: true),
warnIfMissed: false,
);
await tester.pump(const Duration(milliseconds: 250));
await tester.tap(find.byTooltip('Resend'));
await tester.pump(const Duration(milliseconds: 250));
expect(
find.text('Resend 2 selected outgoing messages to this contact?'),
findsOneWidget,
);
await tester.tap(find.text('Cancel'));
await tester.pump(const Duration(milliseconds: 250));
expect(ids(), before);
expect(find.text('2 selected'), findsOneWidget);
await tester.tap(find.byTooltip('Resend'));
await tester.pump(const Duration(milliseconds: 250));
await tester.tap(find.widgetWithText(FilledButton, 'Resend'));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 300)),
);
await tester.pump(const Duration(milliseconds: 250));
final after = ids();
expect(after, hasLength(2));
expect(after, isNot(before));
expect(find.textContaining('selected'), findsNothing);
await _tearDown(tester);
});
});
}
group('no overflow at 320 dp', () {
for (final scale in [1.3, 2.0]) {
testWidgets('channel selection bar at ${scale}x text', (tester) async {
_view(tester, const Size(320, 700));
await _pumpChannel(tester, textScale: scale);
await _enterChannelSelection(tester);
await tester.tap(find.byIcon(Icons.radio_button_unchecked).first);
await tester.pump(const Duration(milliseconds: 250));
expect(tester.takeException(), isNull);
await _tearDown(tester);
});
testWidgets('direct chat selection bar at ${scale}x text', (
tester,
) async {
_view(tester, const Size(320, 700));
await _pumpChat(tester, room: false, outgoing: true, textScale: scale);
await _enterChatSelection(tester, 'dm out 2');
expect(find.byTooltip('Resend'), findsOneWidget);
expect(find.byTooltip('Delete'), findsOneWidget);
expect(tester.takeException(), isNull);
await _tearDown(tester);
});
}
});
}
/// A room-server post: a signed contact message whose 4-byte "signature" is
/// the author's public key prefix.
Uint8List _roomPost(Contact room, Contact author, String text, int stamp) {
final writer = BufferWriter();
writer.writeByte(respCodeContactMsgRecvV3);
writer.writeByte(24);
writer.writeByte(0);
writer.writeByte(0);
writer.writeBytes(Uint8List.fromList(room.publicKey.sublist(0, 6)));
writer.writeByte(0xFF);
writer.writeByte(txtTypeSigned);
writer.writeUInt32LE(stamp);
writer.writeBytes(Uint8List.fromList(author.publicKey.sublist(0, 4)));
writer.writeString(text);
writer.writeByte(0);
return writer.toBytes();
}
String? clipboard;
void _view(WidgetTester tester, Size size) {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
}
Future<void> _settle(WidgetTester tester) async {
for (var i = 0; i < 10; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
Future<void> _tearDown(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox());
// Let writes started during the test finish, so they cannot stall the
// next test's preferences writes.
for (var i = 0; i < 20; i++) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 25)),
);
await tester.pump(const Duration(milliseconds: 25));
}
await tester.pump(const Duration(minutes: 1));
}
/// Opens the message action sheet for the message showing [text] (by calling
/// its long-press handler: a real long press on bubble text starts text
/// selection in tests) and picks "Select messages".
Future<void> _enterSelectionFrom(WidgetTester tester, Finder message) async {
// The row's long-press detector wraps the bubble, so it is an ancestor of
// the message text whatever the text scale.
final detector = find
.ancestor(
of: message.first,
matching: find.byWidgetPredicate(
(w) => w is GestureDetector && w.onLongPress != null,
),
)
.first
.evaluate()
.single;
(detector.widget as GestureDetector).onLongPress!();
await _settle(tester);
await tester.ensureVisible(find.text('Select messages'));
await tester.pump();
await tester.tap(find.text('Select messages'));
await _settle(tester);
}
Future<void> _enterChannelSelection(WidgetTester tester) => _enterSelectionFrom(
tester,
find.textContaining('History 39', findRichText: true),
);
Future<void> _enterChatSelection(WidgetTester tester, String text) =>
_enterSelectionFrom(tester, find.textContaining(text, findRichText: true));
(MeshCoreConnector, List<SingleChildWidget>)? _shared;
Widget _app(List<SingleChildWidget> providers, Widget home, double textScale) =>
MultiProvider(
providers: providers,
child: MaterialApp(
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)),
child: child!,
),
home: home,
),
);
var _stamp = DateTime.now().millisecondsSinceEpoch ~/ 1000 - 100000;
Future<MeshCoreConnector> _pumpChannel(
WidgetTester tester, {
double textScale = 1.0,
}) async {
final (connector, providers) = _shared ??= await _connect(tester);
final channel = connector.channels[0];
if (connector.getChannelMessages(channel).length < 40) {
for (var i = 0; i < 40; i++) {
connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: channel.index,
sender: 'Alice',
message: 'History $i',
timestampSecs: _stamp + i * 60,
),
);
}
}
await tester.pumpWidget(
_app(providers, ChannelChatScreen(channel: channel), textScale),
);
await _settle(tester);
return connector;
}
/// Shows a direct chat (or the review radio's room) holding ten incoming
/// messages "dm 0".."dm 9" / "room 0".."room 9", plus two outgoing ones when
/// [outgoing].
Future<(MeshCoreConnector, Contact)> _pumpChat(
WidgetTester tester, {
required bool room,
bool outgoing = false,
double textScale = 1.0,
bool fresh = false,
}) async {
final (connector, providers) = fresh
? await _connect(tester)
: (_shared ??= await _connect(tester));
final contact = connector.contacts.firstWhere(
(c) => room ? c.type == advTypeRoom : c.type == advTypeChat,
);
final p = room ? 'room' : 'dm';
connector.clearMessagesForContact(contact);
await tester.runAsync(() => connector.flushPendingWrites());
for (var i = 0; i < 10; i++) {
connector.handleFrameForTest(
ReviewFrames.contactMessage(
senderPublicKey: contact.publicKey,
text: '$p $i',
timestampSecs: _stamp++,
),
);
}
if (outgoing) {
await tester.runAsync(() async {
await connector.sendMessage(contact, '$p out 1');
await connector.sendMessage(contact, '$p out 2');
});
}
connector.markContactRead(contact.publicKeyHex);
await tester.pumpWidget(
_app(providers, ChatScreen(contact: contact), textScale),
);
await _settle(tester);
return (connector, contact);
}
Future<(MeshCoreConnector, List<SingleChildWidget>)> _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.any((c) => c.type == advTypeRoom) ||
!connector.contacts.any((c) => c.type == advTypeChat) ||
connector.channels.length < 2) &&
DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
await Future<void>.delayed(const Duration(milliseconds: 500));
});
expect(connector.channels.length, greaterThanOrEqualTo(2));
return (
connector,
<SingleChildWidget>[
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()),
],
);
}
@@ -0,0 +1,265 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/screens/chat_compression_screen.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
final _profiles = [
Cyr2LatProfile(id: 'ru', name: 'Russian', charMap: const {'А': 'A'}),
Cyr2LatProfile(id: 'sr', name: 'Serbian', charMap: const {'З': '3'}),
];
/// Stands in for a chat screen: keeps the "saved" state and applies a change
/// only when the test completes the pending write.
class _Host extends ChangeNotifier {
ChatCompressionMode mode;
String? profileId;
final bool enabled;
final List<ChatCompressionMode> modeCalls = [];
final List<String> profileCalls = [];
final List<Completer<void>> pending = [];
_Host({
this.mode = ChatCompressionMode.off,
this.enabled = true,
this.profileId,
});
ChatCompressionState read() => ChatCompressionState(
mode: mode,
enabled: enabled,
disabledReason: enabled ? null : _l10n.chatCompression_noStorageId,
profiles: _profiles,
profileId: profileId,
defaultProfileId: 'ru',
);
Future<void> _write(void Function() apply) async {
final completer = Completer<void>();
pending.add(completer);
await completer.future;
apply();
notifyListeners();
}
Future<void> setMode(ChatCompressionMode m) {
modeCalls.add(m);
return _write(() => mode = m);
}
Future<void> setProfile(String id) {
profileCalls.add(id);
return _write(() => profileId = id);
}
}
void main() {
late _Host host;
Future<void> pumpPage(
WidgetTester tester, {
ChatCompressionMode mode = ChatCompressionMode.off,
bool enabled = true,
String? profileId,
Size size = const Size(400, 800),
double textScale = 1.0,
}) async {
host = _Host(mode: mode, enabled: enabled, profileId: profileId);
addTearDown(host.dispose);
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: ChatCompressionScreen(
listenable: host,
read: host.read,
onModeChanged: host.setMode,
onProfileChanged: host.setProfile,
),
),
);
}
Finder optionRow(String label) =>
find.ancestor(of: find.text(label), matching: find.byType(ListTile));
bool isSelected(String label) {
return find
.descendant(
of: optionRow(label),
matching: find.byIcon(Icons.radio_button_checked),
)
.evaluate()
.isNotEmpty;
}
testWidgets(
'lists the three modes with short notes and marks the saved one',
(tester) async {
await pumpPage(tester, mode: ChatCompressionMode.smaz);
expect(find.text(_l10n.chatCompression_title), findsWidgets);
expect(find.text(_l10n.chatCompression_off), findsOneWidget);
expect(find.text(_l10n.chatCompression_smaz), findsOneWidget);
expect(find.text(_l10n.chatCompression_cyr2lat), findsOneWidget);
expect(find.text(_l10n.chatCompression_offDescription), findsOneWidget);
expect(find.text(_l10n.chatCompression_smazDescription), findsOneWidget);
expect(
find.text(_l10n.chatCompression_cyr2latDescription),
findsOneWidget,
);
expect(isSelected(_l10n.chatCompression_smaz), isTrue);
expect(isSelected(_l10n.chatCompression_off), isFalse);
expect(find.text(_l10n.chatCompression_profile), findsNothing);
for (final mode in [
_l10n.chatCompression_off,
_l10n.chatCompression_smaz,
_l10n.chatCompression_cyr2lat,
]) {
expect(
tester.getSize(optionRow(mode)).height,
greaterThanOrEqualTo(48),
reason: mode,
);
}
},
);
testWidgets('a choice shows only after it is saved', (tester) async {
await pumpPage(tester);
await tester.tap(find.text(_l10n.chatCompression_smaz));
await tester.pump();
expect(host.modeCalls, [ChatCompressionMode.smaz]);
// Still saving: old mode shown, options locked against rapid taps.
expect(isSelected(_l10n.chatCompression_off), isTrue);
expect(
tester.widget<ListTile>(optionRow(_l10n.chatCompression_cyr2lat)).enabled,
isFalse,
);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
expect(host.modeCalls, [ChatCompressionMode.smaz]);
host.pending.single.complete();
await tester.pumpAndSettle();
expect(isSelected(_l10n.chatCompression_smaz), isTrue);
expect(isSelected(_l10n.chatCompression_off), isFalse);
expect(
tester.widget<ListTile>(optionRow(_l10n.chatCompression_cyr2lat)).enabled,
isTrue,
);
});
testWidgets('Cyr2Lat reveals the profile picker', (tester) async {
await pumpPage(tester);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
host.pending.removeAt(0).complete();
await tester.pumpAndSettle();
expect(isSelected(_l10n.chatCompression_cyr2lat), isTrue);
expect(find.text(_l10n.chatCompression_profile), findsWidgets);
// No profile saved for the chat: the app-wide one is what sending uses.
expect(find.text('Russian'), findsOneWidget);
await tester.tap(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Serbian').last);
await tester.pump();
expect(host.profileCalls, ['sr']);
host.pending.removeAt(0).complete();
await tester.pumpAndSettle();
expect(find.text('Serbian'), findsOneWidget);
});
testWidgets('a failed save keeps the saved mode and says so', (tester) async {
await pumpPage(tester, mode: ChatCompressionMode.smaz);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
host.pending.single.completeError(StateError('disk full'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_saveFailed), findsOneWidget);
expect(isSelected(_l10n.chatCompression_smaz), isTrue);
expect(isSelected(_l10n.chatCompression_cyr2lat), isFalse);
expect(
tester.widget<ListTile>(optionRow(_l10n.chatCompression_off)).enabled,
isTrue,
);
});
testWidgets('a failed profile save shows the saved profile again', (
tester,
) async {
await pumpPage(tester, mode: ChatCompressionMode.cyr2lat, profileId: 'ru');
await tester.tap(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Serbian').last);
await tester.pump();
expect(host.profileCalls, ['sr']);
host.pending.single.completeError(StateError('disk full'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_saveFailed), findsOneWidget);
await tester.scrollUntilVisible(find.text('Russian'), 100);
expect(find.text('Russian'), findsOneWidget);
expect(find.text('Serbian'), findsNothing);
});
testWidgets('disabled shows the saved mode, says why and allows no change', (
tester,
) async {
await pumpPage(tester, mode: ChatCompressionMode.smaz, enabled: false);
expect(find.text(_l10n.chatCompression_noStorageId), findsOneWidget);
expect(isSelected(_l10n.chatCompression_smaz), isTrue);
for (final mode in [
_l10n.chatCompression_off,
_l10n.chatCompression_smaz,
_l10n.chatCompression_cyr2lat,
]) {
expect(tester.widget<ListTile>(optionRow(mode)).enabled, isFalse);
}
await tester.tap(find.text(_l10n.chatCompression_off), warnIfMissed: false);
await tester.pumpAndSettle();
expect(host.modeCalls, isEmpty);
});
for (final scale in [1.3, 2.0]) {
testWidgets('fits a 320dp phone at ${scale}x text', (tester) async {
await pumpPage(
tester,
mode: ChatCompressionMode.cyr2lat,
size: const Size(320, 568),
textScale: scale,
);
expect(tester.takeException(), isNull);
// The page scrolls to its last option and the profile picker.
await tester.scrollUntilVisible(
find.byType(DropdownButtonFormField<String>),
200,
scrollable: find.byType(Scrollable).first,
);
expect(tester.takeException(), isNull);
});
}
}
+150
View File
@@ -0,0 +1,150 @@
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gpx/gpx.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/helpers/message_url_image_helper.dart';
import 'package:meshcore_open/models/bookmarked_message.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/services/translation_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/utils/bookmark_markdown_export.dart';
import 'package:meshcore_open/utils/gpx_export.dart';
// The Export page's data: which contacts each GPX option picks and what the
// file holds, and bookmarks round-tripping into the Markdown export. Uses the
// review-mode radio's sample contacts and messages.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('export_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
late MeshCoreConnector connector;
// Created here, outside any test's fake time, so its futures always run.
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
final settings = AppSettingsService();
await settings.loadSettings();
connector = MeshCoreConnector()
..initialize(
retryService: MessageRetryService(),
pathHistoryService: PathHistoryService(StorageService()),
appSettingsService: settings,
translationService: TranslationService(settings),
)
..reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while (connector.selfName == null && DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
Set<String> names(Iterable<ContactExport> contacts) =>
contacts.map((c) => c.name).toSet();
test('GPX: repeaters and rooms, users / companions, all contacts', () async {
final located = connector.allContacts
.where((c) => c.latitude != null && c.longitude != null)
.toList();
Set<String> expected(bool Function(int type) keep) =>
located.where((c) => keep(c.type)).map((c) => c.name.trim()).toSet();
final repeaters = GpxExport(connector)..addRepeaters();
expect(
names(repeaters.contacts),
expected((t) => t == advTypeRepeater || t == advTypeRoom),
);
expect(
names(repeaters.contacts),
containsAll(['Hilltop Repeater', 'Trailhead Room']),
);
final users = GpxExport(connector)..addContacts();
expect(names(users.contacts), expected((t) => t == advTypeChat));
expect(names(users.contacts), contains('Maya'));
expect(names(users.contacts), isNot(contains('Hilltop Repeater')));
final all = GpxExport(connector)..addAll();
expect(names(all.contacts), expected((_) => true));
expect(
all.contacts.length,
repeaters.contacts.length + users.contacts.length,
);
// One waypoint per contact with its name, position, type, public key and
// meshcore:// link.
final xml = all.buildGpx('All contacts', 'Locations');
final gpx = GpxReader().fromString(xml);
expect(gpx.metadata?.name, 'All contacts');
expect(gpx.wpts, hasLength(located.length));
for (final c in located) {
final wpt = gpx.wpts.singleWhere((w) => w.name == c.name.trim());
expect(wpt.lat, closeTo(c.latitude!, 1e-9));
expect(wpt.lon, closeTo(c.longitude!, 1e-9));
expect(wpt.desc, contains(c.publicKeyHex));
expect(wpt.desc, contains(c.typeLabelRaw));
if (c.rawPacket != null) expect(xml, contains('meshcore://'));
}
// Nothing selected: "no contacts", and no file is written.
expect(
await GpxExport(connector).exportGPX('n', 'd', 'f', 't', 's'),
gpxExportNoContacts,
);
});
test('Bookmarks: a bookmarked message is found and exported', () async {
final previous = MessageUrlImageHelper.loadLinkImages.value;
MessageUrlImageHelper.loadLinkImages.value = false;
addTearDown(() => MessageUrlImageHelper.loadLinkImages.value = previous);
final contact = connector.contacts.firstWhere(
(c) => connector.getMessages(c).any((m) => m.text.isNotEmpty),
);
final message = connector
.getMessages(contact)
.firstWhere((m) => m.text.isNotEmpty);
final bookmark = BookmarkedMessage.fromContact(
message: message,
contactKey: contact.publicKeyHex,
contactName: contact.name,
senderName: contact.name,
);
await connector.setBookmarkedMessage(bookmark, isBookmarked: true);
final saved = await connector.loadBookmarkedMessages();
expect(saved.map((b) => b.messageId), contains(message.messageId));
final markdown = await buildBookmarksMarkdown(
saved,
publicGateway: '',
exportedAt: DateTime(2026, 11, 23),
);
expect(markdown, contains(contact.name));
expect(markdown, contains(message.text));
await connector.setBookmarkedMessage(bookmark, isBookmarked: false);
final after = await connector.loadBookmarkedMessages();
expect(after.map((b) => b.messageId), isNot(contains(message.messageId)));
});
}
@@ -373,6 +373,7 @@ void main() {
expect(_openMenuEntries(tester), [
_l10n.addContact_title,
_l10n.discoveredContacts_Title,
_l10n.bookmarks_title,
'---',
_l10n.contacts_zeroHopAdvert,
_l10n.contacts_floodAdvert,
@@ -387,6 +388,7 @@ void main() {
_menuItemByLabel(_l10n.discoveredContacts_Title).enabled,
isTrue,
);
expect(_menuItemByLabel(_l10n.bookmarks_title).enabled, isTrue);
expect(
_menuItemByLabel(_l10n.contacts_zeroHopAdvert).enabled,
connected,
@@ -57,7 +57,7 @@ void main() {
testWidgets('renders every section with defaults', (tester) async {
await pumpScreen(tester);
expect(find.text('Message filter'), findsOneWidget);
expect(find.text('Message Filter'), findsOneWidget);
expect(find.text('Filter messages'), findsOneWidget);
expect(find.text('Show a small placeholder'), findsOneWidget);
expect(find.text('Hide completely'), findsOneWidget);
+31 -26
View File
@@ -42,9 +42,8 @@ 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/chat_background.dart';
import 'package:meshcore_open/widgets/chat_composer.dart';
import 'package:meshcore_open/widgets/chat_compression_selector.dart';
import 'package:meshcore_open/screens/chat_compression_screen.dart';
import 'package:meshcore_open/widgets/connect_sheet.dart';
final _radioKey = Uint8List.fromList(List<int>.generate(32, (i) => 0xA0 + i));
@@ -349,10 +348,18 @@ void main() {
await tester.pump(const Duration(minutes: 1));
});
group('compression selector', () {
Future<void> choose(WidgetTester tester, String mode) async {
await tester.tap(find.byType(ChatCompressionSelector));
group('compression menu item', () {
Future<void> openMenu(WidgetTester tester) async {
await tester.tap(find.byIcon(Icons.more_vert));
await _settle(tester);
}
/// Opens the page from the overflow menu, picks [mode], and returns.
Future<void> choose(WidgetTester tester, String mode) async {
await openMenu(tester);
await tester.tap(find.textContaining('${_l10n.chatCompression_title}:'));
await _settle(tester);
expect(find.byType(ChatCompressionScreen), findsOneWidget);
await tester.tap(find.text(mode));
await _settle(tester);
// Connector notifications are debounced on a real timer.
@@ -360,9 +367,11 @@ void main() {
() => Future<void>.delayed(const Duration(milliseconds: 200)),
);
await _settle(tester);
await tester.pageBack();
await _settle(tester);
}
testWidgets('DM chat shows it at the top and saves offline', (
testWidgets('DM chat shows it in the menu and saves offline', (
tester,
) async {
final connector = await _offlineConnector(tester);
@@ -373,32 +382,27 @@ void main() {
);
await _settle(tester);
expect(find.byType(ChatCompressionSelector), findsOneWidget);
// No strip above the transcript any more.
expect(find.byType(ChatCompressionScreen), findsNothing);
expect(find.text(_l10n.chatCompression_label('Off')), findsNothing);
await openMenu(tester);
expect(find.text(_l10n.chatCompression_label('Off')), findsOneWidget);
// Above the transcript, outside its scroll view.
expect(
find.ancestor(
of: find.byType(ChatCompressionSelector),
matching: find.byType(Scrollable),
),
findsNothing,
);
expect(
tester.getBottomLeft(find.byType(ChatCompressionSelector)).dy,
lessThanOrEqualTo(tester.getTopLeft(find.byType(ChatBackdrop)).dy),
);
expect(find.byIcon(Icons.compress), findsOneWidget);
await tester.tapAt(const Offset(1, 1));
await _settle(tester);
await choose(tester, _l10n.chatCompression_smaz);
await openMenu(tester);
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
await tester.tapAt(const Offset(1, 1));
await _settle(tester);
expect(
await tester.runAsync(() => store.loadSmazEnabled(alice.publicKeyHex)),
isTrue,
);
await choose(tester, _l10n.chatCompression_cyr2lat);
// Cyr2Lat keeps the sheet open for its profile picker.
await tester.tap(find.byTooltip('Close'));
await _settle(tester);
await openMenu(tester);
expect(find.text(_l10n.chatCompression_label('Cyr2Lat')), findsOneWidget);
expect(
connector.contactCompressionMode(alice.publicKeyHex),
@@ -416,8 +420,6 @@ void main() {
);
// The settings dialog no longer carries the compression switches.
await tester.tap(find.byIcon(Icons.more_vert));
await _settle(tester);
await tester.tap(find.text(_l10n.contact_settings).last);
await _settle(tester);
expect(find.byType(AlertDialog), findsOneWidget);
@@ -431,7 +433,7 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
testWidgets('channel chat uses the same selector and saves offline', (
testWidgets('channel chat uses the same page and saves offline', (
tester,
) async {
final connector = await _offlineConnector(tester);
@@ -442,10 +444,13 @@ void main() {
);
await _settle(tester);
expect(find.byType(ChatCompressionSelector), findsOneWidget);
await openMenu(tester);
expect(find.text(_l10n.chatCompression_label('Off')), findsOneWidget);
await tester.tapAt(const Offset(1, 1));
await _settle(tester);
await choose(tester, _l10n.chatCompression_smaz);
await openMenu(tester);
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
expect(
await tester.runAsync(() => store.loadSmazEnabled(channel.storageId!)),
+582
View File
@@ -0,0 +1,582 @@
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:provider/provider.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/l10n/app_localizations_en.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/about_screen.dart';
import 'package:meshcore_open/screens/contact_settings_screen.dart';
import 'package:meshcore_open/screens/location_picker_screen.dart';
import 'package:meshcore_open/screens/location_settings_screen.dart';
import 'package:meshcore_open/screens/node_name_screen.dart';
import 'package:meshcore_open/screens/privacy_settings_screen.dart';
import 'package:meshcore_open/screens/radio_settings_screen.dart';
import 'package:meshcore_open/screens/settings_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/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/storage_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/widgets/unsaved_changes_guard.dart';
final _l10n = AppLocalizationsEn();
MeshCoreConnector? _sharedConnector;
AppSettingsService? _sharedSettings;
final _frameLog = BleDebugLogService();
Future<MeshCoreConnector> _connectedConnector(WidgetTester tester) async {
if (_sharedConnector != null) return _sharedConnector!;
final storage = StorageService();
final connector = MeshCoreConnector();
final settings = AppSettingsService();
final translation = TranslationService(settings);
await tester.runAsync(() async {
await settings.loadSettings();
connector.initialize(
retryService: MessageRetryService(),
pathHistoryService: PathHistoryService(storage),
appSettingsService: settings,
translationService: translation,
bleDebugLogService: _frameLog,
);
connector.reviewRadioFactoryForTest = () => ReviewRadio(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
await connector.connectReview();
final end = DateTime.now().add(const Duration(seconds: 8));
while (connector.selfName == null && DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
_sharedSettings = settings;
return _sharedConnector = connector;
}
Widget _app(MeshCoreConnector connector, Widget home) {
final settings = _sharedSettings ?? AppSettingsService();
final storage = StorageService();
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: connector),
ChangeNotifierProvider.value(value: settings),
ChangeNotifierProvider(create: (_) => PathHistoryService(storage)),
ChangeNotifierProvider(create: (_) => BleDebugLogService()),
ChangeNotifierProvider(create: (_) => AppDebugLogService()),
ChangeNotifierProvider(create: (_) => UiViewStateService()),
Provider.value(value: storage),
ChangeNotifierProvider(
create: (_) => MapTileCacheService(appSettingsService: settings),
),
],
child: MaterialApp(
theme: MeshTheme.light(),
locale: const Locale('en'),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: home,
),
);
}
/// A home screen with one button that pushes [page], so tests can check
/// whether leaving the page really closes it.
Widget _launcher(Widget page) => Builder(
builder: (context) => Scaffold(
body: Center(
child: TextButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute<void>(builder: (_) => page),
),
child: const Text('open'),
),
),
),
);
Future<void> _open(WidgetTester tester) async {
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
}
Future<void> _waitFor(WidgetTester tester, bool Function() done) async {
await tester.runAsync(() async {
final end = DateTime.now().add(const Duration(seconds: 5));
while (!done() && DateTime.now().isBefore(end)) {
await Future<void>.delayed(const Duration(milliseconds: 25));
}
});
await tester.pumpAndSettle();
}
Finder get _saveAction => find.widgetWithText(TextButton, _l10n.common_save);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final tempDir = Directory.systemTemp.createTempSync('settings_pages_test');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(call) async => tempDir.path,
);
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
});
group('UnsavedChangesGuard', () {
Widget guarded({required Future<bool> Function() onSave}) =>
UnsavedChangesGuard(
hasChanges: true,
canSave: true,
message: 'msg',
onSave: onSave,
child: Scaffold(appBar: AppBar(), body: const Text('page')),
);
Future<void> pumpGuarded(
WidgetTester tester,
Future<bool> Function() onSave,
) async {
await tester.pumpWidget(
_app(MeshCoreConnector(), _launcher(guarded(onSave: onSave))),
);
await _open(tester);
await tester.pageBack();
await tester.pumpAndSettle();
expect(find.text(_l10n.repeater_unsavedChangesTitle), findsOneWidget);
}
testWidgets('Cancel stays and Discard leaves', (tester) async {
await pumpGuarded(tester, () async => true);
await tester.tap(find.text(_l10n.common_cancel));
await tester.pumpAndSettle();
expect(find.text('page'), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.repeater_discardChanges));
await tester.pumpAndSettle();
expect(find.text('page'), findsNothing);
expect(find.text('open'), findsOneWidget);
});
testWidgets('Save leaves only when saving succeeds', (tester) async {
var result = false;
var saves = 0;
await pumpGuarded(tester, () async {
saves++;
return result;
});
await tester.tap(find.widgetWithText(FilledButton, _l10n.common_save));
await tester.pumpAndSettle();
expect(saves, 1);
expect(find.text('page'), findsOneWidget);
result = true;
await tester.pageBack();
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(FilledButton, _l10n.common_save));
await tester.pumpAndSettle();
expect(saves, 2);
expect(find.text('page'), findsNothing);
});
});
testWidgets('SaveToRadioPage reports a failed save and keeps the page', (
tester,
) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_app(
connector,
_launcher(
SaveToRadioPage(
title: 'Page',
hasChanges: true,
onSave: () async => throw StateError('rejected'),
children: const [Text('field')],
),
),
),
);
await _open(tester);
await tester.tap(_saveAction);
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(
find.text(_l10n.settings_error('Bad state: rejected')),
findsOneWidget,
);
expect(find.text('field'), findsOneWidget);
expect(tester.widget<TextButton>(_saveAction).onPressed, isNotNull);
});
testWidgets('Settings rows open pages, not dialogs', (tester) async {
final connector = await _connectedConnector(tester);
// The connected status dot pulses forever, so pump for a fixed time
// instead of waiting for the screen to settle.
Future<void> settle() async {
for (var i = 0; i < 8; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
await tester.pumpWidget(_app(connector, const SettingsScreen()));
await settle();
final rows = <String, Type>{
_l10n.settings_nodeName: NodeNameScreen,
_l10n.settings_radioSettings: RadioSettingsScreen,
_l10n.settings_location: LocationSettingsScreen,
_l10n.settings_contactSettings: ContactSettingsScreen,
_l10n.settings_privacy: PrivacySettingsScreen,
_l10n.settings_aboutTheApp: AboutScreen,
};
for (final MapEntry(key: title, value: page) in rows.entries) {
await tester.scrollUntilVisible(
find.text(title),
200,
scrollable: find
.descendant(
of: find.byType(ListView),
matching: find.byType(Scrollable),
)
.first,
);
await settle();
await tester.tap(find.text(title));
await settle();
expect(find.byType(page), findsOneWidget, reason: title);
expect(find.byType(AlertDialog), findsNothing, reason: title);
await tester.pageBack();
await settle();
expect(find.byType(page), findsNothing, reason: title);
}
await tester.pumpWidget(const SizedBox());
});
testWidgets('Reboot and Delete All Paths use theme colours and confirm', (
tester,
) async {
final connector = await _connectedConnector(tester);
Future<void> settle() async {
for (var i = 0; i < 8; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
await tester.pumpWidget(_app(connector, const SettingsScreen()));
await settle();
final scheme = Theme.of(
tester.element(find.byType(SettingsScreen)),
).colorScheme;
final rows = {
_l10n.settings_rebootDevice: (_l10n.common_reboot, scheme.tertiary),
_l10n.settings_deleteAllPaths: (_l10n.common_deleteAll, scheme.error),
};
for (final MapEntry(key: title, value: (label, color)) in rows.entries) {
await tester.scrollUntilVisible(
find.text(title),
200,
scrollable: find
.descendant(
of: find.byType(ListView),
matching: find.byType(Scrollable),
)
.first,
);
await settle();
expect(tester.widget<Text>(find.text(title)).style?.color, color);
await tester.tap(find.text(title));
await settle();
final confirm = tester.widget<FilledButton>(
find.widgetWithText(FilledButton, label),
);
expect(confirm.style?.backgroundColor?.resolve({}), color, reason: title);
// Cancel, so the review radio isn't rebooted.
await tester.tap(find.text(_l10n.common_cancel));
await settle();
expect(find.byType(AlertDialog), findsNothing, reason: title);
}
await tester.pumpWidget(const SizedBox());
});
testWidgets('Sync Time and Refresh Contacts end with a message', (
tester,
) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(_app(connector, const SettingsScreen()));
for (var i = 0; i < 8; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
// Refresh Contacts ends when the review radio sends END_OF_CONTACTS.
final rows = {
_l10n.settings_syncTime: _l10n.settings_timeSent,
_l10n.settings_refreshContacts: _l10n.settings_contactsRefreshed,
};
for (final MapEntry(key: title, value: message) in rows.entries) {
await tester.scrollUntilVisible(
find.text(title),
200,
scrollable: find
.descendant(
of: find.byType(ListView),
matching: find.byType(Scrollable),
)
.first,
);
await tester.pump(const Duration(milliseconds: 300));
await tester.tap(find.text(title));
await tester.pump();
// Real time lets the reply arrive; pump runs the code waiting for it.
for (var i = 0; i < 200; i++) {
if (find.text(message).evaluate().isNotEmpty) break;
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 25)),
);
await tester.pump(const Duration(milliseconds: 50));
}
expect(find.text(message), findsOneWidget, reason: title);
}
await tester.pumpWidget(const SizedBox());
});
testWidgets('Delete All Paths confirms with a snackbar', (tester) async {
final connector = await _connectedConnector(tester);
Future<void> settle() async {
for (var i = 0; i < 8; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
await tester.pumpWidget(_app(connector, const SettingsScreen()));
await settle();
await tester.scrollUntilVisible(
find.text(_l10n.settings_deleteAllPaths),
200,
scrollable: find
.descendant(
of: find.byType(ListView),
matching: find.byType(Scrollable),
)
.first,
);
await settle();
await tester.tap(find.text(_l10n.settings_deleteAllPaths));
await settle();
await tester.tap(find.widgetWithText(FilledButton, _l10n.common_deleteAll));
await settle();
expect(find.text(_l10n.settings_allPathsDeleted), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Radio Settings shows Save only while something differs', (
tester,
) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_app(connector, RadioSettingsScreen(connector: connector)),
);
await tester.pumpAndSettle();
expect(_saveAction, findsNothing);
final txField = find.widgetWithText(TextField, _l10n.settings_txPower);
final original = tester.widget<TextField>(txField).controller!.text;
final changed = original == '10' ? '11' : '10';
await tester.enterText(txField, changed);
await tester.pump();
expect(_saveAction, findsOneWidget);
await tester.enterText(txField, original);
await tester.pump();
expect(_saveAction, findsNothing);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Location picker fills the coordinate fields', (tester) async {
final connector = await _connectedConnector(tester);
await tester.pumpWidget(
_app(connector, _launcher(const LocationSettingsScreen())),
);
await _open(tester);
await tester.enterText(
find.widgetWithText(TextField, _l10n.settings_latitude),
'45.5',
);
await tester.enterText(
find.widgetWithText(TextField, _l10n.settings_longitude),
'-122.6',
);
await tester.tap(find.text(_l10n.location_pickOnMap));
await tester.pumpAndSettle();
expect(find.byType(LocationPickerScreen), findsOneWidget);
expect(find.text('45.500000, -122.600000'), findsOneWidget);
await tester.tap(find.text(_l10n.locationPicker_useLocation));
await tester.pumpAndSettle();
expect(find.byType(LocationPickerScreen), findsNothing);
expect(find.text('45.500000'), findsOneWidget);
expect(find.text('-122.600000'), findsOneWidget);
expect(_saveAction, findsOneWidget);
// Unsaved coordinates are not dropped silently.
await tester.pageBack();
await tester.pumpAndSettle();
await tester.tap(find.text(_l10n.repeater_discardChanges));
await tester.pumpAndSettle();
expect(find.byType(LocationSettingsScreen), findsNothing);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Contact Settings sends the hop limit and reads it back', (
tester,
) async {
final connector = await _connectedConnector(tester);
final original = connector.autoAddMaxHops;
expect(original, isNotNull, reason: 'review radio reports the hop limit');
await tester.pumpWidget(
_app(connector, _launcher(const ContactSettingsScreen())),
);
await _open(tester);
String option(int hops) => _l10n.contactsSettings_hopLimitOption(hops);
expect(find.text(option(original!)), findsOneWidget);
Future<void> setHops(int hops) async {
final field = find.byType(DropdownButtonFormField<int>);
await tester.ensureVisible(field);
await tester.pumpAndSettle();
await tester.tap(field);
await tester.pumpAndSettle();
// The open menu builds only the rows around the current value.
final item = find.text(option(hops));
await tester.scrollUntilVisible(
item,
hops < connector.autoAddMaxHops! ? -48 : 48,
scrollable: find.byType(Scrollable).last,
);
await tester.pumpAndSettle();
await tester.tap(item.last);
await tester.pumpAndSettle();
await tester.tap(_saveAction);
await _waitFor(tester, () => connector.autoAddMaxHops == hops);
}
// The last frame of [code] the app sent to the radio.
List<int> lastSent(int code) => _frameLog.entries
.lastWhere((e) => e.outgoing && e.payload.first == code)
.payload;
int sentCount(int code) => _frameLog.entries
.where((e) => e.outgoing && e.payload.first == code)
.length;
final fetchesBefore = sentCount(cmdGetAutoAddConfig);
await setHops(8);
expect(connector.autoAddMaxHops, 8);
expect(find.text(option(8)), findsOneWidget);
expect(_saveAction, findsNothing);
// [CMD_SET_AUTOADD_CONFIG][flags][max hops], then a fetch to read it back.
expect(lastSent(cmdSetAutoAddConfig), hasLength(3));
expect(lastSent(cmdSetAutoAddConfig).last, 8);
expect(sentCount(cmdGetAutoAddConfig), fetchesBefore + 1);
// Changing only another setting sends the old two-byte frame.
final overwrite = find.text(_l10n.contactsSettings_overwriteOldestTitle);
for (var i = 0; i < 2; i++) {
await tester.ensureVisible(overwrite);
await tester.pumpAndSettle();
await tester.tap(overwrite);
await tester.pump();
await tester.tap(_saveAction);
await _waitFor(tester, () => _saveAction.evaluate().isEmpty);
expect(lastSent(cmdSetAutoAddConfig), hasLength(2));
}
expect(connector.autoAddMaxHops, 8);
await setHops(original);
expect(connector.autoAddMaxHops, original);
expect(lastSent(cmdSetAutoAddConfig), hasLength(3));
expect(lastSent(cmdSetAutoAddConfig).last, original);
await tester.pumpWidget(const SizedBox());
});
testWidgets('Node Name counts bytes and saves to the radio', (tester) async {
final connector = await _connectedConnector(tester);
final originalName = connector.selfName!;
await tester.pumpWidget(_app(connector, _launcher(const NodeNameScreen())));
await _open(tester);
expect(_saveAction, findsNothing);
expect(
find.text(_l10n.nodeName_bytesAvailable(maxContactMessageBytes())),
findsOneWidget,
);
// "Ab" is two bytes and the emoji four.
const newName = 'Ab😀';
await tester.enterText(find.byType(TextField), newName);
await tester.pump();
expect(find.text('6 / 31'), findsOneWidget);
expect(
find.text(_l10n.nodeName_bytesAvailable(maxChannelMessageBytes(newName))),
findsOneWidget,
);
expect(maxChannelMessageBytes(newName), 158 - 6);
expect(_saveAction, findsOneWidget);
await tester.tap(_saveAction);
await _waitFor(tester, () => connector.selfName == newName);
expect(connector.selfName, newName);
expect(find.text(_l10n.settings_nodeNameUpdated), findsOneWidget);
expect(_saveAction, findsNothing);
// Longer names are accepted but can't be saved, and say how far over
// the limit they are.
final longName = 'x' * 33;
await tester.enterText(find.byType(TextField), longName);
await tester.pump();
expect(find.text(longName), findsOneWidget);
expect(find.text('33 / 31'), findsOneWidget);
expect(find.text(_l10n.nodeName_bytesOver(2)), findsOneWidget);
expect(tester.widget<TextButton>(_saveAction).onPressed, isNull);
// Saving from the leave dialog sends the edit, then closes the page.
await tester.enterText(find.byType(TextField), originalName);
await tester.pump();
await tester.pageBack();
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(FilledButton, _l10n.common_save));
await _waitFor(tester, () => connector.selfName == originalName);
expect(connector.selfName, originalName);
expect(find.byType(NodeNameScreen), findsNothing);
await tester.pumpWidget(const SizedBox());
});
}
+23 -3
View File
@@ -22,6 +22,7 @@ import 'package:meshcore_open/games/hash_chain.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/screens/about_screen.dart';
import 'package:meshcore_open/screens/add_contact_screen.dart';
import 'package:meshcore_open/screens/app_debug_log_screen.dart';
import 'package:meshcore_open/screens/app_settings_screen.dart';
@@ -32,14 +33,20 @@ import 'package:meshcore_open/screens/channels_screen.dart';
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/contact_settings_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/location_picker_screen.dart';
import 'package:meshcore_open/screens/location_settings_screen.dart';
import 'package:meshcore_open/screens/map_cache_screen.dart';
import 'package:meshcore_open/screens/map_screen.dart';
import 'package:meshcore_open/screens/neighbors_screen.dart';
import 'package:meshcore_open/screens/node_name_screen.dart';
import 'package:meshcore_open/screens/path_trace_map.dart';
import 'package:meshcore_open/screens/privacy_settings_screen.dart';
import 'package:meshcore_open/screens/radio_settings_screen.dart';
import 'package:meshcore_open/screens/region_management_screen.dart';
import 'package:meshcore_open/screens/repeater_cli_screen.dart';
import 'package:meshcore_open/screens/repeater_hub_screen.dart';
@@ -245,6 +252,14 @@ final Map<String, _ScreenBuilder> _screens = {
'Channels': (_) => const ChannelsScreen(),
'Settings': (_) => const SettingsScreen(),
'AppSettings': (_) => const AppSettingsScreen(),
'NodeName': (_) => const NodeNameScreen(),
'RadioSettings': (c) => RadioSettingsScreen(connector: c),
'LocationSettings': (_) => const LocationSettingsScreen(),
'LocationPicker': (_) =>
const LocationPickerScreen(initial: LatLng(45.515232, -122.678385)),
'ContactSettings': (_) => const ContactSettingsScreen(),
'PrivacySettings': (_) => const PrivacySettingsScreen(),
'About': (_) => const AboutScreen(),
'Discovery': (_) => const DiscoveryScreen(),
'RegionManagement': (_) => const RegionManagementScreen(),
'MapCache': (_) => const MapCacheScreen(),
@@ -325,9 +340,9 @@ void main() {
final variants = [
for (final entry in _screens.entries) (entry, false),
// Repeater screens add a banner while the companion radio is offline;
// the main and chat screens swap in the Connect button and the
// read-only composer bar.
// Repeater screens and the radio settings pages add a banner while the
// companion radio is offline; the main and chat screens swap in the
// Connect button and the read-only composer bar.
for (final entry in _screens.entries)
if (entry.key.startsWith('Repeater') ||
const {
@@ -339,6 +354,11 @@ void main() {
'ChannelChat',
'ChessGame',
'Settings',
'NodeName',
'RadioSettings',
'LocationSettings',
'ContactSettings',
'PrivacySettings',
}.contains(entry.key))
(entry, true),
];
@@ -1,334 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/chat_compression_selector.dart';
final _l10n = lookupAppLocalizations(const Locale('en'));
final _profiles = [
Cyr2LatProfile(id: 'ru', name: 'Russian', charMap: const {'А': 'A'}),
Cyr2LatProfile(id: 'sr', name: 'Serbian', charMap: const {'З': '3'}),
];
/// Stands in for a chat screen: keeps the "saved" state and applies a change
/// only when the test completes the pending write.
class _Host extends StatefulWidget {
final ChatCompressionMode initialMode;
final bool enabled;
final String? initialProfileId;
final List<ChatCompressionMode> modeCalls;
final List<String> profileCalls;
final List<Completer<void>> pending;
const _Host({
this.initialMode = ChatCompressionMode.off,
this.enabled = true,
this.initialProfileId,
required this.modeCalls,
required this.profileCalls,
required this.pending,
});
@override
State<_Host> createState() => _HostState();
}
class _HostState extends State<_Host> {
late ChatCompressionMode _mode = widget.initialMode;
late String? _profileId = widget.initialProfileId;
Future<void> _write(void Function() apply) async {
final completer = Completer<void>();
widget.pending.add(completer);
await completer.future;
if (mounted) setState(apply);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Chat')),
body: Column(
children: [
ChatCompressionSelector(
mode: _mode,
enabled: widget.enabled,
disabledReason: widget.enabled
? null
: _l10n.chatCompression_noStorageId,
profiles: _profiles,
profileId: _profileId,
defaultProfileId: 'ru',
onModeChanged: (mode) {
widget.modeCalls.add(mode);
return _write(() => _mode = mode);
},
onProfileChanged: (id) {
widget.profileCalls.add(id);
return _write(() => _profileId = id);
},
),
const Expanded(child: Placeholder()),
],
),
);
}
}
void main() {
late List<ChatCompressionMode> modeCalls;
late List<String> profileCalls;
late List<Completer<void>> pending;
setUp(() {
modeCalls = [];
profileCalls = [];
pending = [];
});
Future<void> pumpHost(
WidgetTester tester, {
ChatCompressionMode mode = ChatCompressionMode.off,
bool enabled = true,
String? profileId,
Size size = const Size(400, 800),
double textScale = 1.0,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
theme: MeshTheme.light(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
),
home: _Host(
initialMode: mode,
enabled: enabled,
initialProfileId: profileId,
modeCalls: modeCalls,
profileCalls: profileCalls,
pending: pending,
),
),
);
}
Future<void> openSheet(WidgetTester tester) async {
await tester.tap(find.byType(ChatCompressionSelector));
await tester.pumpAndSettle();
}
Finder optionRow(String label) =>
find.ancestor(of: find.text(label), matching: find.byType(ListTile));
bool isSelected(WidgetTester tester, String label) {
final row = optionRow(label);
return find
.descendant(of: row, matching: find.byIcon(Icons.radio_button_checked))
.evaluate()
.isNotEmpty;
}
testWidgets('shows the saved mode and announces it', (tester) async {
final semantics = tester.ensureSemantics();
await pumpHost(tester, mode: ChatCompressionMode.smaz);
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
expect(
tester.getSemantics(
find.bySemanticsLabel(_l10n.chatCompression_label('SMAZ')),
),
isSemantics(
label: _l10n.chatCompression_label('SMAZ'),
hint: _l10n.chatCompression_changeHint,
isButton: true,
isEnabled: true,
hasTapAction: true,
),
);
expect(
tester.getSize(find.byType(ChatCompressionSelector)).height,
greaterThanOrEqualTo(48),
);
semantics.dispose();
});
testWidgets('one sheet lists the three modes with their explanations', (
tester,
) async {
await pumpHost(tester);
await openSheet(tester);
expect(find.text(_l10n.chatCompression_title), findsOneWidget);
expect(find.text(_l10n.chatCompression_off), findsOneWidget);
expect(find.text(_l10n.chatCompression_smaz), findsOneWidget);
expect(find.text(_l10n.chatCompression_cyr2lat), findsOneWidget);
expect(find.text(_l10n.chatCompression_offDescription), findsOneWidget);
expect(find.text(_l10n.chatCompression_smazDescription), findsOneWidget);
expect(find.text(_l10n.chatCompression_cyr2latDescription), findsOneWidget);
expect(isSelected(tester, _l10n.chatCompression_off), isTrue);
expect(isSelected(tester, _l10n.chatCompression_smaz), isFalse);
// No profile picker unless Cyr2Lat is chosen.
expect(find.text(_l10n.chatCompression_profile), findsNothing);
expect(find.byType(Dialog), findsNothing);
});
testWidgets('a choice shows only after it is saved, then the sheet closes', (
tester,
) async {
await pumpHost(tester);
await openSheet(tester);
await tester.tap(find.text(_l10n.chatCompression_smaz));
await tester.pump();
expect(modeCalls, [ChatCompressionMode.smaz]);
// Still saving: old mode shown, options locked against rapid taps.
expect(isSelected(tester, _l10n.chatCompression_off), isTrue);
expect(
tester.widget<ListTile>(optionRow(_l10n.chatCompression_cyr2lat)).enabled,
isFalse,
);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
expect(modeCalls, [ChatCompressionMode.smaz]);
pending.single.complete();
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_title), findsNothing);
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
});
testWidgets('Cyr2Lat keeps the sheet open with its profile picker', (
tester,
) async {
await pumpHost(tester);
await openSheet(tester);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
pending.removeAt(0).complete();
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_title), findsOneWidget);
expect(isSelected(tester, _l10n.chatCompression_cyr2lat), isTrue);
expect(find.text(_l10n.chatCompression_profile), findsOneWidget);
// No profile saved for the chat: the app-wide one is what sending uses.
expect(find.text('Russian'), findsOneWidget);
await tester.ensureVisible(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Serbian').last);
await tester.pump();
expect(profileCalls, ['sr']);
pending.removeAt(0).complete();
await tester.pumpAndSettle();
expect(find.text('Serbian'), findsOneWidget);
expect(find.text(_l10n.chatCompression_label('Cyr2Lat')), findsOneWidget);
});
testWidgets('a failed save keeps the saved mode and says so', (tester) async {
await pumpHost(tester, mode: ChatCompressionMode.smaz);
await openSheet(tester);
await tester.tap(find.text(_l10n.chatCompression_cyr2lat));
await tester.pump();
pending.single.completeError(StateError('disk full'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_saveFailed), findsOneWidget);
expect(isSelected(tester, _l10n.chatCompression_smaz), isTrue);
expect(isSelected(tester, _l10n.chatCompression_cyr2lat), isFalse);
expect(
tester.widget<ListTile>(optionRow(_l10n.chatCompression_off)).enabled,
isTrue,
);
await tester.tap(find.byTooltip('Close'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_label('SMAZ')), findsOneWidget);
});
testWidgets('a failed profile save shows the saved profile again', (
tester,
) async {
await pumpHost(tester, mode: ChatCompressionMode.cyr2lat, profileId: 'ru');
await openSheet(tester);
await tester.ensureVisible(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Russian'));
await tester.pumpAndSettle();
await tester.tap(find.text('Serbian').last);
await tester.pump();
expect(profileCalls, ['sr']);
pending.single.completeError(StateError('disk full'));
await tester.pumpAndSettle();
expect(find.text(_l10n.chatCompression_saveFailed), findsOneWidget);
expect(find.text('Russian'), findsOneWidget);
expect(find.text('Serbian'), findsNothing);
});
testWidgets('disabled shows the saved mode, and the sheet says why and '
'allows no change', (tester) async {
final semantics = tester.ensureSemantics();
await pumpHost(tester, mode: ChatCompressionMode.smaz, enabled: false);
final label = _l10n.chatCompression_label('SMAZ');
expect(find.text(label), findsOneWidget);
expect(find.byIcon(Icons.lock_outline), findsOneWidget);
expect(
find.bySemanticsLabel('$label. ${_l10n.chatCompression_noStorageId}'),
findsOneWidget,
);
await openSheet(tester);
expect(find.text(_l10n.chatCompression_noStorageId), findsOneWidget);
expect(isSelected(tester, _l10n.chatCompression_smaz), isTrue);
for (final mode in [
_l10n.chatCompression_off,
_l10n.chatCompression_smaz,
_l10n.chatCompression_cyr2lat,
]) {
expect(tester.widget<ListTile>(optionRow(mode)).enabled, isFalse);
}
await tester.tap(find.text(_l10n.chatCompression_off), warnIfMissed: false);
await tester.pumpAndSettle();
expect(modeCalls, isEmpty);
semantics.dispose();
});
for (final scale in [1.3, 2.0]) {
testWidgets('fits a 320dp phone at ${scale}x text', (tester) async {
await pumpHost(
tester,
mode: ChatCompressionMode.cyr2lat,
enabled: true,
size: const Size(320, 568),
textScale: scale,
);
expect(tester.takeException(), isNull);
await openSheet(tester);
expect(tester.takeException(), isNull);
// The sheet scrolls to its last option and the profile picker.
await tester.scrollUntilVisible(
find.text(_l10n.chatCompression_profile),
200,
scrollable: find.byType(Scrollable).last,
);
expect(tester.takeException(), isNull);
});
}
}
+35
View File
@@ -0,0 +1,35 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/widgets/sync_progress_overlay.dart';
// The shared top progress bar: 4px, theme colours, keeps its height idle.
void main() {
Widget host(Widget child) => MaterialApp(
home: Scaffold(body: Column(children: [child])),
);
testWidgets('idle bar keeps its 4px height and draws nothing', (
tester,
) async {
await tester.pumpWidget(host(const MeshProgressBar(active: false)));
expect(tester.getSize(find.byType(MeshProgressBar)).height, 4);
expect(find.byType(LinearProgressIndicator), findsNothing);
});
testWidgets('active bar fills with the theme colour', (tester) async {
await tester.pumpWidget(host(const MeshProgressBar(value: 0.5)));
final bar = tester.widget<LinearProgressIndicator>(
find.byType(LinearProgressIndicator),
);
expect(bar.value, 0.5);
expect(bar.minHeight, 4);
expect(bar.color, isNull);
expect(bar.backgroundColor, isNull);
});
test('app bar versions are 4px tall', () {
expect(const MeshProgressAppBarBottom().preferredSize.height, 4);
expect(const SyncProgressAppBarBottom().preferredSize.height, 4);
});
}
@@ -54,13 +54,7 @@ Future<void> _openSheet(
builder: (context, child) {
final media = MediaQuery.of(context);
return MediaQuery(
data: media.copyWith(
size: size,
padding: padding,
viewPadding: viewPadding,
viewInsets: viewInsets,
textScaler: TextScaler.linear(textScale),
),
data: media.copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
);
},
@@ -128,6 +122,48 @@ void main() {
},
);
testWidgets(
'sheet recomputes height cap and expands when keyboard inset closes',
(tester) async {
await _openSheet(
tester,
size: const Size(320, 568),
padding: const EdgeInsets.only(top: 48),
viewPadding: const EdgeInsets.only(top: 48, bottom: 34),
viewInsets: const EdgeInsets.only(bottom: 300),
);
final listFinder = find.byType(CustomScrollView);
expect(listFinder, findsOneWidget);
final compressedHeaderTop = tester
.getTopLeft(find.byType(BottomSheetHeader))
.dy;
final compressedBottom = tester.getBottomLeft(listFinder).dy;
final compressedContentHeight = compressedBottom - compressedHeaderTop;
expect(compressedContentHeight, lessThanOrEqualTo(220.0));
// Dismiss the keyboard while the sheet remains open.
tester.view.viewInsets = FakeViewPadding.zero;
tester.view.padding = const FakeViewPadding(top: 48, bottom: 34);
await tester.pumpAndSettle();
final expandedHeaderTop = tester
.getTopLeft(find.byType(BottomSheetHeader))
.dy;
final expandedListFinder = find.byType(ListView);
expect(expandedListFinder, findsOneWidget);
final expandedBottom = tester.getBottomLeft(expandedListFinder).dy;
final expandedContentHeight = expandedBottom - expandedHeaderTop;
expect(expandedContentHeight, greaterThan(compressedContentHeight));
expect(expandedContentHeight, greaterThan(400.0));
expect(
tester.getRect(find.byType(BottomSheet)).height,
greaterThan(450.0),
);
},
);
testWidgets(
'toggling switch, filtering languages, and selecting target or app language works',
(tester) async {