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

+211 -1
View File
@@ -1,6 +1,9 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../models/app_settings.dart';
import '../models/custom_theme.dart';
import '../models/holiday_schedule.dart';
import '../models/image_codec_support.dart';
import '../models/translation_support.dart';
@@ -12,6 +15,12 @@ import '../helpers/cyr2lat.dart';
class AppSettingsService extends ChangeNotifier {
static const String _settingsKey = 'app_settings';
/// [clock] supplies "now" for the holiday theme schedule; tests inject one.
AppSettingsService({DateTime Function()? clock})
: _clock = clock ?? DateTime.now;
final DateTime Function() _clock;
AppSettings _settings = AppSettings();
AppSettings get settings => _settings;
@@ -55,11 +64,14 @@ class AppSettingsService extends ChangeNotifier {
_settings = AppSettings();
Cyr2Lat.setCharMap(_settings.cyr2latCharMap);
}
_syncDateTimer();
}
Future<void> updateSettings(AppSettings newSettings) async {
_settings = newSettings;
Cyr2Lat.setCharMap(_settings.cyr2latCharMap);
_lastAutoHolidayKey = autoHoliday?.occurrenceKey;
_syncDateTimer();
notifyListeners();
final prefs = PrefsManager.instance;
@@ -234,8 +246,206 @@ class AppSettingsService extends ChangeNotifier {
);
}
/// Picks a stock light/dark/system mode and leaves any custom theme.
///
/// Counts as a manual choice: an automatically applied holiday theme is
/// skipped for the rest of that holiday.
Future<void> setThemeMode(String value) async {
await updateSettings(_settings.copyWith(themeMode: value));
await updateSettings(
_dismissAutoHoliday(
_settings.copyWith(themeMode: value, activeThemeId: null),
),
);
}
Future<void> setHolidayAnimationsEnabled(bool value) async {
await updateSettings(_settings.copyWith(holidayAnimationsEnabled: value));
}
/// The theme in use, or null for the stock theme: the automatic holiday
/// theme while one applies ([autoHolidayTheme]), otherwise the user's own
/// choice ([AppSettings.activeThemeId]).
CustomTheme? get activeCustomTheme =>
autoHolidayTheme ?? _themeById(_settings.activeThemeId);
/// The user's own chosen theme, ignoring any automatic holiday theme.
CustomTheme? get chosenCustomTheme => _themeById(_settings.activeThemeId);
CustomTheme? _themeById(String? id) {
if (id == null) return null;
return CustomTheme.presetById(id) ??
_settings.customThemes.where((t) => t.id == id).firstOrNull;
}
/// The holiday within its window today, if auto-switching is on and the
/// user has not overridden this occurrence. Null otherwise.
ActiveHoliday? get autoHoliday {
if (!_settings.holidayAutoSwitch) return null;
final holiday = activeHolidayFor(_clock());
if (holiday == null) return null;
if (_settings.holidayThemeDismissed == holiday.occurrenceKey) return null;
// The user picked this holiday's theme themselves: nothing to override.
if (_settings.activeThemeId == holiday.themeId) return null;
return holiday;
}
/// The holiday preset being applied automatically in place of the user's
/// own theme, or null when none is.
CustomTheme? get autoHolidayTheme {
final holiday = autoHoliday;
return holiday == null ? null : CustomTheme.presetById(holiday.themeId);
}
/// Marks the automatically applied holiday (if any) as overridden for this
/// occurrence, so a manual theme choice sticks until the holiday is over.
AppSettings _dismissAutoHoliday(AppSettings next) {
final holiday = autoHoliday;
if (holiday == null) return next;
return next.copyWith(holidayThemeDismissed: holiday.occurrenceKey);
}
/// Applies a custom or preset theme; null returns to the stock theme.
///
/// Picking a theme while a holiday theme is applied automatically keeps
/// the pick for the rest of that holiday. Picking the automatic holiday
/// theme itself changes nothing, so the user's own theme still returns
/// after the holiday.
Future<void> setActiveTheme(String? themeId) async {
final holiday = autoHoliday;
if (holiday != null && themeId == holiday.themeId) return;
await updateSettings(
_dismissAutoHoliday(_settings.copyWith(activeThemeId: themeId)),
);
}
/// Turns automatic holiday themes on or off. Turning it on also forgets an
/// earlier override, so the current holiday's theme shows again.
Future<void> setHolidayAutoSwitch(bool value) async {
await updateSettings(
_settings.copyWith(
holidayAutoSwitch: value,
holidayThemeDismissed: value ? null : _settings.holidayThemeDismissed,
),
);
}
// ---- date-change refresh --------------------------------------------------
// The automatic holiday theme depends on the date. Once [startDateWatch] has
// been called (the app does so at startup; tests normally don't), a timer
// wakes at the next local midnight, or after an hour at most in case the
// device slept through it, and tells listeners if the holiday theme
// changed. It only runs while auto-switching is on.
static const Duration _maxDateCheckInterval = Duration(hours: 1);
Timer? _dateTimer;
bool _dateWatchStarted = false;
String? _lastAutoHolidayKey;
/// Starts re-checking the automatic holiday theme when the date changes.
void startDateWatch() {
_dateWatchStarted = true;
_lastAutoHolidayKey = autoHoliday?.occurrenceKey;
_syncDateTimer();
}
void _syncDateTimer() {
final wanted = _dateWatchStarted && _settings.holidayAutoSwitch;
if (!wanted) {
_dateTimer?.cancel();
_dateTimer = null;
} else if (_dateTimer == null) {
_scheduleDateTimer();
}
}
void _scheduleDateTimer() {
final now = _clock();
// A second past midnight so a slightly early wake-up still sees the new
// day.
final nextMidnight = DateTime(now.year, now.month, now.day + 1, 0, 0, 1);
var delay = nextMidnight.difference(now);
if (delay > _maxDateCheckInterval) delay = _maxDateCheckInterval;
_dateTimer = Timer(delay, () {
_dateTimer = null;
checkDateChange();
_syncDateTimer();
});
}
/// Notifies listeners if the automatic holiday theme differs from the one
/// last seen. Called by the date timer; public so tests can drive it.
@visibleForTesting
void checkDateChange() {
final key = autoHoliday?.occurrenceKey;
if (key == _lastAutoHolidayKey) return;
_lastAutoHolidayKey = key;
notifyListeners();
}
@visibleForTesting
bool get hasDateTimer => _dateTimer != null;
@override
void dispose() {
_dateTimer?.cancel();
_dateTimer = null;
super.dispose();
}
/// Adds [theme] or replaces the saved theme with the same ID.
Future<void> saveCustomTheme(CustomTheme theme, {bool apply = false}) async {
final themes = List<CustomTheme>.from(_settings.customThemes);
final index = themes.indexWhere((t) => t.id == theme.id);
if (index >= 0) {
themes[index] = theme;
} else {
themes.add(theme);
}
final next = _settings.copyWith(
customThemes: themes,
activeThemeId: apply ? theme.id : _settings.activeThemeId,
);
// Applying a theme is a manual choice, like [setActiveTheme].
await updateSettings(apply ? _dismissAutoHoliday(next) : next);
}
Future<void> deleteCustomTheme(String themeId) async {
final themes = _settings.customThemes
.where((t) => t.id != themeId)
.toList();
await updateSettings(
_settings.copyWith(
customThemes: themes,
activeThemeId: _settings.activeThemeId == themeId
? null
: _settings.activeThemeId,
),
);
}
/// A fresh ID for a new custom theme.
/// The counter keeps IDs unique when several are made in the same tick
/// (bulk imports; web clocks only tick in milliseconds).
String newCustomThemeId() =>
'custom:${DateTime.now().microsecondsSinceEpoch}-${_themeIdCounter++}';
int _themeIdCounter = 0;
/// Adds [themes], skipping any identical (apart from ID) to a saved one.
/// Returns how many were added.
Future<int> importCustomThemes(List<CustomTheme> themes) async {
final existing = List<CustomTheme>.from(_settings.customThemes);
var added = 0;
for (final theme in themes) {
final duplicate = existing.any((t) => t == theme.copyWith(id: t.id));
if (duplicate) continue;
existing.add(theme);
added++;
}
if (added > 0) {
await updateSettings(_settings.copyWith(customThemes: existing));
}
return added;
}
Future<void> setLanguageOverride(String? value) async {
@@ -0,0 +1,7 @@
/// Platform-appropriate [ChatBackgroundImageStore], chosen at compile time
/// (`dart:io` files natively, preferences on web).
library;
export 'chat_background_image_store_base.dart';
export 'chat_background_image_store_stub.dart'
if (dart.library.io) 'chat_background_image_store_io.dart';
@@ -0,0 +1,26 @@
import 'dart:typed_data';
/// Stores chat background pictures by content ID.
abstract class ChatBackgroundImageStore {
Future<void> write(String id, Uint8List bytes);
Future<Uint8List?> read(String id);
Future<void> delete(String id);
Future<Set<String>> listIds();
}
/// For tests.
class InMemoryChatBackgroundImageStore implements ChatBackgroundImageStore {
final Map<String, Uint8List> images = {};
@override
Future<void> write(String id, Uint8List bytes) async => images[id] = bytes;
@override
Future<Uint8List?> read(String id) async => images[id];
@override
Future<void> delete(String id) async => images.remove(id);
@override
Future<Set<String>> listIds() async => images.keys.toSet();
}
@@ -0,0 +1,59 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';
import 'chat_background_image_store_base.dart';
ChatBackgroundImageStore createChatBackgroundImageStore() =>
_FileChatBackgroundImageStore();
/// One JPEG XL file per picture under `<app support>/chat_backgrounds/`.
class _FileChatBackgroundImageStore implements ChatBackgroundImageStore {
Directory? _dir;
Future<Directory> _directory() async {
final existing = _dir;
if (existing != null) return existing;
final base = await getApplicationSupportDirectory();
final dir = Directory('${base.path}/chat_backgrounds');
await dir.create(recursive: true);
return _dir = dir;
}
Future<File> _file(String id) async =>
File('${(await _directory()).path}/$id.jxl');
@override
Future<void> write(String id, Uint8List bytes) async {
final file = await _file(id);
final temp = File('${file.path}.tmp');
await temp.writeAsBytes(bytes, flush: true);
await temp.rename(file.path);
}
@override
Future<Uint8List?> read(String id) async {
final file = await _file(id);
if (!await file.exists()) return null;
return file.readAsBytes();
}
@override
Future<void> delete(String id) async {
final file = await _file(id);
if (await file.exists()) await file.delete();
}
@override
Future<Set<String>> listIds() async {
final dir = await _directory();
return dir
.listSync()
.whereType<File>()
.map((f) => f.uri.pathSegments.last)
.where((name) => name.endsWith('.jxl'))
.map((name) => name.substring(0, name.length - 4))
.toSet();
}
}
@@ -0,0 +1,42 @@
import 'dart:convert';
import 'dart:typed_data';
import '../storage/prefs_manager.dart';
import 'chat_background_image_store_base.dart';
ChatBackgroundImageStore createChatBackgroundImageStore() =>
_PrefsChatBackgroundImageStore();
/// Web: pictures are base64 in preferences (browser local storage). They are
/// small JPEG XL files, so a handful fit comfortably in the storage quota.
class _PrefsChatBackgroundImageStore implements ChatBackgroundImageStore {
static const _prefix = 'chat_bg_image_';
@override
Future<void> write(String id, Uint8List bytes) async {
await PrefsManager.instance.setString('$_prefix$id', base64Encode(bytes));
}
@override
Future<Uint8List?> read(String id) async {
final value = PrefsManager.instance.getString('$_prefix$id');
if (value == null) return null;
try {
return base64Decode(value);
} on FormatException {
return null;
}
}
@override
Future<void> delete(String id) async {
await PrefsManager.instance.remove('$_prefix$id');
}
@override
Future<Set<String>> listIds() async => PrefsManager.instance
.getKeys()
.where((k) => k.startsWith(_prefix))
.map((k) => k.substring(_prefix.length))
.toSet();
}
+237
View File
@@ -0,0 +1,237 @@
import 'dart:async';
import 'dart:convert';
import 'dart:ui' as ui;
import 'package:crypto/crypto.dart' as crypto;
import 'package:flutter/foundation.dart';
import 'package:koni_jxl_flutter/koni_jxl_flutter.dart';
import '../models/channel.dart';
import '../models/chat_background.dart';
import '../models/contact.dart';
import '../models/custom_theme.dart';
import '../storage/prefs_manager.dart';
import '../utils/app_logger.dart';
import 'app_settings_service.dart';
import 'chat_background_image_store.dart';
/// Chat backgrounds: one per channel or DM, plus the active theme's.
///
/// A chat's own background wins over the theme's, unless the theme turns on
/// [CustomTheme.chatBackgroundEverywhere]. Settings are global (not per
/// radio): channels are keyed by their PSK-derived storage ID and DMs by the
/// contact's public key, both of which identify the chat on any radio.
class ChatBackgroundService extends ChangeNotifier {
static const _prefsKey = 'chat_backgrounds_v1';
/// Longest side of a stored picture, in pixels.
static const int maxImageSide = 1080;
/// JPEG XL lossy "distance" (cjxl-style; 1 is visually lossless). A chat
/// background is shown faded behind messages, so 2 keeps it sharp at a
/// fraction of the size.
static const double jxlDistance = 2.0;
final AppSettingsService _settings;
final ChatBackgroundImageStore _images;
final Map<String, ChatBackground> _byChat = {};
final Map<String, Uint8List> _imageCache = {};
final Set<String> _loading = {};
ChatBackgroundService(this._settings, {ChatBackgroundImageStore? imageStore})
: _images = imageStore ?? createChatBackgroundImageStore() {
_load();
_settings.addListener(notifyListeners);
}
static String channelKey(Channel channel) =>
'channel:${channel.storageId ?? 'slot${channel.index}'}';
static String contactKey(Contact contact) =>
'contact:${contact.publicKeyHex}';
void _load() {
final raw = PrefsManager.instance.getString(_prefsKey);
if (raw == null) return;
try {
final decoded = jsonDecode(raw);
if (decoded is! Map) return;
decoded.forEach((key, value) {
final background = ChatBackground.fromJson(value);
if (key is! String || background == null) return;
if (background.color != null || background.imageId != null) {
_byChat[key] = background;
}
});
} catch (e) {
appLogger.warn('Could not read chat backgrounds: $e');
}
}
Future<void> _save() async {
await PrefsManager.instance.setString(
_prefsKey,
jsonEncode(_byChat.map((key, value) => MapEntry(key, value.toJson()))),
);
}
/// The background this chat has been given itself (ignoring the theme).
ChatBackground? chatBackground(String chatKey) => _byChat[chatKey];
/// The theme background that will override [chatKey]'s own, if any.
CustomTheme? get overridingTheme {
final theme = _settings.activeCustomTheme;
if (theme?.chatBackground == null || !theme!.chatBackgroundEverywhere) {
return null;
}
return theme;
}
/// What to draw behind [chatKey]'s messages, or null for none.
ChatBackground? resolve(String chatKey) {
final theme = _settings.activeCustomTheme;
final themed = theme?.chatBackground;
if (themed != null && theme!.chatBackgroundEverywhere) return themed;
return _byChat[chatKey] ?? themed;
}
Future<void> setChatBackground(
String chatKey,
ChatBackground? background,
) async {
if (background == null) {
_byChat.remove(chatKey);
} else {
_byChat[chatKey] = background;
}
notifyListeners();
await _save();
}
/// Cached picture bytes, or null while they load (listeners are notified
/// once they arrive).
Uint8List? imageBytes(String imageId) {
final cached = _imageCache[imageId];
if (cached != null) return cached;
if (_loading.add(imageId)) {
unawaited(
_images.read(imageId).then((bytes) {
_loading.remove(imageId);
if (bytes == null) return;
_imageCache[imageId] = bytes;
notifyListeners();
}),
);
}
return null;
}
/// Shrinks a picture (any format Flutter or JPEG XL decodes), re-encodes
/// it as JPEG XL and stores it. Returns its ID, or null when [bytes] is not
/// a readable image.
Future<String?> addImage(Uint8List bytes) async {
final jxl = await encodeChatBackgroundJxl(bytes);
if (jxl == null) return null;
final id = crypto.sha256.convert(jxl).toString().substring(0, 20);
_imageCache[id] = jxl;
await _images.write(id, jxl);
return id;
}
/// Writes any picture carried inline by [theme] (from a share code or
/// file) to the image store, so the theme can be saved in settings.
Future<CustomTheme> storeThemeImages(CustomTheme theme) async {
final background = theme.chatBackground;
final inline = background?.inlineImage;
if (background == null || inline == null) return theme;
// Re-encode untrusted input rather than storing it verbatim.
final id = await addImage(inline);
return id == null
? theme.copyWith(chatBackground: null)
: theme.copyWith(chatBackground: background.withStoredImage(id));
}
/// Attaches the picture bytes to [theme] so its share code or file
/// carries the picture.
Future<CustomTheme> embedThemeImages(CustomTheme theme) async {
final background = theme.chatBackground;
final id = background?.imageId;
if (background == null || id == null) return theme;
final bytes = _imageCache[id] ?? await _images.read(id);
if (bytes == null) return theme;
return theme.copyWith(chatBackground: background.withInlineImage(bytes));
}
/// Deletes stored pictures no chat or saved theme uses any more.
Future<void> collectGarbage() async {
final inUse = <String>{
for (final background in _byChat.values)
if (background.imageId != null) background.imageId!,
for (final theme in _settings.settings.customThemes)
if (theme.chatBackground?.imageId != null)
theme.chatBackground!.imageId!,
};
try {
for (final id in await _images.listIds()) {
if (inUse.contains(id)) continue;
await _images.delete(id);
_imageCache.remove(id);
}
} catch (e) {
appLogger.warn('Chat background cleanup failed: $e');
}
}
@override
void dispose() {
_settings.removeListener(notifyListeners);
super.dispose();
}
}
/// Decodes [bytes], shrinks the picture to fit
/// [ChatBackgroundService.maxImageSide] and encodes it as lossy JPEG XL.
/// Returns null for unreadable input.
///
/// Non-JXL input goes through Flutter's decoder, which also applies a
/// photo's EXIF rotation.
Future<Uint8List?> encodeChatBackgroundJxl(Uint8List bytes) async {
const maxSide = ChatBackgroundService.maxImageSide;
ui.Image? image;
try {
if (looksLikeJxl(bytes)) {
image = await decodeJxlToUiImage(
bytes,
cacheWidth: maxSide,
cacheHeight: maxSide,
);
} else {
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
final codec = await ui.instantiateImageCodecWithSize(
buffer,
getTargetSize: (width, height) {
final longest = width > height ? width : height;
if (longest <= maxSide) {
return ui.TargetImageSize(width: width, height: height);
}
final scale = maxSide / longest;
return ui.TargetImageSize(
width: (width * scale).round().clamp(1, maxSide),
height: (height * scale).round().clamp(1, maxSide),
);
},
);
image = (await codec.getNextFrame()).image;
codec.dispose();
}
return await encodeJxlLossyFromUiImage(
image,
distance: ChatBackgroundService.jxlDistance,
);
} catch (e) {
appLogger.warn('Could not encode chat background: $e');
return null;
} finally {
image?.dispose();
}
}
+14
View File
@@ -6,6 +6,7 @@ import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_map/flutter_map.dart';
import '../models/app_settings.dart';
import '../theme/mesh_theme.dart';
import 'app_settings_service.dart';
enum MapRasterSourcePreset {
@@ -506,6 +507,19 @@ class MapTileCacheService extends ChangeNotifier {
layer = ColorFiltered(colorFilter: filter, child: layer);
}
// Custom themes wash their background color over the tiles so the map
// matches the rest of the app. Kept light so roads and labels stay clear.
final tint = MeshMapTheme.of(context).tileTint;
if (tint != null) {
layer = ColorFiltered(
colorFilter: ColorFilter.mode(
tint.withValues(alpha: MeshMapTheme.tileTintStrength),
BlendMode.srcATop,
),
child: layer,
);
}
if (opacity < 1) {
layer = Opacity(opacity: opacity, child: layer);
}
+16 -9
View File
@@ -359,14 +359,27 @@ class NotificationService {
),
];
// Always MessagingStyle: Android Auto only handles messaging notifications
// in that style, so an image preview is shown as the large icon instead.
AndroidNotificationDetails _androidConversationDetails(
_Conversation conversation, {
int? badgeCount,
bool silent = false,
}) {
final imagePath = conversation.imagePath;
final styleInformation = imagePath != null
? BigPictureStyleInformation(
FilePathAndroidBitmap(imagePath),
contentTitle: conversation.title,
summaryText: _collapsedBody(conversation),
showBigPictureWhenCollapsed: true,
)
: MessagingStyleInformation(
Person(key: 'self', name: _selfName ?? _l10n.notification_you),
conversationTitle: conversation.isChannel
? conversation.title
: null,
groupConversation: conversation.isChannel,
messages: List<Message>.of(conversation.messages),
);
return AndroidNotificationDetails(
conversation.isChannel ? 'channel_messages' : 'messages',
conversation.isChannel ? 'Channel Messages' : 'Messages',
@@ -379,13 +392,7 @@ class NotificationService {
number: badgeCount,
silent: silent,
category: AndroidNotificationCategory.message,
largeIcon: imagePath != null ? FilePathAndroidBitmap(imagePath) : null,
styleInformation: MessagingStyleInformation(
Person(key: 'self', name: _selfName ?? _l10n.notification_you),
conversationTitle: conversation.isChannel ? conversation.title : null,
groupConversation: conversation.isChannel,
messages: List<Message>.of(conversation.messages),
),
styleInformation: styleInformation,
actions: _conversationActions(conversation.isChannel),
);
}