Merge upstream/dev: custom and holiday themes, chat backgrounds
build / ci-image (push) Successful in 9s
build / build (push) Successful in 11m47s

Upstream's theme system (two-color custom themes, holiday themes, picture
icons, chat backgrounds) next to the tth terminal theme:
- a user's custom theme wins; without one, themeMode 'terminal' is still
  the dark theme (main.dart);
- MeshTheme.buildFrom (terminal base) builds with the stock bubble, icon
  and map extensions, like dark()/light();
- terminal avatars also show a theme slot's glyph; the bottom bar stays
  44 px without labels in the terminal theme, 76/60 otherwise;
- map overlays: terminal panels stay square and black, otherwise
  upstream's palette/follow-theme logic; channel list keeps the terminal
  padding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-02 16:12:14 +01:00
commit 675342e745
144 files changed
+13281 -732

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/holiday_triggers.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/widgets/holiday_animations.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
group('holidayAnimationFor', () {
test('every greeting in every language triggers its holiday', () {
for (final locale in AppLocalizations.supportedLocales) {
final l10n = lookupAppLocalizations(Locale(locale.languageCode));
for (final animation in HolidayAnimation.values) {
final greetings = holidayGreetingsIn(l10n, animation);
expect(greetings.trim(), isNotEmpty, reason: '$locale $animation');
for (final phrase in greetings.split('|')) {
expect(
holidayAnimationFor('$phrase!'),
animation,
reason: '${locale.languageCode}: "$phrase"',
);
}
}
}
});
test('case, punctuation and surrounding words do not matter', () {
expect(
holidayAnimationFor('HAPPY HALLOWEEN!!! 🎃'),
HolidayAnimation.halloween,
);
expect(
holidayAnimationFor('hey all, happy new year’s from the mesh'),
HolidayAnimation.newYear,
);
expect(holidayAnimationFor('#HappyNewYear'), HolidayAnimation.newYear);
expect(
holidayAnimationFor('Merry Christmas, everyone'),
HolidayAnimation.christmas,
);
expect(
holidayAnimationFor('happy thanksgiving y’all'),
HolidayAnimation.thanksgiving,
);
expect(holidayAnimationFor('FELIZ NAVIDAD'), HolidayAnimation.christmas);
expect(holidayAnimationFor('С НОВЫМ ГОДОМ!'), HolidayAnimation.newYear);
expect(holidayAnimationFor('みんな、メリークリスマス!'), HolidayAnimation.christmas);
expect(holidayAnimationFor('祝大家新年快乐'), HolidayAnimation.newYear);
});
test('ordinary messages and near misses do not trigger', () {
for (final text in [
'',
'happy',
'halloween party at 8?',
'feliz natalia', // a name, not "feliz natal"
'my christmas tree fell over',
'new year plans?',
'unhappy new yearly report',
'thanksgiving dinner menu',
]) {
expect(holidayAnimationFor(text), isNull, reason: text);
}
});
});
group('HolidayTriggerWatcher', () {
late AppSettingsService settings;
setUp(() async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
settings = AppSettingsService();
});
Future<BuildContext> host(
WidgetTester tester, {
bool reduceMotion = false,
}) async {
late BuildContext ctx;
await tester.pumpWidget(
ChangeNotifierProvider.value(
value: settings,
child: MediaQuery(
data: MediaQueryData(disableAnimations: reduceMotion),
child: MaterialApp(
home: Builder(
builder: (c) {
ctx = c;
return const SizedBox.expand();
},
),
),
),
),
);
return ctx;
}
void send(
HolidayTriggerWatcher w,
BuildContext ctx,
String id,
String text, {
Duration age = Duration.zero,
}) {
w.onNewest(
ctx,
id: id,
texts: [text],
receivedAt: DateTime.now().subtract(age),
originOf: () => const Offset(100, 400),
);
}
testWidgets('plays for new greetings only, once each', (tester) async {
final ctx = await host(tester);
final watcher = HolidayTriggerWatcher();
// A greeting already there when the chat opens stays quiet.
send(watcher, ctx, 'a', 'Happy Halloween');
await tester.pump();
expect(find.byType(HolidayAnimationView), findsNothing);
send(watcher, ctx, 'b', 'Happy Halloween everyone');
// It starts after the frame that showed the message, then builds.
await tester.pump();
await tester.pump();
expect(find.byType(HolidayAnimationView), findsOneWidget);
// Rebuilds with the same newest message do not replay it.
send(watcher, ctx, 'b', 'Happy Halloween everyone');
await tester.pumpAndSettle();
expect(find.byType(HolidayAnimationView), findsNothing);
// Old messages (e.g. a synced backlog) stay quiet.
send(watcher, ctx, 'c', 'Merry Christmas', age: const Duration(hours: 3));
await tester.pump();
expect(find.byType(HolidayAnimationView), findsNothing);
});
testWidgets('each animation runs and cleans up after itself', (
tester,
) async {
final ctx = await host(tester);
for (final animation in HolidayAnimation.values) {
playHolidayAnimation(ctx, animation, origin: const Offset(80, 500));
await tester.pump();
expect(find.byType(HolidayAnimationView), findsOneWidget);
await tester.pump(holidayAnimationDuration(animation) ~/ 2);
expect(tester.takeException(), isNull);
await tester.pumpAndSettle();
expect(find.byType(HolidayAnimationView), findsNothing);
}
});
testWidgets('respects the setting and reduced motion', (tester) async {
await settings.setHolidayAnimationsEnabled(false);
var ctx = await host(tester);
playHolidayAnimation(ctx, HolidayAnimation.newYear, origin: Offset.zero);
await tester.pump();
expect(find.byType(HolidayAnimationView), findsNothing);
await settings.setHolidayAnimationsEnabled(true);
ctx = await host(tester, reduceMotion: true);
playHolidayAnimation(ctx, HolidayAnimation.newYear, origin: Offset.zero);
await tester.pump();
expect(find.byType(HolidayAnimationView), findsNothing);
});
});
}
@@ -51,18 +51,18 @@ void main() {
);
});
test('resolves ipfs cid links with the default ipfs.io gateway', () async {
test('resolves ipfs cid links with the default Filebase gateway', () async {
expect(
await MessageUrlImageHelper.parse(
'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text',
),
'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly',
'https://ipfs.filebase.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly',
);
expect(
await MessageUrlImageHelper.parse(
'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text',
),
'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly',
'https://ipfs.filebase.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly',
);
});
+246
View File
@@ -0,0 +1,246 @@
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/models/custom_theme.dart';
import 'package:meshcore_open/screens/theme_editor_screen.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
group('hex colors', () {
test('parse long, short and bare forms', () {
expect(parseHexColor('#0EA5E9'), const Color(0xFF0EA5E9));
expect(parseHexColor('0ea5e9'), const Color(0xFF0EA5E9));
expect(parseHexColor('#fff'), const Color(0xFFFFFFFF));
expect(parseHexColor(' #000000 '), const Color(0xFF000000));
});
test('reject invalid input', () {
expect(parseHexColor('#12'), isNull);
expect(parseHexColor('#GGGGGG'), isNull);
expect(parseHexColor(42), isNull);
expect(parseHexColor(null), isNull);
});
test('format as uppercase #RRGGBB', () {
expect(colorToHex(const Color(0xFF0ea5e9)), '#0EA5E9');
expect(colorToHex(const Color(0x800000FF)), '#0000FF');
});
});
group('CustomTheme', () {
const theme = CustomTheme(
id: 'custom:1',
name: 'Forest',
background: Color(0xFF0E1A13),
accent: Color(0xFF4ADE80),
);
test('brightness comes from the background', () {
expect(theme.isDark, isTrue);
expect(theme.copyWith(background: Colors.white).isDark, isFalse);
});
test('JSON round-trips', () {
expect(CustomTheme.fromJson(theme.toJson()), theme);
});
test('share code round-trips under a new ID', () {
final imported = CustomTheme.fromShareCode(
theme.toShareCode(),
newId: 'custom:2',
);
expect(imported, theme.copyWith(id: 'custom:2'));
});
test('hand-written share code is accepted', () {
final imported = CustomTheme.fromShareCode(
'{"name": "Mine", "background": "#fff", "accent": "1d4ed8"}',
newId: 'x',
);
expect(imported?.name, 'Mine');
expect(imported?.isDark, isFalse);
});
test('bad share codes are rejected', () {
for (final code in [
'',
'not json',
'[]',
'{"name": "", "background": "#000", "accent": "#fff"}',
'{"name": "X", "background": "nope", "accent": "#fff"}',
'{"name": "X", "background": "#000"}',
]) {
expect(
CustomTheme.fromShareCode(code, newId: 'x'),
isNull,
reason: code,
);
}
});
test('preset IDs are unique and resolvable', () {
final ids = CustomTheme.presets.map((p) => p.id).toSet();
expect(ids.length, CustomTheme.presets.length);
for (final preset in [
...CustomTheme.presets,
...CustomTheme.holidayPresets,
]) {
expect(preset.isPreset, isTrue);
expect(CustomTheme.presetById(preset.id), preset);
}
});
});
group('MeshTheme.fromCustom', () {
test('every preset yields readable text and buttons', () {
for (final preset in [
...CustomTheme.presets,
...CustomTheme.holidayPresets,
]) {
final data = MeshTheme.fromCustom(preset);
final scheme = data.colorScheme;
expect(
data.brightness,
preset.isDark ? Brightness.dark : Brightness.light,
);
expect(scheme.surface, preset.background);
expect(scheme.primary, preset.accent);
expect(
_contrast(scheme.onSurface, scheme.surface),
greaterThan(7),
reason: preset.name,
);
expect(
_contrast(scheme.onPrimary, scheme.primary),
greaterThan(3),
reason: preset.name,
);
final bubble = data.extension<MeshBubbleTheme>()!;
expect(
_contrast(bubble.meInk, bubble.me),
greaterThan(4.5),
reason: preset.name,
);
}
});
test('stock themes keep the standard bubble', () {
expect(
MeshTheme.dark().extension<MeshBubbleTheme>(),
MeshBubbleTheme.standard,
);
});
});
group('settings', () {
setUp(() async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
});
test('custom themes and the active ID persist', () {
const theme = CustomTheme(
id: 'custom:1',
name: 'Mine',
background: Color(0xFF000000),
accent: Color(0xFFFACC15),
);
final settings = AppSettings(
customThemes: const [theme],
activeThemeId: theme.id,
);
final restored = AppSettings.fromJson(settings.toJson());
expect(restored.customThemes, [theme]);
expect(restored.activeThemeId, theme.id);
expect(AppSettings.fromJson(const {}).customThemes, isEmpty);
});
test('service saves, applies, resolves and deletes themes', () async {
final service = AppSettingsService();
const theme = CustomTheme(
id: 'custom:1',
name: 'Mine',
background: Color(0xFF000000),
accent: Color(0xFFFACC15),
);
await service.saveCustomTheme(theme, apply: true);
expect(service.activeCustomTheme, theme);
await service.saveCustomTheme(theme.copyWith(name: 'Renamed'));
expect(service.settings.customThemes.single.name, 'Renamed');
await service.setActiveTheme(CustomTheme.presets.first.id);
expect(service.activeCustomTheme, CustomTheme.presets.first);
await service.setThemeMode('light');
expect(service.activeCustomTheme, isNull);
await service.setActiveTheme(theme.id);
await service.deleteCustomTheme(theme.id);
expect(service.settings.customThemes, isEmpty);
expect(service.activeCustomTheme, isNull);
});
});
testWidgets('editor saves and applies a new theme', (tester) async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
final service = AppSettingsService();
await tester.pumpWidget(
ChangeNotifierProvider.value(
value: service,
child: const MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: ThemeEditorScreen(),
),
),
);
final list = find.byType(Scrollable).first;
final save = find.text('Save and use');
Future<void> tapSave() async {
await tester.scrollUntilVisible(save, 200, scrollable: list);
await tester.ensureVisible(save);
await tester.pumpAndSettle();
await tester.tap(save);
}
// Saving without a name is refused.
await tapSave();
await tester.pumpAndSettle();
expect(find.text('Give your theme a name'), findsOneWidget);
expect(service.settings.customThemes, isEmpty);
await tester.scrollUntilVisible(
find.byType(TextField).first,
-200,
scrollable: list,
);
await tester.enterText(find.byType(TextField).first, 'Night Owl');
final accentHex = find.widgetWithText(TextField, '#0EA5E9');
await tester.scrollUntilVisible(accentHex, 200, scrollable: list);
await tester.enterText(accentHex, '#FACC15');
await tester.pump();
await tapSave();
await tester.pumpAndSettle();
final saved = service.settings.customThemes.single;
expect(saved.name, 'Night Owl');
expect(saved.accent, const Color(0xFFFACC15));
expect(service.activeCustomTheme, saved);
});
}
double _contrast(Color a, Color b) {
final la = a.computeLuminance();
final lb = b.computeLuminance();
final hi = la > lb ? la : lb;
final lo = la > lb ? lb : la;
return (hi + 0.05) / (lo + 0.05);
}
+180
View File
@@ -0,0 +1,180 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:koni_jxl_flutter/koni_jxl_flutter.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/chat_background.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/theme/theme_icons.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
/// Every bundled picture a holiday theme points at.
List<String> _assetsOf(CustomTheme theme) => [
for (final icon in theme.icons.values) ?icon.asset,
?theme.chatBackground?.asset,
];
void main() {
test('map marker slots cover every node type', () {
expect(mapMarkerSlotForNodeType(advTypeChat), ThemeIconSlot.mapChat);
expect(
mapMarkerSlotForNodeType(advTypeRepeater),
ThemeIconSlot.mapRepeater,
);
expect(mapMarkerSlotForNodeType(advTypeRoom), ThemeIconSlot.mapRoom);
expect(mapMarkerSlotForNodeType(advTypeSensor), ThemeIconSlot.mapSensor);
expect(mapMarkerSlotForNodeType(99), isNull);
expect(ThemeIconSlot.values.where((s) => s.isMapMarker).map((s) => s.key), [
'map_chat',
'map_repeater',
'map_room',
'map_sensor',
'map_self',
]);
});
test('list avatars and map markers share a node type icon', () {
const marker = ThemeIconOverride.icon('castle');
const theme = MeshIconTheme({'map_repeater': marker});
expect(theme[ThemeIconSlot.repeater], marker);
expect(theme[ThemeIconSlot.mapRepeater], marker);
expect(theme[ThemeIconSlot.room], isNull);
// A slot's own setting wins over its partner's.
const own = ThemeIconOverride.icon('home');
const both = MeshIconTheme({'map_room': marker, 'room': own});
expect(both[ThemeIconSlot.room], own);
expect(both[ThemeIconSlot.mapRoom], marker);
for (final slot in ThemeIconSlot.values) {
expect(slot.partner?.partner ?? slot, slot, reason: slot.key);
}
});
testWidgets('holiday list avatars show the map marker picture', (
tester,
) async {
final theme = CustomTheme.holidayPresets.first;
await tester.pumpWidget(
MaterialApp(
theme: MeshTheme.fromCustom(theme),
home: const Column(
children: [
AvatarCircle(name: 'Tower', iconSlot: ThemeIconSlot.repeater),
AvatarCircle(name: 'Zed'),
],
),
),
);
final image = tester.widget<Image>(find.byType(Image));
expect(
image.image,
JxlImageProvider.asset(theme.icons['map_repeater']!.asset!),
);
// Chat contacts keep their initials.
expect(find.text('ZE'), findsOneWidget);
});
test('pictures and named icons resolve to the right provider', () {
expect(themePictureOf(null), isNull);
expect(themePictureOf(const ThemeIconOverride.icon('park')), isNull);
expect(
themePictureOf(
const ThemeIconOverride.asset('assets/themes/halloween/map_chat.jxl'),
),
isA<JxlImageProvider>(),
);
});
test('holiday themes have unique IDs that resolve', () {
final all = [...CustomTheme.presets, ...CustomTheme.holidayPresets];
expect(all.map((t) => t.id).toSet(), hasLength(all.length));
for (final theme in CustomTheme.holidayPresets) {
expect(CustomTheme.presetById(theme.id), theme);
expect(theme.isPreset, isTrue);
expect(theme.chatBackground?.asset, isNotNull);
expect(theme.icons.keys, containsAll(['contacts', 'channels', 'map']));
expect(
theme.icons.keys,
containsAll([
for (final slot in ThemeIconSlot.values)
if (slot.isMapMarker) slot.key,
]),
reason: '${theme.name} has every map marker',
);
}
});
test('every holiday picture is a bundled, declared JPEG XL file', () {
final pubspec = File('pubspec.yaml').readAsStringSync();
for (final theme in CustomTheme.holidayPresets) {
for (final path in _assetsOf(theme)) {
expect(isThemeAssetPath(path), isTrue, reason: path);
final file = File(path);
expect(file.existsSync(), isTrue, reason: path);
expect(looksLikeJxl(file.readAsBytesSync()), isTrue, reason: path);
final dir = path.substring(0, path.lastIndexOf('/') + 1);
expect(pubspec, contains('- $dir'), reason: 'pubspec lists $dir');
}
}
});
testWidgets('holiday pictures decode, icons keep transparency', (
tester,
) async {
await tester.runAsync(() async {
for (final theme in CustomTheme.holidayPresets) {
final background = await decodeJxlToUiImage(
File(theme.chatBackground!.asset!).readAsBytesSync(),
);
expect(background.height, greaterThan(background.width));
background.dispose();
final icon = await decodeJxlToUiImage(
File(theme.icons['contacts']!.asset!).readAsBytesSync(),
);
final pixels = (await icon.toByteData())!;
// Top-left corner lies outside the round badge.
expect(pixels.getUint8(3), 0, reason: theme.name);
icon.dispose();
}
});
});
test('asset references survive JSON and share codes', () {
final theme = CustomTheme.holidayPresets.first;
expect(CustomTheme.fromJson(theme.toJson()), theme);
final copy = CustomTheme.fromShareCode(theme.toShareCode(), newId: 'x')!;
expect(copy.chatBackground, theme.chatBackground);
expect(copy.icons, theme.icons);
});
test('shared codes cannot point outside the theme assets', () {
for (final bad in [
'assets/images/logo.png',
'assets/themes/../fonts/Inter.ttf',
'assets/themes/halloween/background.png',
'/etc/passwd',
]) {
expect(isThemeAssetPath(bad), isFalse, reason: bad);
expect(ThemeIconOverride.fromJson({'asset': bad}), isNull);
expect(ChatBackground.fromJson({'asset': bad}), isNull);
}
});
testWidgets('a holiday theme shows its icon in place of the default', (
tester,
) async {
final theme = CustomTheme.holidayPresets.first;
await tester.pumpWidget(
MaterialApp(
theme: MeshTheme.fromCustom(theme),
home: const ThemedIcon(ThemeIconSlot.map),
),
);
expect(find.byType(Image), findsOneWidget);
expect(find.byIcon(Icons.map_outlined), findsNothing);
});
}
+5 -9
View File
@@ -457,12 +457,12 @@ void main() {
expect(AppSettings.fromJson(saved).showLinkImagesByDefault, isTrue);
});
test('public IPFS gateway defaults to ipfs.io when never set', () {
test('public IPFS gateway defaults to Filebase when never set', () {
expect(
AppSettings.fromJson({}).publicIpfsGateway,
'https://ipfs.io/ipfs/',
'https://ipfs.filebase.io/ipfs/',
);
expect(AppSettings().publicIpfsGateway, 'https://ipfs.io/ipfs/');
expect(AppSettings().publicIpfsGateway, 'https://ipfs.filebase.io/ipfs/');
});
test('public IPFS gateway keeps a saved empty value as deactivated', () {
@@ -470,12 +470,8 @@ void main() {
expect(AppSettings.fromJson(saved).publicIpfsGateway, isEmpty);
});
test('public IPFS gateway keeps saved ipfs.io and dweb.link values', () {
for (final gateway in [
'https://ipfs.io/ipfs/',
'https://dweb.link/ipfs/',
'https://gateway.example.com/ipfs/',
]) {
test('public IPFS gateway keeps saved custom values', () {
for (final gateway in ['https://gateway.example.com/ipfs/']) {
final saved = AppSettings(publicIpfsGateway: gateway).toJson();
expect(AppSettings.fromJson(saved).publicIpfsGateway, gateway);
}
+161
View File
@@ -0,0 +1,161 @@
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:koni_jxl_flutter/koni_jxl_flutter.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/theme/theme_icons.dart';
import 'package:meshcore_open/utils/theme_file.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
final png = Uint8List.fromList([137, 80, 78, 71, 1, 2, 3]);
final theme = CustomTheme(
id: 'custom:1',
name: 'Iconic',
background: const Color(0xFF000000),
accent: const Color(0xFFFACC15),
icons: {
'map': const ThemeIconOverride.icon('park'),
'send': ThemeIconOverride.image(png),
},
);
group('theme icons', () {
test('icons survive JSON and share codes', () {
expect(CustomTheme.fromJson(theme.toJson()), theme);
final imported = CustomTheme.fromShareCode(
theme.toShareCode(),
newId: 'x',
)!;
expect(imported.icons['send']!.imageBytes, png);
expect(imported.icons['map']!.icon, 'park');
});
test('unknown slots, unknown icons and bad pictures are dropped', () {
final icons = parseThemeIcons({
'map': {'icon': 'not_an_icon'},
'nope': {'icon': 'park'},
'send': {'image': '%%%'},
'contacts': {'icon': 'rocket_launch'},
});
expect(icons.keys, ['contacts']);
});
test('slot keys are unique and catalog names resolve', () {
final keys = ThemeIconSlot.values.map((s) => s.key).toSet();
expect(keys.length, ThemeIconSlot.values.length);
});
test('custom theme carries its icons into ThemeData', () {
final data = MeshTheme.fromCustom(theme);
expect(data.extension<MeshIconTheme>()![ThemeIconSlot.map]!.icon, 'park');
expect(MeshTheme.dark().extension<MeshIconTheme>()!.overrides, isEmpty);
});
testWidgets('ThemedIcon shows the override or the default', (tester) async {
Widget host(ThemeData data) => MaterialApp(
theme: data,
home: const Row(
children: [
ThemedIcon(ThemeIconSlot.map),
ThemedIcon(ThemeIconSlot.channels),
],
),
);
await tester.pumpWidget(host(MeshTheme.fromCustom(theme)));
expect(find.byIcon(Icons.park), findsOneWidget);
expect(find.byIcon(Icons.tag), findsOneWidget);
await tester.pumpWidget(host(MeshTheme.dark()));
await tester.pumpAndSettle(); // theme change animates
expect(find.byIcon(Icons.map_outlined), findsOneWidget);
});
testWidgets('pictures are shrunk to a lossless JPEG XL', (tester) async {
final big = await tester.runAsync(() async {
final recorder = ui.PictureRecorder();
Canvas(recorder).drawRect(
const Rect.fromLTWH(0, 0, 400, 200),
Paint()..color = const Color(0xFFFF0000),
);
final image = await recorder.endRecording().toImage(400, 200);
final data = await image.toByteData(format: ui.ImageByteFormat.png);
return data!.buffer.asUint8List();
});
final shrunk = await tester.runAsync(() => shrinkThemeIconImage(big!));
expect(looksLikeJxl(shrunk!), isTrue);
final size = await tester.runAsync(() async {
final image = await decodeJxlToUiImage(shrunk);
return Size(image.width.toDouble(), image.height.toDouble());
});
expect(size, const Size(128, 64));
expect(
await tester.runAsync(
() => shrinkThemeIconImage(Uint8List.fromList([1, 2, 3])),
),
isNull,
);
});
});
group('jsonl files', () {
var n = 0;
String newId() => 'id${n++}';
test('one theme per line round-trips', () {
final second = CustomTheme.presets.first;
final text = encodeThemesJsonl([theme, second]);
expect(text.trim().split('\n'), hasLength(2));
final decoded = decodeThemesJsonl(text, newId: newId);
expect(decoded, hasLength(2));
expect(decoded[0], theme.copyWith(id: decoded[0].id));
expect(decoded[1].name, second.name);
expect(decoded[0].id, isNot(decoded[1].id));
});
test('bad and blank lines are skipped', () {
final text =
'\n{"name":"A","background":"#000","accent":"#fff"}\n'
'garbage\n\r\n{"name":"B","background":"#fff","accent":"#000"}\r\n';
expect(decodeThemesJsonl(text, newId: newId).map((t) => t.name), [
'A',
'B',
]);
});
test('a pretty-printed single theme is accepted', () {
const text =
'{\n "name": "Pretty",\n "background": "#000",\n'
' "accent": "#fff"\n}\n';
expect(decodeThemesJsonl(text, newId: newId).single.name, 'Pretty');
});
test('file stems are safe', () {
expect(themeFileStem('My Cool Theme!'), 'my-cool-theme');
expect(themeFileStem(' '), 'theme');
});
test('import skips duplicates and assigns unique IDs', () async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
final service = AppSettingsService();
final themes = decodeThemesJsonl(
encodeThemesJsonl([theme, CustomTheme.presets.first]),
newId: service.newCustomThemeId,
);
expect(await service.importCustomThemes(themes), 2);
final again = decodeThemesJsonl(
encodeThemesJsonl([theme]),
newId: service.newCustomThemeId,
);
expect(await service.importCustomThemes(again), 0);
final ids = service.settings.customThemes.map((t) => t.id).toSet();
expect(ids, hasLength(2));
});
});
}
@@ -0,0 +1,76 @@
import 'dart:typed_data';
import 'package:flutter/material.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/contact.dart';
import 'package:meshcore_open/screens/repeater_settings_screen.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
void main() {
// Regression: the Advanced and Identity Keys cards keep their expanded flag
// in PageStorage. Their TextFields' inner Scrollables used to share that
// identifier, read the bool as a scroll offset and fail to build (a grey
// box in release builds).
testWidgets('expanding Advanced and Identity Keys builds their text fields', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
// Tall enough that both cards fit without scrolling.
tester.view.physicalSize = const Size(1080, 24000);
tester.view.devicePixelRatio = 2.6;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => MeshCoreConnector()),
ChangeNotifierProvider(create: (_) => AppSettingsService()),
],
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: RepeaterSettingsScreen(
repeater: Contact(
publicKey: Uint8List(32),
name: 'Repeater',
type: 2,
pathLength: 0,
path: Uint8List(0),
lastSeen: DateTime(2026),
),
password: 'x',
),
),
),
);
await tester.pump(const Duration(milliseconds: 500));
final l10n = AppLocalizations.of(
tester.element(find.byType(RepeaterSettingsScreen)),
);
for (final title in [
l10n.repeater_advancedSettings,
l10n.repeater_keySettings,
]) {
await tester.tap(find.text(title));
await tester.pump(const Duration(seconds: 1));
expect(tester.takeException(), isNull);
}
expect(
find.widgetWithText(TextField, l10n.repeater_txDelay),
findsOneWidget,
);
expect(
find.widgetWithText(TextField, l10n.repeater_prvKey),
findsOneWidget,
);
});
}
@@ -0,0 +1,260 @@
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:koni_jxl_flutter/koni_jxl_flutter.dart';
import 'package:meshcore_open/models/chat_background.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/chat_background_image_store.dart';
import 'package:meshcore_open/services/chat_background_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/widgets/chat_background.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _green = Color(0xFF166534);
const _navy = Color(0xFF1E3A8A);
CustomTheme _theme({ChatBackground? background, bool everywhere = false}) =>
CustomTheme(
id: 'custom:bg',
name: 'Bg',
background: const Color(0xFF000000),
accent: const Color(0xFFFACC15),
chatBackground: background,
chatBackgroundEverywhere: everywhere,
);
Future<Uint8List> _pngBytes(int width, int height) async {
final recorder = ui.PictureRecorder();
ui.Canvas(recorder).drawRect(
ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
ui.Paint()..color = const Color(0xFF3366CC),
);
final image = await recorder.endRecording().toImage(width, height);
final data = await image.toByteData(format: ui.ImageByteFormat.png);
image.dispose();
return data!.buffer.asUint8List();
}
void main() {
late AppSettingsService settings;
late InMemoryChatBackgroundImageStore images;
late ChatBackgroundService service;
setUp(() async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
// A date with no holiday nearby, so no automatic holiday theme (and its
// chat background) gets in the way.
settings = AppSettingsService(clock: () => DateTime(2026, 7, 1));
images = InMemoryChatBackgroundImageStore();
service = ChatBackgroundService(settings, imageStore: images);
});
group('ChatBackground', () {
test('storage JSON round-trips and fade is clamped', () {
const color = ChatBackground.color(_green, fade: 0.5);
expect(ChatBackground.fromJson(color.toJson()), color);
const image = ChatBackground.image('abc', fade: 0.3);
expect(ChatBackground.fromJson(image.toJson()), image);
expect(
ChatBackground.fromJson({'color': '#000000', 'fade': 5})!.fade,
ChatBackground.maxFade,
);
expect(ChatBackground.fromJson({'fade': 0.5}), isNull);
});
test('share JSON carries colors and attached pictures only', () {
expect(const ChatBackground.image('abc').toShareJson(), isNull);
final withBytes = const ChatBackground.image(
'abc',
).withInlineImage(Uint8List.fromList([1, 2, 3]));
final shared = ChatBackground.fromJson(withBytes.toShareJson())!;
expect(shared.inlineImage, [1, 2, 3]);
expect(shared.imageId, isNull);
});
});
group('themes', () {
test('chat background persists with the theme', () {
final theme = _theme(
background: const ChatBackground.image('pic'),
everywhere: true,
);
expect(CustomTheme.fromJson(theme.toJson()), theme);
});
test('share codes keep colors but never a local image ID', () {
final colored = _theme(
background: const ChatBackground.color(_navy),
everywhere: true,
);
final shared = CustomTheme.fromShareCode(
colored.toShareCode(),
newId: 'x',
)!;
expect(shared.chatBackground, colored.chatBackground);
expect(shared.chatBackgroundEverywhere, isTrue);
final pictured = _theme(background: const ChatBackground.image('pic'));
final noBytes = CustomTheme.fromShareCode(
pictured.toShareCode(),
newId: 'x',
)!;
expect(noBytes.chatBackground, isNull);
// A hand-written code pointing at a local ID is ignored too.
final forged = CustomTheme.fromShareCode(
'{"name":"F","background":"#000","accent":"#fff",'
'"chatBackground":{"image":"pic"}}',
newId: 'x',
)!;
expect(forged.chatBackground, isNull);
});
});
group('resolve', () {
const key = 'channel:abc';
test('chat background beats the theme by default', () async {
expect(service.resolve(key), isNull);
await settings.saveCustomTheme(
_theme(background: const ChatBackground.color(_navy)),
apply: true,
);
expect(service.resolve(key)?.color, _navy);
expect(service.overridingTheme, isNull);
await service.setChatBackground(key, const ChatBackground.color(_green));
expect(service.resolve(key)?.color, _green);
expect(service.resolve('channel:other')?.color, _navy);
});
test('"use in every chat" lets the theme win', () async {
await service.setChatBackground(key, const ChatBackground.color(_green));
await settings.saveCustomTheme(
_theme(background: const ChatBackground.color(_navy), everywhere: true),
apply: true,
);
expect(service.resolve(key)?.color, _navy);
expect(service.overridingTheme?.name, 'Bg');
// The chat keeps its own choice for when the theme changes.
expect(service.chatBackground(key)?.color, _green);
await settings.setActiveTheme(null);
expect(service.resolve(key)?.color, _green);
});
test('per-chat backgrounds survive a restart', () async {
await service.setChatBackground(
key,
const ChatBackground.color(_green, fade: 0.7),
);
final reloaded = ChatBackgroundService(settings, imageStore: images);
expect(reloaded.chatBackground(key), service.chatBackground(key));
await service.setChatBackground(key, null);
expect(
ChatBackgroundService(settings, imageStore: images).chatBackground(key),
isNull,
);
});
});
group('pictures', () {
testWidgets('are shrunk and stored as JPEG XL', (tester) async {
final id = await tester.runAsync(() async {
return service.addImage(await _pngBytes(1600, 800));
});
expect(id, isNotNull);
final stored = images.images[id]!;
expect(looksLikeJxl(stored), isTrue);
final size = await tester.runAsync(() async {
final image = await decodeJxlToUiImage(stored);
final s = Size(image.width.toDouble(), image.height.toDouble());
image.dispose();
return s;
});
expect(size, const Size(1080, 540));
expect(
await tester.runAsync(
() => service.addImage(Uint8List.fromList([1, 2, 3])),
),
isNull,
);
});
testWidgets('travel with themes and come back as stored pictures', (
tester,
) async {
final id = (await tester.runAsync(
() async => service.addImage(await _pngBytes(40, 30)),
))!;
final theme = _theme(background: ChatBackground.image(id, fade: 0.5));
final embedded = (await tester.runAsync(
() => service.embedThemeImages(theme),
))!;
final code = embedded.toShareCode();
final received = CustomTheme.fromShareCode(code, newId: 'new')!;
expect(received.chatBackground!.inlineImage, isNotNull);
final stored = (await tester.runAsync(
() => service.storeThemeImages(received),
))!;
final storedId = stored.chatBackground!.imageId!;
expect(images.images[storedId], isNotNull);
expect(stored.chatBackground!.inlineImage, isNull);
expect(stored.chatBackground!.fade, 0.5);
});
testWidgets('unused pictures are cleaned up', (tester) async {
await tester.runAsync(() async {
final kept = (await service.addImage(await _pngBytes(20, 20)))!;
final themed = (await service.addImage(await _pngBytes(21, 20)))!;
final orphan = (await service.addImage(await _pngBytes(22, 20)))!;
await service.setChatBackground(
'contact:a',
ChatBackground.image(kept),
);
await settings.saveCustomTheme(
_theme(background: ChatBackground.image(themed)),
);
await service.collectGarbage();
expect(images.images.keys, unorderedEquals([kept, themed]));
expect(images.images.containsKey(orphan), isFalse);
});
});
});
testWidgets('ChatBackdrop paints the resolved background', (tester) async {
await service.setChatBackground(
'contact:a',
const ChatBackground.color(_green),
);
Widget host(String key) => ChangeNotifierProvider.value(
value: service,
child: MaterialApp(
home: ChatBackdrop(chatKey: key, child: const Text('hi')),
),
);
await tester.pumpWidget(host('contact:a'));
expect(find.byType(ChatBackgroundLayer), findsOneWidget);
expect(find.text('hi'), findsOneWidget);
await tester.pumpWidget(host('contact:b'));
expect(find.byType(ChatBackgroundLayer), findsNothing);
// Works (and draws nothing) without the service, e.g. in older tests.
await tester.pumpWidget(
const MaterialApp(
home: ChatBackdrop(chatKey: 'x', child: Text('hi')),
),
);
expect(find.text('hi'), findsOneWidget);
});
}
+278
View File
@@ -0,0 +1,278 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/models/holiday_schedule.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const halloween = 'preset:halloween';
const thanksgiving = 'preset:thanksgiving';
const christmas = 'preset:christmas';
const newYear = 'preset:new_year';
String? holidayOn(int year, int month, int day) =>
activeHolidayFor(DateTime(year, month, day, 13, 30))?.themeId;
void main() {
group('holiday dates', () {
test('Thanksgiving is the fourth Thursday of November', () {
expect(ThemeHoliday.thanksgiving.dateIn(2024), DateTime(2024, 11, 28));
expect(ThemeHoliday.thanksgiving.dateIn(2025), DateTime(2025, 11, 27));
expect(ThemeHoliday.thanksgiving.dateIn(2026), DateTime(2026, 11, 26));
expect(ThemeHoliday.thanksgiving.dateIn(2029), DateTime(2029, 11, 22));
expect(ThemeHoliday.thanksgiving.dateIn(2018), DateTime(2018, 11, 22));
});
test('preset ids exist', () {
for (final holiday in ThemeHoliday.values) {
expect(CustomTheme.presetById(holiday.themeId), isNotNull);
}
});
});
group('activeHolidayFor', () {
test('Halloween window', () {
expect(holidayOn(2026, 10, 13), isNull);
expect(holidayOn(2026, 10, 14), halloween);
expect(holidayOn(2026, 10, 31), halloween);
});
test('Thanksgiving 2026 (Nov 26) window', () {
expect(holidayOn(2026, 11, 1), isNull);
expect(holidayOn(2026, 11, 8), isNull);
expect(holidayOn(2026, 11, 9), thanksgiving);
expect(holidayOn(2026, 11, 26), thanksgiving);
});
test('Nov 1 is Thanksgiving when it falls within 17 days', () {
// Thanksgiving 2029 is Nov 22, 21 days after Nov 1: none.
expect(holidayOn(2029, 11, 1), isNull);
// Thanksgiving 2018 was Nov 22 too; Nov 5 is exactly 17 days out.
expect(holidayOn(2018, 11, 5), thanksgiving);
expect(holidayOn(2018, 11, 4), isNull);
});
test('Thanksgiving holds until its day, then Christmas waits its turn', () {
// Thanksgiving is at the latest Nov 28 and Christmas' window opens
// Dec 8, so those two never compete; the days between have no theme.
expect(holidayOn(2024, 11, 28), thanksgiving);
expect(holidayOn(2024, 11, 29), isNull);
expect(holidayOn(2024, 12, 7), isNull);
expect(holidayOn(2024, 12, 8), christmas);
});
test('Christmas and New Year windows', () {
expect(holidayOn(2026, 12, 7), isNull);
expect(holidayOn(2026, 12, 8), christmas);
// Dec 15 is within 17 days of New Year's too; Christmas is nearer.
expect(holidayOn(2026, 12, 15), christmas);
expect(holidayOn(2026, 12, 25), christmas);
expect(holidayOn(2026, 12, 26), newYear);
expect(holidayOn(2026, 12, 31), newYear);
expect(holidayOn(2027, 1, 1), newYear);
expect(holidayOn(2027, 1, 2), isNull);
});
test('year wrap gives the coming New Year occurrence', () {
final active = activeHolidayFor(DateTime(2026, 12, 26))!;
expect(active.date, DateTime(2027, 1, 1));
expect(active.daysAway, 6);
expect(active.occurrenceKey, 'preset:new_year@2027-01-01');
});
test('no holiday in spring or summer', () {
expect(holidayOn(2026, 3, 15), isNull);
expect(holidayOn(2026, 7, 4), isNull);
});
});
group('settings JSON', () {
test('auto switch defaults to true', () {
expect(AppSettings().holidayAutoSwitch, isTrue);
expect(AppSettings.fromJson({}).holidayAutoSwitch, isTrue);
expect(AppSettings().holidayThemeDismissed, isNull);
});
test('round-trips', () {
final settings = AppSettings(
holidayAutoSwitch: false,
holidayThemeDismissed: 'preset:christmas@2026-12-25',
);
final decoded = AppSettings.fromJson(
jsonDecode(jsonEncode(settings.toJson())) as Map<String, dynamic>,
);
expect(decoded.holidayAutoSwitch, isFalse);
expect(decoded.holidayThemeDismissed, 'preset:christmas@2026-12-25');
expect(settings.toJson()['holiday_auto_switch'], isFalse);
});
test('copyWith can clear the dismissal', () {
final settings = AppSettings(holidayThemeDismissed: 'x');
expect(settings.copyWith().holidayThemeDismissed, 'x');
expect(
settings.copyWith(holidayThemeDismissed: null).holidayThemeDismissed,
isNull,
);
});
});
group('AppSettingsService', () {
late DateTime now;
late AppSettingsService service;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
now = DateTime(2026, 7, 1, 12);
service = AppSettingsService(clock: () => now);
await service.loadSettings();
});
tearDown(() => service.dispose());
test('holiday theme overrides without touching activeThemeId', () async {
await service.setActiveTheme('preset:forest');
final ownId = service.settings.activeThemeId;
expect(service.activeCustomTheme?.id, ownId);
now = DateTime(2026, 12, 10, 9);
expect(service.activeCustomTheme?.id, christmas);
expect(service.autoHolidayTheme?.id, christmas);
expect(service.settings.activeThemeId, ownId);
expect(service.chosenCustomTheme?.id, ownId);
now = DateTime(2027, 1, 2, 9);
expect(service.activeCustomTheme?.id, ownId);
expect(service.autoHolidayTheme, isNull);
});
test('stock theme users get the holiday theme too', () {
now = DateTime(2026, 10, 31, 20);
expect(service.settings.activeThemeId, isNull);
expect(service.activeCustomTheme?.id, halloween);
});
test('manual pick dismisses only the current occurrence', () async {
now = DateTime(2026, 10, 20);
expect(service.activeCustomTheme?.id, halloween);
await service.setActiveTheme(null);
expect(service.activeCustomTheme, isNull);
expect(
service.settings.holidayThemeDismissed,
'preset:halloween@2026-10-31',
);
now = DateTime(2026, 10, 31, 23);
expect(service.activeCustomTheme, isNull);
// Next holiday switches again.
now = DateTime(2026, 11, 20);
expect(service.activeCustomTheme?.id, thanksgiving);
// Next year's Halloween too.
now = DateTime(2027, 10, 20);
expect(service.activeCustomTheme?.id, halloween);
});
test('picking a stock mode dismisses too', () async {
now = DateTime(2026, 12, 20);
expect(service.activeCustomTheme?.id, christmas);
await service.setThemeMode('dark');
expect(service.activeCustomTheme, isNull);
expect(service.settings.themeMode, 'dark');
now = DateTime(2026, 12, 26);
expect(service.activeCustomTheme?.id, newYear);
});
test(
'picking the auto-applied holiday preset is not a dismissal',
() async {
await service.setActiveTheme('preset:forest');
final ownId = service.settings.activeThemeId;
now = DateTime(2026, 12, 20);
await service.setActiveTheme(christmas);
expect(service.settings.holidayThemeDismissed, isNull);
expect(service.settings.activeThemeId, ownId);
expect(service.activeCustomTheme?.id, christmas);
now = DateTime(2027, 1, 5);
expect(service.activeCustomTheme?.id, ownId);
},
);
test('a user who picked the holiday preset keeps it', () async {
await service.setActiveTheme(halloween);
now = DateTime(2026, 10, 20);
expect(service.autoHolidayTheme, isNull);
expect(service.activeCustomTheme?.id, halloween);
now = DateTime(2026, 11, 1);
expect(service.activeCustomTheme?.id, halloween);
});
test('auto switch off keeps the user theme', () async {
await service.setHolidayAutoSwitch(false);
now = DateTime(2026, 12, 25);
expect(service.activeCustomTheme, isNull);
expect(service.autoHolidayTheme, isNull);
await service.setHolidayAutoSwitch(true);
expect(service.activeCustomTheme?.id, christmas);
});
test('turning auto switch back on forgets the dismissal', () async {
now = DateTime(2026, 12, 20);
await service.setThemeMode('light');
expect(service.activeCustomTheme, isNull);
await service.setHolidayAutoSwitch(false);
await service.setHolidayAutoSwitch(true);
expect(service.settings.holidayThemeDismissed, isNull);
expect(service.activeCustomTheme?.id, christmas);
});
test('date timer runs only once started and while enabled', () async {
expect(service.hasDateTimer, isFalse);
service.startDateWatch();
expect(service.hasDateTimer, isTrue);
await service.setHolidayAutoSwitch(false);
expect(service.hasDateTimer, isFalse);
await service.setHolidayAutoSwitch(true);
expect(service.hasDateTimer, isTrue);
service.dispose();
expect(service.hasDateTimer, isFalse);
// tearDown disposes again; use a fresh service there.
service = AppSettingsService(clock: () => now);
});
test('date change notifies only when the holiday theme changes', () {
now = DateTime(2026, 12, 6, 23);
service.startDateWatch();
var notified = 0;
service.addListener(() => notified++);
now = DateTime(2026, 12, 7, 0, 0, 1);
service.checkDateChange();
expect(notified, 0);
now = DateTime(2026, 12, 8, 0, 0, 1);
service.checkDateChange();
expect(notified, 1);
expect(service.activeCustomTheme?.id, christmas);
now = DateTime(2026, 12, 9, 0, 0, 1);
service.checkDateChange();
expect(notified, 1);
now = DateTime(2026, 12, 26, 0, 0, 1);
service.checkDateChange();
expect(notified, 2);
expect(service.activeCustomTheme?.id, newYear);
});
});
}
@@ -61,34 +61,30 @@ int _readIntOption(Socket socket, int level, int option) {
}
void main() {
test(
'connect enables TCP keepalive with short probe timings',
() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final overrides = _CapturingConnectOverrides();
final service = TcpTransportService();
try {
await IOOverrides.runZoned(
() => service.connect(
host: InternetAddress.loopbackIPv4.address,
port: server.port,
),
socketConnect: overrides.socketConnect,
);
final socket = overrides.socket!;
// Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5,
// TCP_KEEPCNT 6.
expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3);
} finally {
await service.disconnect();
await server.close();
}
},
skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones',
);
test('connect enables TCP keepalive with short probe timings', () async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final overrides = _CapturingConnectOverrides();
final service = TcpTransportService();
try {
await IOOverrides.runZoned(
() => service.connect(
host: InternetAddress.loopbackIPv4.address,
port: server.port,
),
socketConnect: overrides.socketConnect,
);
final socket = overrides.socket!;
// Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5,
// TCP_KEEPCNT 6.
expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10);
expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3);
} finally {
await service.disconnect();
await server.close();
}
}, skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones');
test('connect/disconnect updates TCP transport state', () async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+124
View File
@@ -0,0 +1,124 @@
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/custom_theme.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/map_tile_cache_service.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/quick_switch_bar.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
final custom = CustomTheme.holidayPresets.first;
test('stock themes keep the fixed map palette', () {
for (final data in [MeshTheme.dark(), MeshTheme.light()]) {
final map = data.extension<MeshMapTheme>()!;
expect(map.accent, MapPalette.selected);
expect(map.tileTint, isNull);
expect(map.followsTheme, isFalse);
}
});
test('custom themes tint the map with their own colors', () {
final map = MeshTheme.fromCustom(custom).extension<MeshMapTheme>()!;
expect(map.accent, custom.accent);
expect(map.tileTint, custom.background);
expect(map.followsTheme, isTrue);
});
group('tile layer', () {
late MapTileCacheService tiles;
setUp(() async {
SharedPreferences.setMockInitialValues({});
await PrefsManager.initialize();
tiles = MapTileCacheService(
appSettingsService: AppSettingsService(),
cacheManager: _NoCache(),
);
});
Future<List<ColorFiltered>> filtersFor(
WidgetTester tester,
ThemeData theme,
) async {
late Widget layer;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Builder(
builder: (context) {
layer = tiles.buildTileLayer(context);
return const SizedBox();
},
),
),
);
final found = <ColorFiltered>[];
Widget? w = layer;
while (w is ColorFiltered) {
found.add(w);
w = w.child;
}
return found;
}
testWidgets('custom themes wash their background over the tiles', (
tester,
) async {
final filters = await filtersFor(tester, MeshTheme.fromCustom(custom));
expect(
filters.first.colorFilter,
ColorFilter.mode(
custom.background.withValues(alpha: MeshMapTheme.tileTintStrength),
BlendMode.srcATop,
),
);
});
testWidgets('the stock light theme leaves tiles untouched', (tester) async {
expect(await filtersFor(tester, MeshTheme.light()), isEmpty);
});
});
testWidgets('map tab bar follows a custom theme', (tester) async {
Future<Color?> panelColor(ThemeData theme) async {
await tester.pumpWidget(
MaterialApp(
theme: theme,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: QuickSwitchBar(
selectedIndex: 2,
onDestinationSelected: (_) {},
highContrast: true,
),
),
),
);
await tester.pumpAndSettle(); // theme changes animate
final box = tester.widget<DecoratedBox>(
find
.descendant(
of: find.byType(QuickSwitchBar),
matching: find.byType(DecoratedBox),
)
.first,
);
return (box.decoration as BoxDecoration).color;
}
expect(await panelColor(MeshTheme.dark()), MapPalette.panelDark);
expect(await panelColor(MeshTheme.fromCustom(custom)), Colors.transparent);
});
}
/// Never touched: these tests only inspect the widget tree.
class _NoCache implements BaseCacheManager {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
+29
View File
@@ -0,0 +1,29 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/theme/mesh_theme.dart';
import 'package:meshcore_open/widgets/mesh_ui.dart';
void main() {
// Amber on its own pale tint in the light theme was about 2:1.
final lightTint = Color.alphaBlend(
MeshPalette.warn.withValues(alpha: 0.12),
MeshPalette.lightBg1,
);
final darkTint = Color.alphaBlend(
MeshPalette.warn.withValues(alpha: 0.12),
MeshPalette.bg1,
);
test('darkens an accent on a light background until it is readable', () {
expect(meshContrastRatio(MeshPalette.warn, lightTint), lessThan(3));
final text = readableAccent(MeshPalette.warn, lightTint);
expect(meshContrastRatio(text, lightTint), greaterThanOrEqualTo(4.5));
final icon = readableAccent(MeshPalette.warn, lightTint, minContrast: 3);
expect(meshContrastRatio(icon, lightTint), greaterThanOrEqualTo(3));
});
test('keeps an accent that is already readable', () {
expect(readableAccent(MeshPalette.warn, darkTint), MeshPalette.warn);
});
}