Merge upstream/dev (22 commits) [upstream-sync]
build / ci-image (push) Successful in 11s
build / build (push) Successful in 26m36s

Conflicts resolved by hand, our fork changes carried over:
- MainActivity.kt: keep the unread widget hooks next to upstream's
  scroll capture (attach and detach both).
- app_settings_screen.dart: upstream wrapped the list in
  MeshSettingsTileTheme; image-message and translation sections stay
  gated on kOnDeviceMl (ML-free build).
- channel_chat_screen.dart: upstream split build() into methods; took
  theirs and re-applied the terminal-theme list padding.
- chat_composer.dart: both imports (terminal_theme, radio_guard).
- mesh_nav_tile.dart: upstream's meshTileTitleStyle, with the smaller
  terminal-theme title kept.

flutter analyze clean, flutter test 1522 passed (CI image, local).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-10 15:30:43 +01:00
commit 185d2aca53
210 files changed
+52066 -5541

No files matched your search

+10 -1
View File
@@ -2,6 +2,7 @@ import 'package:flutter/widgets.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import '../l10n/app_localizations.dart';
import '../l10n/locale_tag.dart';
import '../utils/platform_info.dart';
class BackgroundService {
@@ -33,6 +34,11 @@ class BackgroundService {
eventAction: ForegroundTaskEventAction.repeat(5000),
autoRunOnBoot: false,
allowWifiLock: false,
// The radio link lives in the app process; once the user swipes the
// app away it is gone, so a lingering "connected" notification (or
// an automatic restart) would only be misleading.
allowAutoRestart: false,
stopWithTask: true,
),
);
_initialized = true;
@@ -49,6 +55,9 @@ class BackgroundService {
await FlutterForegroundTask.startService(
notificationTitle: l10n.background_serviceTitle,
notificationText: l10n.background_serviceText,
notificationIcon: const NotificationIcon(
metaDataName: 'org.meshcore.open.NOTIFICATION_ICON',
),
callback: startCallback,
);
}
@@ -57,7 +66,7 @@ class BackgroundService {
final supported = AppLocalizations.supportedLocales;
final override = _languageOverrideProvider?.call();
if (override != null && override.isNotEmpty) {
final overrideLocale = Locale(override);
final overrideLocale = localeFromTag(override);
final isSupported = supported.any(
(l) => l.languageCode == overrideLocale.languageCode,
);
File diff suppressed because it is too large. Load diff
+12 -4
View File
@@ -385,7 +385,7 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
///
/// Call once at startup, next to
/// `await translationService.refreshDownloadedModels();` in `main.dart`.
Future<void> refreshDownloadedModels() async {
Future<void> refreshDownloadedModels({bool clearMissing = false}) async {
if (_isDownloading) return;
await _settingsStore.load();
if (kIsWeb) {
@@ -393,7 +393,7 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
return;
}
final scanned = await _fileStore.scanDownloadedModels();
if (scanned.isEmpty) {
if (scanned.isEmpty && !clearMissing) {
_notify();
return;
}
@@ -405,6 +405,9 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
final existingByPath = {
for (final model in preferences.downloadedModels) model.localPath: model,
};
final existingByName = {
for (final model in preferences.downloadedModels) model.name: model,
};
final merged = <ImageCodecModelRecord>[];
// Every filename the registry knows about, so a half-installed bundle's
// leftovers are never mistaken for standalone models.
@@ -457,9 +460,14 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
// as its own single-file record so a hand-fetched graph is not deleted.
for (final model in scanned) {
if (claimed.contains(model.name)) continue;
final existing = existingByPath[model.localPath];
final existing =
existingByPath[model.localPath] ?? existingByName[model.name];
merged.add(
existing?.copyWith(fileSizeBytes: model.fileSizeBytes) ?? model,
existing?.copyWith(
localPath: model.localPath,
fileSizeBytes: model.fileSizeBytes,
) ??
model,
);
}
@@ -0,0 +1,2 @@
export 'map_tile_cache_repository_stub.dart'
if (dart.library.io) 'map_tile_cache_repository_io.dart';
@@ -0,0 +1,312 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
CacheInfoRepository createMapTileCacheRepository(String cacheKey) {
if (!Platform.isLinux && !Platform.isWindows) {
return CacheObjectProvider(databaseName: cacheKey);
}
sqfliteFfiInit();
return SqliteMapTileCacheRepository(databaseName: cacheKey);
}
/// Tile metadata stays in SQLite; only queried rows become Dart objects.
class SqliteMapTileCacheRepository implements CacheInfoRepository {
SqliteMapTileCacheRepository({
required this.databaseName,
Future<Directory> Function()? directory,
DatabaseFactory? factory,
}) : _directory = directory ?? getApplicationSupportDirectory,
_factory = factory ?? databaseFactoryFfi;
static const int schemaVersion = 1;
static const int legacyImportVersion = 1;
static const String _table = 'cacheObject';
static const String _migrationTable = 'cacheMigration';
static const String _legacyMigration = 'legacyJson';
static const String _unreadableSuffix = '.unreadable';
final String databaseName;
final Future<Directory> Function() _directory;
final DatabaseFactory _factory;
Future<Directory>? _resolvedDirectory;
Future<Database>? _opening;
int _connections = 0;
Future<Directory> _baseDirectory() => _resolvedDirectory ??= _directory();
Future<String> _databasePath() async =>
'${(await _baseDirectory()).path}${Platform.pathSeparator}$databaseName.db';
Future<File> _legacyFile() async => File(
'${(await _baseDirectory()).path}${Platform.pathSeparator}$databaseName.json',
);
Future<Database> _database() async {
final pending = _opening;
if (pending != null) return pending;
final started = _openDatabase();
_opening = started;
try {
return await started;
} catch (_) {
if (identical(_opening, started)) _opening = null;
rethrow;
}
}
Future<Database> _openDatabase() async {
final path = await _databasePath();
await File(path).parent.create(recursive: true);
final db = await _factory.openDatabase(
path,
options: OpenDatabaseOptions(
version: schemaVersion,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE $_table (
_id INTEGER PRIMARY KEY,
url TEXT NOT NULL,
key TEXT NOT NULL UNIQUE,
relativePath TEXT NOT NULL,
eTag TEXT,
validTill INTEGER NOT NULL,
touched INTEGER NOT NULL,
length INTEGER
)
''');
await db.execute('CREATE INDEX cacheTouched ON $_table (touched)');
await db.execute('''
CREATE TABLE $_migrationTable (
name TEXT PRIMARY KEY,
version INTEGER NOT NULL
)
''');
},
),
);
try {
await _importLegacyJson(db);
return db;
} catch (_) {
await db.close();
rethrow;
}
}
Future<void> _importLegacyJson(Database db) async {
final versions = await db.query(
_migrationTable,
where: 'name = ?',
whereArgs: [_legacyMigration],
);
final version = versions.isEmpty ? 0 : versions.single['version'] as int;
if (version > legacyImportVersion) return;
final legacy = await _legacyFile();
var unreadable = false;
if (version < legacyImportVersion) {
final List<Map<String, Object?>> records;
(records, unreadable) = await compute(_readLegacyRecords, legacy.path);
await db.transaction((transaction) async {
final batch = transaction.batch();
for (final record in records) {
batch.insert(
_table,
record,
conflictAlgorithm: ConflictAlgorithm.ignore,
);
}
batch.insert(_migrationTable, {
'name': _legacyMigration,
'version': legacyImportVersion,
}, conflictAlgorithm: ConflictAlgorithm.replace);
await batch.commit(noResult: true);
});
}
// A committed version marker makes a crash before cleanup safe to retry.
try {
if (unreadable && await legacy.exists()) {
// Kept for inspection rather than deleted; it is never imported again.
debugPrint('Map metadata migration skipped unreadable records');
await legacy.rename('${legacy.path}$_unreadableSuffix');
}
for (final file in [legacy, File('${legacy.path}.tmp')]) {
if (await file.exists()) await file.delete();
}
} on FileSystemException catch (error) {
debugPrint('Map metadata migration cleanup: $error');
}
}
@override
Future<bool> open() async {
_connections++;
try {
await _database();
return true;
} catch (_) {
_connections--;
rethrow;
}
}
@override
Future<bool> close() async {
if (_connections == 0 || --_connections > 0) return false;
final pending = _opening;
_opening = null;
if (pending != null) await (await pending).close();
return true;
}
@override
Future<bool> exists() async => File(await _databasePath()).exists();
@override
Future<void> deleteDataFile() async {
if (_connections != 0) {
throw StateError('Close map metadata connections before deleting it.');
}
await _factory.deleteDatabase(await _databasePath());
final legacy = await _legacyFile();
for (final file in [
legacy,
File('${legacy.path}.tmp'),
File('${legacy.path}$_unreadableSuffix'),
]) {
if (await file.exists()) await file.delete();
}
}
@override
Future<CacheObject?> get(String key) async {
final rows = await (await _database()).query(
_table,
where: 'key = ?',
whereArgs: [key],
limit: 1,
);
return rows.isEmpty ? null : CacheObject.fromMap(rows.single);
}
@override
Future<CacheObject> insert(
CacheObject cacheObject, {
bool setTouchedToNow = true,
}) async {
if (cacheObject.id != null) {
throw ArgumentError('Inserted cache objects must not have an ID.');
}
final map = cacheObject.toMap(setTouchedToNow: setTouchedToNow);
final id = await (await _database()).insert(_table, map);
return CacheObject.fromMap({...map, CacheObject.columnId: id});
}
@override
Future<int> update(
CacheObject cacheObject, {
bool setTouchedToNow = true,
}) async {
if (cacheObject.id == null) {
throw ArgumentError('Updated cache objects must have an ID.');
}
return (await _database()).update(
_table,
cacheObject.toMap(setTouchedToNow: setTouchedToNow),
where: '_id = ?',
whereArgs: [cacheObject.id],
);
}
@override
Future<dynamic> updateOrInsert(CacheObject cacheObject) =>
cacheObject.id == null ? insert(cacheObject) : update(cacheObject);
@override
Future<int> delete(int id) async =>
(await _database()).delete(_table, where: '_id = ?', whereArgs: [id]);
@override
Future<int> deleteAll(Iterable<int> ids) async {
final unique = ids.toSet().toList();
if (unique.isEmpty) return 0;
final db = await _database();
return db.transaction((transaction) async {
var deleted = 0;
for (var start = 0; start < unique.length; start += 500) {
final chunk = unique.skip(start).take(500).toList();
deleted += await transaction.delete(
_table,
where: '_id IN (${List.filled(chunk.length, '?').join(',')})',
whereArgs: chunk,
);
}
return deleted;
});
}
@override
Future<List<CacheObject>> getAllObjects() async =>
CacheObject.fromMapList(await (await _database()).query(_table));
@override
Future<List<CacheObject>> getObjectsOverCapacity(int capacity) async =>
CacheObject.fromMapList(
await (await _database()).query(
_table,
where: 'touched < ?',
whereArgs: [
DateTime.now()
.subtract(const Duration(days: 1))
.millisecondsSinceEpoch,
],
orderBy: 'touched DESC, _id DESC',
offset: capacity,
limit: 100,
),
);
@override
Future<List<CacheObject>> getOldObjects(Duration maxAge) async =>
CacheObject.fromMapList(
await (await _database()).query(
_table,
where: 'touched < ?',
whereArgs: [DateTime.now().subtract(maxAge).millisecondsSinceEpoch],
orderBy: 'touched ASC, _id ASC',
limit: 100,
),
);
}
/// Returns the importable records and whether any part of the file was
/// unreadable. A broken file must not keep the tile cache from opening.
(List<Map<String, Object?>>, bool) _readLegacyRecords(String path) {
final file = File(path);
if (!file.existsSync()) return ([], false);
final Object? decoded;
try {
decoded = jsonDecode(file.readAsStringSync());
} on Exception {
return ([], true);
}
if (decoded is! List) return ([], true);
final records = <Map<String, Object?>>[];
var unreadable = false;
for (final value in decoded) {
try {
records.add(
CacheObject.fromMap(
(value as Map).cast<String, dynamic>(),
).toMap(setTouchedToNow: false)..remove(CacheObject.columnId),
);
} catch (_) {
unreadable = true;
}
}
return (records, unreadable);
}
@@ -0,0 +1,4 @@
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
CacheInfoRepository createMapTileCacheRepository(String cacheKey) =>
NonStoringObjectProvider();
+16 -10
View File
@@ -8,6 +8,7 @@ import 'package:flutter_map/flutter_map.dart';
import '../models/app_settings.dart';
import '../theme/mesh_theme.dart';
import 'app_settings_service.dart';
import 'map_tile_cache_repository.dart';
enum MapRasterSourcePreset {
osmAuto('osm_auto'),
@@ -347,6 +348,7 @@ class MapTileCacheService extends ChangeNotifier {
cacheKey,
stalePeriod: const Duration(days: 365),
maxNrOfCacheObjects: 200000,
repo: createMapTileCacheRepository(cacheKey),
),
) {
tileProvider = CachedNetworkTileProvider(cacheManager: this.cacheManager);
@@ -534,19 +536,23 @@ class MapTileCacheService extends ChangeNotifier {
Future<CachedTileInventory> getCachedTileInventory() async {
final repo = _concreteCacheManager.config.repo;
await repo.open();
final objects = await repo.getAllObjects();
final tiles = <CachedTileInfo>[];
int totalBytes = 0;
try {
final objects = await repo.getAllObjects();
final tiles = <CachedTileInfo>[];
int totalBytes = 0;
for (final object in objects) {
totalBytes += object.length ?? 0;
final tile = _parseCachedTile(object);
if (tile != null) {
tiles.add(tile);
for (final object in objects) {
totalBytes += object.length ?? 0;
final tile = _parseCachedTile(object);
if (tile != null) {
tiles.add(tile);
}
}
}
return CachedTileInventory(tiles: tiles, totalBytes: totalBytes);
return CachedTileInventory(tiles: tiles, totalBytes: totalBytes);
} finally {
await repo.close();
}
}
List<CachedTileInfo> filterTilesForActiveSource(
@@ -12,7 +12,17 @@ class _SeenMessage {
/// When this device saw it (local clock). Only used to forget entries.
final DateTime receivedAt;
const _SeenMessage(this.sender, this.key, this.sentAt, this.receivedAt);
/// How many sends of this text by this sender, each within the
/// same-sender window of the previous one, end with this one (1 = first).
final int sends;
const _SeenMessage(
this.sender,
this.key,
this.sentAt,
this.receivedAt, {
this.sends = 1,
});
}
/// In-memory, per-channel tracker of recently seen channel texts used to catch
@@ -28,10 +38,19 @@ class _SeenMessage {
/// so a sender whose clock is far off cannot push everyone else's entries
/// out early or keep its own around forever.
///
/// The same-sender rule only applies to texts of at least
/// [sameSenderMinWords] words and [sameSenderMinLength] characters: people
/// naturally repeat short replies ("ok", "yes", "test" when checking reach),
/// while spam that gets re-posted is a whole sentence.
/// A copy with the same sender, text and send second as an entry already
/// recorded is the same message seen again (another companion syncing it,
/// a mesh repeat that slipped past storage dedup), never a repeat, and is
/// not recorded twice.
///
/// The same-sender rule flags the [sameSenderSends]th send of a text in a
/// row, each send within [sameSenderWindow] of the previous one (2 = the
/// first re-send). Higher values tolerate people re-sending when they see
/// no repeat or reply.
///
/// The same-sender rule applies to texts of any length, so one word sent
/// over and over ("hello", "test") is caught at the same count as a
/// sentence.
///
/// The cross-sender rule only applies to sentence-length texts (at least
/// [crossSenderMinWords] words): short greetings like "Happy New Year!" or
@@ -40,8 +59,7 @@ class _SeenMessage {
class DuplicateTracker {
DuplicateTracker({
this.sameSenderWindow = const Duration(minutes: 10),
this.sameSenderMinLength = 10,
this.sameSenderMinWords = 3,
this.sameSenderSends = 2,
this.crossSenderWindow = const Duration(minutes: 30),
this.crossSenderMinSenders = 3,
this.crossSenderMinLength = 10,
@@ -51,9 +69,9 @@ class DuplicateTracker {
final Duration sameSenderWindow;
/// Minimum length / word count for the same-sender rule (see class docs).
final int sameSenderMinLength;
final int sameSenderMinWords;
/// Which send in a row of the same text is flagged; can be overridden per
/// call so a settings change applies immediately.
final int sameSenderSends;
final Duration crossSenderWindow;
final int crossSenderMinSenders;
final int crossSenderMinLength;
@@ -95,7 +113,11 @@ class DuplicateTracker {
required String text,
required DateTime at,
DateTime? receivedAt,
int? sameSenderSends,
}) {
final flagAt = (sameSenderSends ?? this.sameSenderSends) < 2
? 2
: (sameSenderSends ?? this.sameSenderSends);
final arrived = receivedAt ?? at;
final key = MessageFilterText.normalizeForDuplicates(text);
if (key.isEmpty) return null;
@@ -103,23 +125,38 @@ class DuplicateTracker {
final entries = _seen.putIfAbsent(channelId, ListQueue<_SeenMessage>.new);
_prune(entries, arrived);
final atSecond = _second(at);
for (final entry in entries) {
if (entry.key == key &&
entry.sender == senderKey &&
_second(entry.sentAt) == atSecond) {
// The same message seen again, not a new send.
return null;
}
}
// The longest run of sends this one continues: earlier sends of this
// text by this sender within the window, each already carrying its run.
var sends = 1;
for (final entry in entries) {
if (entry.key != key || entry.sender != senderKey) continue;
if (entry.sentAt.difference(at).abs() <= sameSenderWindow &&
entry.sends + 1 > sends) {
sends = entry.sends + 1;
}
}
FilterReason? result;
if (!isAllowed(channelId, text)) {
final senders = <String>{senderKey};
var sameSender = false;
for (final entry in entries) {
if (entry.key != key) continue;
if (entry.key != key || entry.sender == senderKey) continue;
// Absolute gap between send times: delivery order does not matter.
final gap = entry.sentAt.difference(at).abs();
if (entry.sender == senderKey) {
if (gap <= sameSenderWindow) sameSender = true;
} else if (gap <= crossSenderWindow) {
if (entry.sentAt.difference(at).abs() <= crossSenderWindow) {
senders.add(entry.sender);
}
}
if (sameSender &&
key.length >= sameSenderMinLength &&
_wordCount(key) >= sameSenderMinWords) {
if (sends >= flagAt) {
result = FilterReason.duplicate;
} else if (key.length >= crossSenderMinLength &&
_wordCount(key) >= crossSenderMinWords &&
@@ -128,11 +165,13 @@ class DuplicateTracker {
}
}
entries.addLast(_SeenMessage(senderKey, key, at, arrived));
entries.addLast(_SeenMessage(senderKey, key, at, arrived, sends: sends));
if (entries.length > maxEntriesPerChannel) entries.removeFirst();
return result;
}
static int _second(DateTime time) => time.millisecondsSinceEpoch ~/ 1000;
/// [key] is already whitespace-collapsed by `normalizeForDuplicates`.
static int _wordCount(String key) => key.isEmpty ? 0 : key.split(' ').length;
@@ -107,6 +107,14 @@ class MessageFilterService extends ChangeNotifier {
@visibleForTesting
int get recentCleanCount => _recentClean.length;
@visibleForTesting
bool hasRecentCleanExample(String text) {
final key = MessageFilterText.normalize(text);
return _recentClean.any(
(example) => MessageFilterText.normalize(example.text) == key,
);
}
/// Loads persisted state and trains the classifier.
Future<void> load() async {
try {
@@ -139,6 +147,10 @@ class MessageFilterService extends ChangeNotifier {
/// [sentAt] is the message's own timestamp. Duplicate windows are measured
/// between send times, so history synced in a burst after reconnecting is
/// not mistaken for a flood; without it the local clock is used.
///
/// Messages addressed to someone ([isReply], or an `@[name]` mention in
/// [text]) are exempt from duplicate detection and not recorded for it:
/// asking several people the same thing is conversation, not a repeat.
FilterVerdict? evaluate({
required String channelId,
required String sender,
@@ -146,6 +158,7 @@ class MessageFilterService extends ChangeNotifier {
DateTime? sentAt,
bool isOutgoing = false,
bool isReaction = false,
bool isReply = false,
}) {
if (!isChannelFiltered(channelId)) return null;
if (isOutgoing || isReaction) return null;
@@ -153,13 +166,17 @@ class MessageFilterService extends ChangeNotifier {
if (MessageFilterText.isStructuredPayload(text)) return null;
// Always record (even when a rule matches) so floods keep being caught.
final duplicateReason = _tracker.check(
channelId: channelId,
sender: sender,
text: text,
at: sentAt ?? _clock(),
receivedAt: _clock(),
);
final mentionsSomeone = isReply || MessageFilterText.hasMention(text);
final duplicateReason = mentionsSomeone
? null
: _tracker.check(
channelId: channelId,
sender: sender,
text: text,
at: sentAt ?? _clock(),
receivedAt: _clock(),
sameSenderSends: _settings.repeatSends,
);
final byRule = _matchRules(sender, text);
if (byRule != null) return byRule;
@@ -272,12 +289,28 @@ class MessageFilterService extends ChangeNotifier {
}
/// User tapped "Spam": store the example and retrain.
Future<void> markSpam({required String sender, required String text}) async {
final key = MessageFilterText.normalize(text);
if (key.isEmpty) return;
_recentClean.removeWhere((e) => MessageFilterText.normalize(e.text) == key);
_hamExamples.removeWhere((e) => MessageFilterText.normalize(e.text) == key);
_addExample(_spamExamples, _example(sender, text), maxSpamExamples);
Future<void> markSpam({required String sender, required String text}) =>
markSpamMany([(sender: sender, text: text)]);
/// Marks several messages as spam with one save and one retrain (bulk
/// selection in a chat).
Future<void> markSpamMany(
List<({String sender, String text})> messages,
) async {
var changed = false;
for (final m in messages) {
final key = MessageFilterText.normalize(m.text);
if (key.isEmpty) continue;
_recentClean.removeWhere(
(e) => MessageFilterText.normalize(e.text) == key,
);
_hamExamples.removeWhere(
(e) => MessageFilterText.normalize(e.text) == key,
);
_addExample(_spamExamples, _example(m.sender, m.text), maxSpamExamples);
changed = true;
}
if (!changed) return;
final training = _retrain();
_notify();
await _guardSave(() async {
@@ -294,17 +327,27 @@ class MessageFilterService extends ChangeNotifier {
required String channelId,
required String sender,
required String text,
}) async {
_tracker.allow(channelId, text);
final key = MessageFilterText.normalize(text);
if (key.isEmpty) {
}) => markNotSpamMany([(channelId: channelId, sender: sender, text: text)]);
/// Marks several messages as not spam with one save and one retrain.
Future<void> markNotSpamMany(
List<({String channelId, String sender, String text})> messages,
) async {
var changed = false;
for (final m in messages) {
_tracker.allow(m.channelId, m.text);
final key = MessageFilterText.normalize(m.text);
if (key.isEmpty) continue;
_spamExamples.removeWhere(
(e) => MessageFilterText.normalize(e.text) == key,
);
_addExample(_hamExamples, _example(m.sender, m.text), maxNotSpamExamples);
changed = true;
}
if (!changed) {
_notify();
return;
}
_spamExamples.removeWhere(
(e) => MessageFilterText.normalize(e.text) == key,
);
_addExample(_hamExamples, _example(sender, text), maxNotSpamExamples);
final training = _retrain();
_notify();
await _guardSave(() async {
@@ -141,6 +141,9 @@ class MessageFilterText {
return _fold(text).replaceAll(_whitespace, ' ').trim();
}
/// True when [text] contains an `@[name]` mention.
static bool hasMention(String text) => _mention.hasMatch(text);
/// Looser form used to detect repeated messages: also drops `@[name]`
/// mentions, punctuation and emoji so trivial variations still match.
static String normalizeForDuplicates(String text) {
+44 -14
View File
@@ -95,6 +95,14 @@ class MessageRetryService extends ChangeNotifier {
final Map<String, Message> _pendingMessages = {};
final Map<String, Contact> _pendingContacts = {};
final Map<String, List<PathSelection>> _attemptPathHistory = {};
/// Route failures of each pending message, held back until its fate is
/// known: if any attempt is acknowledged the contact was reachable and the
/// routes that timed out really failed; if nothing ever gets through the
/// contact was probably just offline, and blaming its routes would wreck a
/// good history.
final Map<String, List<({int attempt, PathSelection selection})>>
_deferredRouteFailures = {};
final Map<String, List<AckHashMapping>> _ackHashToMessageId = {};
final Map<String, List<int>> _expectedAckHashes = {};
final List<_AckHistoryEntry> _ackHistory = [];
@@ -618,6 +626,7 @@ class MessageRetryService extends ChangeNotifier {
_pendingMessages.remove(messageId);
_pendingContacts.remove(messageId);
_attemptPathHistory.remove(messageId);
_deferredRouteFailures.remove(messageId);
_timeoutTimers.remove(messageId);
_resolvedMessages.remove(messageId);
// Cancellation (and other cleanup paths) must release the active in-flight
@@ -653,13 +662,10 @@ class MessageRetryService extends ChangeNotifier {
final backoffMs = 1000 * (1 << message.retryCount);
if (selection != null) {
_recordPathResultFromMessage(
contact.publicKeyHex,
message,
selection,
false,
null,
);
_deferredRouteFailures.putIfAbsent(messageId, () => []).add((
attempt: message.retryCount,
selection: selection,
));
}
final updatedMessage = message.copyWith(
@@ -690,13 +696,19 @@ class MessageRetryService extends ChangeNotifier {
config!.clearContactPath!(contact);
}
_recordPathResultFromMessage(
contact.publicKeyHex,
message,
selection,
false,
null,
);
// Nothing got through on any route: treat the contact as unreachable
// and leave its routes' records alone. Only flood stats count the miss.
// The held failures stay until the grace-period cleanup below, so a
// late ACK still blames the routes that really failed.
if (selection != null && selection.useFlood) {
_recordPathResultFromMessage(
contact.publicKeyHex,
message,
selection,
false,
null,
);
}
config?.updateMessage(failedMessage);
@@ -828,12 +840,29 @@ class MessageRetryService extends ChangeNotifier {
);
final wasAlreadyResolved = _resolvedMessages.contains(matchedMessageId);
final deferredFailures =
_deferredRouteFailures.remove(matchedMessageId) ?? const [];
_cleanupMessage(matchedMessageId);
config?.updateMessage(deliveredMessage);
if (contact != null) {
// The contact was reachable, so earlier attempts that timed out
// really failed — except the attempt this (possibly late) ACK is for.
// Without knowing which attempt was acknowledged, blame nothing.
if (!ambiguousPath && matchedAttemptIndex != null) {
for (final failure in deferredFailures) {
if (failure.attempt == ackedAttempt) continue;
_recordPathResultFromMessage(
contact.publicKeyHex,
message,
failure.selection,
false,
null,
);
}
}
if (!ambiguousPath) {
_recordPathResultFromMessage(
contact.publicKeyHex,
@@ -948,6 +977,7 @@ class MessageRetryService extends ChangeNotifier {
_pendingMessages.clear();
_pendingContacts.clear();
_attemptPathHistory.clear();
_deferredRouteFailures.clear();
_expectedAckHashes.clear();
_ackHistory.clear();
_ackHashToMessageId.clear();
+79
View File
@@ -0,0 +1,79 @@
import 'package:flutter/material.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../screens/channel_chat_screen.dart';
import '../screens/chat_screen.dart';
import 'notification_service.dart';
/// Opens the conversation behind a tapped message notification instead of
/// leaving the user on whatever screen they last had open.
///
/// Only acts while a radio is connected: chats need its contacts/channels, and
/// a cold start goes through the scanner anyway, so a stale tap is dropped.
class NotificationNavigator {
final GlobalKey<NavigatorState> navigatorKey;
final MeshCoreConnector connector;
final NotificationService notifications;
NotificationNavigator({
required this.navigatorKey,
required this.connector,
required this.notifications,
});
void attach() {
notifications.pendingTap.addListener(_handleTap);
_handleTap();
}
void dispose() {
notifications.pendingTap.removeListener(_handleTap);
}
void _handleTap() {
final payload = notifications.pendingTap.value;
if (payload == null) return;
notifications.pendingTap.value = null;
final navigator = navigatorKey.currentState;
// Offline the last radio's saved chats still open (read-only).
if (navigator == null || !connector.hasRadioData) return;
final sep = payload.indexOf(':');
if (sep <= 0) return;
final kind = payload.substring(0, sep);
final value = payload.substring(sep + 1);
if (kind == 'message') {
if (connector.activeContactKey == value) return;
final contact = connector.getContactByPubKeyHex(value);
if (contact == null ||
(contact.type != advTypeChat && contact.type != advTypeRoom)) {
return;
}
final unread = connector.getUnreadCountForContactKey(value);
connector.markContactRead(value);
navigator.push(
MaterialPageRoute(
builder: (_) =>
ChatScreen(contact: contact, initialUnreadCount: unread),
),
);
} else if (kind == 'channel') {
final index = int.tryParse(value);
if (index == null || connector.activeChannelIndex == index) return;
final channel = connector.channels
.where((c) => c.index == index)
.firstOrNull;
if (channel == null) return;
final unread = connector.getUnreadCountForChannelIndex(index);
connector.markChannelRead(index);
navigator.push(
MaterialPageRoute(
builder: (_) =>
ChannelChatScreen(channel: channel, initialUnreadCount: unread),
),
);
}
}
}
+6 -3
View File
@@ -6,6 +6,7 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../l10n/app_localizations.dart';
import '../l10n/locale_tag.dart';
/// Name under which the main isolate registers the port that receives
/// notification actions from the plugin's background isolate.
@@ -153,7 +154,9 @@ Future<void> notificationActionBackgroundHandler(
final plugin = FlutterLocalNotificationsPlugin();
await plugin.initialize(
settings: const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
android: AndroidInitializationSettings(
'@drawable/ic_stat_notification',
),
),
);
final l10n = await _backgroundLocalizations();
@@ -168,7 +171,7 @@ Future<void> notificationActionBackgroundHandler(
channelDescription: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
),
),
);
@@ -186,7 +189,7 @@ Future<AppLocalizations> _backgroundLocalizations() async {
);
} catch (_) {}
for (final locale in [
if (code != null) Locale(code),
if (code != null) localeFromTag(code),
PlatformDispatcher.instance.locale,
]) {
try {
+174 -16
View File
@@ -9,10 +9,12 @@ import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import '../helpers/gif_helper.dart';
import '../helpers/contact_share_message.dart';
import '../helpers/marker_message.dart';
import '../helpers/message_url_image_helper.dart';
import '../helpers/reaction_helper.dart';
import '../l10n/app_localizations.dart';
import '../l10n/locale_tag.dart';
import '../models/app_settings.dart';
import '../storage/prefs_manager.dart';
import '../utils/platform_info.dart';
@@ -43,7 +45,7 @@ class NotificationService {
try {
PrefsManager.instance.setString(
notificationLanguagePrefsKey,
locale.languageCode,
localeTag(locale),
);
} catch (_) {}
}
@@ -91,6 +93,42 @@ class NotificationService {
static const _minNotificationInterval = Duration(seconds: 3);
static const _batchWindow = Duration(seconds: 5);
/// Messages for the same conversation that arrive within this window are
/// posted as one notification update. A queue sync can deliver hundreds of
/// messages in seconds; posting each one floods the shade and makes the
/// phone sluggish (Android also drops updates past its rate limit).
static const _coalesceDelay = Duration(milliseconds: 800);
/// While the radio's offline queue is syncing, sound/vibrate at most this
/// often instead of every [_minNotificationInterval].
static const _bulkSyncAlertInterval = Duration(seconds: 60);
/// Reports whether the connector is draining the radio's message queue.
bool Function()? isBulkSyncActive;
/// Current unread total for the app badge. Coalesced conversation updates
/// flush on independent timers, so a count captured when a message was
/// queued can be older than one already posted by another conversation.
int Function()? unreadTotalProvider;
/// Newest badge count seen on any queued message, when no provider is set.
int? _latestQueuedBadgeCount;
final Map<String, List<_PendingNotification>> _pendingConversationUpdates =
{};
final Map<String, Timer> _conversationUpdateTimers = {};
/// Bumped whenever a conversation notification is cleared, so a post still
/// awaiting permission/image lookup does not bring a read chat back.
final Map<int, int> _clearGenerations = {};
int _cancelAllGeneration = 0;
(int, int) _clearGenerationOf(int id) =>
(_cancelAllGeneration, _clearGenerations[id] ?? 0);
void _bumpClearGeneration(int id) =>
_clearGenerations[id] = (_clearGenerations[id] ?? 0) + 1;
DateTime? _lastNotificationTime;
final List<_PendingNotification> _pendingNotifications = [];
bool _isBatchingActive = false;
@@ -101,6 +139,7 @@ class NotificationService {
_suppressNotifications = suppress;
if (suppress) {
_pendingNotifications.clear();
_dropAllPendingConversationUpdates();
}
}
@@ -108,7 +147,7 @@ class NotificationService {
if (_isInitialized) return;
const androidSettings = AndroidInitializationSettings(
'@mipmap/ic_launcher',
'@drawable/ic_stat_notification',
);
const iosSettings = DarwinInitializationSettings(
requestAlertPermission: true,
@@ -302,6 +341,12 @@ class NotificationService {
if (GifHelper.parseGif(trimmed) != null) {
return l10n.notification_sentGif;
}
final contactShare = parseContactShare(trimmed);
if (contactShare != null) {
return l10n.contactShare_notification(
contactShare.name.isEmpty ? contactShare.shortKey : contactShare.name,
);
}
final marker = parseMarkerText(trimmed);
if (marker != null) {
return marker.label.isEmpty
@@ -388,7 +433,7 @@ class NotificationService {
: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
number: badgeCount,
silent: silent,
category: AndroidNotificationCategory.message,
@@ -420,13 +465,22 @@ class NotificationService {
String? senderName,
int? badgeCount,
bool silent = false,
List<_PendingNotification> earlier = const [],
}) async {
final generation = _clearGenerationOf(id);
if (!await _ensureCanNotify()) return;
// Only the newest messages fit in the notification anyway.
final skipped = earlier.length > _maxConversationMessages
? earlier.length - _maxConversationMessages
: 0;
final history = earlier.skip(skipped);
final imagePath = await _resolveNotificationImagePath(
message,
urlImagesEnabled: urlImagesEnabled,
);
if (_clearGenerationOf(id) != generation) return;
final preview = formatNotificationText(message.trim(), _l10n);
final body = preview.isEmpty
? _l10n.notification_receivedNewMessage
@@ -444,6 +498,23 @@ class NotificationService {
..title = title
..badgeCount = badgeCount
..imagePath = imagePath;
for (final prior in history) {
final priorPreview = formatNotificationText(prior.body.trim(), _l10n);
final priorSender = isChannel ? (prior.senderName ?? title) : title;
conversation.add(
Message(
priorPreview.isEmpty
? _l10n.notification_receivedNewMessage
: priorPreview,
DateTime.now(),
Person(
key: isChannel ? 'sender:$priorSender' : payload,
name: priorSender,
),
),
_maxConversationMessages,
);
}
final sender = isChannel ? (senderName ?? title) : title;
conversation.add(
Message(
@@ -549,7 +620,7 @@ class NotificationService {
channelDescription: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
),
),
payload: conversation?.payload,
@@ -592,7 +663,7 @@ class NotificationService {
channelDescription: 'New node advertisement notifications',
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
);
const iosDetails = DarwinNotificationDetails(
@@ -648,7 +719,7 @@ class NotificationService {
channelDescription: 'Low battery alerts for the connected device',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
);
const darwinDetails = DarwinNotificationDetails(
@@ -691,16 +762,48 @@ class NotificationService {
}
}
/// Payload (`message:<key>` or `channel:<index>`) of the last tapped
/// conversation notification, until [NotificationNavigator] consumes it.
final ValueNotifier<String?> pendingTap = ValueNotifier<String?>(null);
void _onNotificationTapped(NotificationResponse response) {
final payload = response.payload;
if (payload != null) {
debugPrint('Notification tapped: $payload');
// Handle navigation based on payload
// This can be extended to navigate to specific screens
// Action buttons (reply, mark read, mute) are handled elsewhere; only a
// tap on the notification body should open the conversation. Use the
// response type, not actionId: the Windows plugin fills actionId with the
// payload even for plain body clicks.
if (payload == null ||
response.notificationResponseType !=
NotificationResponseType.selectedNotification) {
return;
}
debugPrint('Notification tapped: $payload');
if (payload.startsWith('message:') || payload.startsWith('channel:')) {
pendingTap.value = payload;
}
}
static const String _radioKeyPrefsKey = 'notifications_radio_key';
/// Called when a radio connects. Notifications name conversations by
/// contact key and channel *slot*; after switching radios a leftover
/// channel notification would open (and mark read) whatever channel the
/// new radio keeps in that slot, so a different radio clears them all.
/// The key is persisted so this also holds across app restarts.
Future<void> bindRadio(String radioKeyHex) async {
String? previous;
try {
previous = PrefsManager.instance.getString(_radioKeyPrefsKey);
await PrefsManager.instance.setString(_radioKeyPrefsKey, radioKeyHex);
} catch (_) {}
if (previous == null || previous == radioKeyHex) return;
if (!await _ensureInitialized()) return;
await cancelAll();
}
Future<void> cancelAll() async {
_cancelAllGeneration++;
_dropAllPendingConversationUpdates();
_conversations.clear();
await _notifications.cancelAll();
await _updateBadge(0);
@@ -715,6 +818,8 @@ class NotificationService {
String contactId,
int totalUnreadCount,
) async {
_dropPendingConversationUpdate(_NotificationType.message, contactId);
_bumpClearGeneration(contactId.hashCode);
if (!await _ensureInitialized()) return;
_conversations.remove(contactId.hashCode);
await _notifications.cancel(id: contactId.hashCode);
@@ -726,6 +831,11 @@ class NotificationService {
int channelIndex,
int totalUnreadCount,
) async {
_dropPendingConversationUpdate(
_NotificationType.channelMessage,
channelIndex.toString(),
);
_bumpClearGeneration(channelIndex.hashCode);
if (!await _ensureInitialized()) return;
_conversations.remove(channelIndex.hashCode);
await _notifications.cancel(id: channelIndex.hashCode);
@@ -853,10 +963,16 @@ class NotificationService {
now.difference(_lastNotificationTime!) < _minNotificationInterval;
// Messages always update their conversation notification so the reply
// action stays available; during a burst they update silently.
// action stays available; bursts are coalesced and update silently.
if (notification.type != _NotificationType.advert) {
_showNotificationImmediately(notification, silent: throttled);
if (!throttled) _lastNotificationTime = now;
_latestQueuedBadgeCount =
notification.badgeCount ?? _latestQueuedBadgeCount;
final key = _conversationKey(notification.type, notification.id);
(_pendingConversationUpdates[key] ??= []).add(notification);
_conversationUpdateTimers[key] ??= Timer(
_coalesceDelay,
() => unawaited(_flushConversationUpdate(key)),
);
return;
}
@@ -883,6 +999,43 @@ class NotificationService {
_lastNotificationTime = now;
}
static String _conversationKey(_NotificationType type, String? id) =>
'${type.name}:$id';
void _dropPendingConversationUpdate(_NotificationType type, String id) {
final key = _conversationKey(type, id);
_conversationUpdateTimers.remove(key)?.cancel();
_pendingConversationUpdates.remove(key);
}
void _dropAllPendingConversationUpdates() {
for (final timer in _conversationUpdateTimers.values) {
timer.cancel();
}
_conversationUpdateTimers.clear();
_pendingConversationUpdates.clear();
}
Future<void> _flushConversationUpdate(String key) async {
_conversationUpdateTimers.remove(key);
final batch = _pendingConversationUpdates.remove(key);
if (batch == null || batch.isEmpty) return;
final now = DateTime.now();
final alertGap = (isBulkSyncActive?.call() ?? false)
? _bulkSyncAlertInterval
: _minNotificationInterval;
final silent =
_lastNotificationTime != null &&
now.difference(_lastNotificationTime!) < alertGap;
if (!silent) _lastNotificationTime = now;
await _showNotificationImmediately(
batch.last,
silent: silent,
earlier: batch.sublist(0, batch.length - 1),
badgeCount: unreadTotalProvider?.call() ?? _latestQueuedBadgeCount,
);
}
Future<void> _processBatch() async {
_isBatchingActive = false;
@@ -905,7 +1058,10 @@ class NotificationService {
Future<void> _showNotificationImmediately(
_PendingNotification notification, {
bool silent = false,
List<_PendingNotification> earlier = const [],
int? badgeCount,
}) async {
final badge = badgeCount ?? notification.badgeCount;
try {
switch (notification.type) {
case _NotificationType.message:
@@ -916,8 +1072,9 @@ class NotificationService {
isChannel: false,
message: notification.body,
urlImagesEnabled: notification.urlImagesEnabled,
badgeCount: notification.badgeCount,
badgeCount: badge,
silent: silent,
earlier: earlier,
);
break;
case _NotificationType.advert:
@@ -939,8 +1096,9 @@ class NotificationService {
message: notification.body,
senderName: notification.senderName,
urlImagesEnabled: notification.urlImagesEnabled,
badgeCount: notification.badgeCount,
badgeCount: badge,
silent: silent,
earlier: earlier,
);
break;
}
@@ -965,7 +1123,7 @@ class NotificationService {
channelDescription: 'Batched notification summaries',
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
icon: '@mipmap/ic_launcher',
icon: '@drawable/ic_stat_notification',
);
const notificationDetails = NotificationDetails(android: androidDetails);
+230 -146
View File
@@ -1,18 +1,23 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import '../models/contact.dart';
import '../models/path_history.dart';
import '../models/path_selection.dart';
import '../utils/app_logger.dart';
import '../utils/coalesced_writes.dart';
import 'route_chooser.dart';
import 'storage_service.dart';
class PathHistoryService extends ChangeNotifier {
final StorageService _storage;
final Map<String, ContactPathHistory> _cache = {};
final Map<String, int> _autoRotationIndex = {};
final Map<String, _FloodStats> _floodStats = {};
final Map<String, Future<void>> _pendingLoads = {};
final Map<String, Future<bool>> _pendingLoads = {};
int _generation = 0;
bool _disposed = false;
Future<void> _clearing = Future<void>.value();
// A path record lands for most received messages, so saves are batched.
final CoalescedWrites _writes = CoalescedWrites(
delay: const Duration(seconds: 5),
@@ -24,19 +29,33 @@ class PathHistoryService extends ChangeNotifier {
static const int _maxHistoryEntries = 100;
/// A failing route is only deleted once it hasn't delivered for this long.
static const Duration _forgetRouteAfter = Duration(days: 7);
int _version = 0;
int get version => _version;
PathHistoryService(this._storage);
final math.Random _random;
final DateTime Function() _now;
/// [random] and [clock] are for tests: route picks are random by design.
PathHistoryService(
this._storage, {
math.Random? random,
DateTime Function()? clock,
}) : _random = random ?? math.Random(),
_now = clock ?? DateTime.now;
void setDevicePublicKey(String publicKeyHex) {
if (_disposed) return;
// Queued saves use the storage key on entry, so they still land under
// the previous radio's key.
unawaited(_writes.flush());
_generation++;
_pendingLoads.clear();
_storage.setPublicKeyHex = publicKeyHex;
_cache.clear();
_cacheAccessOrder.clear();
_autoRotationIndex.clear();
_floodStats.clear();
_version++;
notifyListeners();
@@ -47,6 +66,7 @@ class PathHistoryService extends ChangeNotifier {
}
void handlePathUpdated(Contact contact, {double initialWeight = 1.0}) {
if (_disposed) return;
if (contact.pathLength < 0 && contact.path.isEmpty) return;
final hopCount = contact.pathLength < 0
? contact.path.length
@@ -65,6 +85,7 @@ class PathHistoryService extends ChangeNotifier {
}
void recordPathAttempt(String contactPubKeyHex, PathSelection selection) {
if (_disposed) return;
if (selection.useFlood) {
_updateFloodStats(contactPubKeyHex);
return;
@@ -92,10 +113,18 @@ class PathHistoryService extends ChangeNotifier {
double successIncrement = 0.5,
double maxWeight = 5.0,
}) {
if (pathBytes.isEmpty || hopCount < 0) return;
if (_disposed) return;
// A flood answered directly credits the direct (zero-hop) path.
if (hopCount < 0 || (pathBytes.isEmpty && hopCount != 0)) return;
if (!_cache.containsKey(contactPubKeyHex)) {
_ensureLoaded(contactPubKeyHex).then((_) {
if (!_cache.containsKey(contactPubKeyHex)) return;
final generation = _generation;
_ensureLoaded(contactPubKeyHex).then((loaded) {
if (!loaded ||
_disposed ||
generation != _generation ||
!_cache.containsKey(contactPubKeyHex)) {
return;
}
recordFloodPathAttribution(
contactPubKeyHex: contactPubKeyHex,
pathBytes: pathBytes,
@@ -111,6 +140,8 @@ class PathHistoryService extends ChangeNotifier {
final existing = _findPathRecord(contactPubKeyHex, pathBytes);
final successCount = (existing?.successCount ?? 0) + 1;
final failureCount = existing?.failureCount ?? 0;
final now = _now();
final faded = addRouteResult(existing, success: true, now: now);
final currentWeight = existing?.routeWeight ?? 1.0;
final newWeight = (currentWeight + successIncrement).clamp(0.0, maxWeight);
@@ -129,7 +160,10 @@ class PathHistoryService extends ChangeNotifier {
successCount: successCount,
failureCount: failureCount,
routeWeight: newWeight,
timestamp: DateTime.now(),
timestamp: now,
recentSuccess: faded.success,
recentFailure: faded.failure,
statsAt: now,
);
}
@@ -142,6 +176,7 @@ class PathHistoryService extends ChangeNotifier {
double failureDecrement = 0.5,
double maxWeight = 5.0,
}) {
if (_disposed) return;
if (selection.useFlood) {
final stats = _floodStats.putIfAbsent(
contactPubKeyHex,
@@ -158,8 +193,14 @@ class PathHistoryService extends ChangeNotifier {
}
if (!_cache.containsKey(contactPubKeyHex)) {
_ensureLoaded(contactPubKeyHex).then((_) {
if (!_cache.containsKey(contactPubKeyHex)) return;
final generation = _generation;
_ensureLoaded(contactPubKeyHex).then((loaded) {
if (!loaded ||
_disposed ||
generation != _generation ||
!_cache.containsKey(contactPubKeyHex)) {
return;
}
recordPathResult(
contactPubKeyHex,
selection,
@@ -176,6 +217,8 @@ class PathHistoryService extends ChangeNotifier {
final existing = _findPathRecord(contactPubKeyHex, selection.pathBytes);
final successCount = (existing?.successCount ?? 0) + (success ? 1 : 0);
final failureCount = (existing?.failureCount ?? 0) + (success ? 0 : 1);
final now = _now();
final faded = addRouteResult(existing, success: success, now: now);
final currentWeight = existing?.routeWeight ?? 1.0;
double newWeight;
@@ -183,7 +226,14 @@ class PathHistoryService extends ChangeNotifier {
newWeight = (currentWeight + successIncrement).clamp(0.0, maxWeight);
} else {
newWeight = currentWeight - failureDecrement;
if (newWeight <= 0 && failureCount >= 3) {
// Faded stats already push a failing route out of use, and a repeater
// that is down for a day comes back; only forget a route that keeps
// failing and hasn't delivered in a week. Route weight is bookkeeping
// only now and plays no part in this.
final lastWorked = existing?.timestamp;
final longDead =
lastWorked == null || now.difference(lastWorked) > _forgetRouteAfter;
if (failureCount >= 3 && longDead) {
removePathRecord(contactPubKeyHex, selection.pathBytes);
return;
}
@@ -200,21 +250,31 @@ class PathHistoryService extends ChangeNotifier {
successCount: successCount,
failureCount: failureCount,
routeWeight: newWeight,
timestamp: success ? DateTime.now() : existing?.timestamp,
timestamp: success ? now : existing?.timestamp,
recentSuccess: faded.success,
recentFailure: faded.failure,
statsAt: now,
);
}
/// Route for one send attempt of a message to [contactPubKeyHex].
///
/// The last attempt always floods. Otherwise a known route is drawn by
/// Thompson sampling over faded delivery stats, weighted by how well it
/// fits [context]; routes used for this message's recent attempts score
/// lower so retries usually try something different.
PathSelection selectPathForAttempt(
String contactPubKeyHex, {
required int attemptIndex,
required int maxRetries,
List<PathSelection> recentSelections = const [],
RouteContext context = RouteContext.unknown,
}) {
if (maxRetries <= 0 || attemptIndex >= maxRetries - 1) {
return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
}
final ranked = _getRankedPaths(contactPubKeyHex);
final ranked = _getRankedPaths(contactPubKeyHex, context: context);
if (ranked.isEmpty) {
return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
}
@@ -225,20 +285,15 @@ class PathHistoryService extends ChangeNotifier {
.where((selection) => !selection.useFlood)
.map((selection) => selection.pathBytes)
.toList();
final candidates = recentPaths.isEmpty
? ranked
: ranked
.where(
(path) => !recentPaths.any(
(recentPath) => _pathsEqual(path.pathBytes, recentPath),
),
)
.toList();
final selected = candidates.isNotEmpty
? (recentPaths.isEmpty
? _selectRotatedCandidate(contactPubKeyHex, candidates)
: candidates.first)
: ranked.first;
final selected = pickRoute(
ranked,
random: _random,
now: _now(),
context: context,
triedThisMessage: (path) => recentPaths.any(
(recentPath) => _pathsEqual(path.pathBytes, recentPath),
),
);
return PathSelection(
pathBytes: selected.pathBytes,
@@ -247,22 +302,6 @@ class PathHistoryService extends ChangeNotifier {
);
}
PathRecord _selectRotatedCandidate(
String contactPubKeyHex,
List<PathRecord> candidates,
) {
if (candidates.length <= 1) {
_autoRotationIndex[contactPubKeyHex] = 0;
return candidates.first;
}
final currentIndex = _autoRotationIndex[contactPubKeyHex] ?? 0;
final selectedIndex = currentIndex % candidates.length;
_autoRotationIndex[contactPubKeyHex] =
(selectedIndex + 1) % candidates.length;
return candidates[selectedIndex];
}
void _addPathRecord({
required String contactPubKeyHex,
required int hopCount,
@@ -274,7 +313,12 @@ class PathHistoryService extends ChangeNotifier {
double? routeWeight,
double initialWeight = 1.0,
DateTime? timestamp,
double? recentSuccess,
double? recentFailure,
DateTime? statsAt,
}) {
if (_disposed) return;
final generation = _generation;
void add() => _addPathRecordInternal(
contactPubKeyHex,
hopCount,
@@ -286,32 +330,51 @@ class PathHistoryService extends ChangeNotifier {
routeWeight,
initialWeight,
timestamp,
recentSuccess: recentSuccess,
recentFailure: recentFailure,
statsAt: statsAt,
);
if (_cache.containsKey(contactPubKeyHex)) {
add();
} else {
_ensureLoaded(contactPubKeyHex).then((_) => add());
_ensureLoaded(contactPubKeyHex).then((loaded) {
if (loaded && !_disposed && generation == _generation) add();
});
}
}
Future<void> _ensureLoaded(String contactPubKeyHex) {
if (_cache.containsKey(contactPubKeyHex)) return Future.value();
return _pendingLoads[contactPubKeyHex] ??=
_loadHistoryFromStorage(contactPubKeyHex)
.then((loaded) {
_cache[contactPubKeyHex] ??=
loaded ??
ContactPathHistory(
contactPubKeyHex: contactPubKeyHex,
recentPaths: [],
);
_trackAccess(contactPubKeyHex);
_evictIfNeeded();
})
.whenComplete(() {
_pendingLoads.remove(contactPubKeyHex);
});
Future<bool> _ensureLoaded(String contactPubKeyHex) {
if (_disposed) return Future.value(false);
if (_cache.containsKey(contactPubKeyHex)) return Future.value(true);
final existing = _pendingLoads[contactPubKeyHex];
if (existing != null) return existing;
final generation = _generation;
late final Future<bool> pending;
pending = _loadHistoryFromStorage(contactPubKeyHex)
.then((loaded) {
if (_disposed ||
generation != _generation ||
!identical(_pendingLoads[contactPubKeyHex], pending)) {
return false;
}
_cache[contactPubKeyHex] ??=
loaded ??
ContactPathHistory(
contactPubKeyHex: contactPubKeyHex,
recentPaths: [],
);
_trackAccess(contactPubKeyHex);
_evictIfNeeded();
return true;
})
.whenComplete(() {
if (identical(_pendingLoads[contactPubKeyHex], pending)) {
_pendingLoads.remove(contactPubKeyHex);
}
});
_pendingLoads[contactPubKeyHex] = pending;
return pending;
}
void _addPathRecordInternal(
@@ -324,8 +387,12 @@ class PathHistoryService extends ChangeNotifier {
int failureCount,
double? routeWeight,
double initialWeight,
DateTime? timestamp,
) {
DateTime? timestamp, {
double? recentSuccess,
double? recentFailure,
DateTime? statsAt,
}) {
if (_disposed) return;
var history = _cache[contactPubKeyHex];
if (history == null) return;
_version++;
@@ -339,6 +406,12 @@ class PathHistoryService extends ChangeNotifier {
}
wasFloodDiscovery = existing.wasFloodDiscovery || wasFloodDiscovery;
timestamp ??= existing.timestamp;
if (recentSuccess == null) {
// Not a result: keep the faded stats as they were.
recentSuccess = existing.recentSuccess;
recentFailure = existing.recentFailure;
statsAt = existing.statsAt;
}
}
routeWeight ??= existing?.routeWeight ?? initialWeight;
@@ -351,6 +424,10 @@ class PathHistoryService extends ChangeNotifier {
successCount: successCount,
failureCount: failureCount,
routeWeight: routeWeight,
// A brand-new record starts with no faded results.
recentSuccess: recentSuccess ?? 0,
recentFailure: recentFailure ?? 0,
statsAt: statsAt,
);
final updatedPaths = List<PathRecord>.from(history.recentPaths);
@@ -394,6 +471,7 @@ class PathHistoryService extends ChangeNotifier {
/// Reads saved paths straight from storage without adding them to the
/// cache, evicting anything, or notifying listeners.
Future<List<PathRecord>> readStoredPaths(String contactPubKeyHex) async {
if (_disposed) return [];
final cached = _cache[contactPubKeyHex];
if (cached != null) return cached.recentPaths;
final stored = await _loadHistoryFromStorage(contactPubKeyHex);
@@ -401,13 +479,16 @@ class PathHistoryService extends ChangeNotifier {
}
List<PathRecord> getRecentPaths(String contactPubKeyHex) {
if (_disposed) return [];
final history = _cache[contactPubKeyHex];
if (history != null) {
_trackAccess(contactPubKeyHex);
return history.recentPaths;
}
_ensureLoaded(contactPubKeyHex).then((_) {
final generation = _generation;
_ensureLoaded(contactPubKeyHex).then((loaded) {
if (!loaded || _disposed || generation != _generation) return;
if (_cache[contactPubKeyHex]?.recentPaths.isNotEmpty ?? false) {
_version++;
notifyListeners();
@@ -420,10 +501,12 @@ class PathHistoryService extends ChangeNotifier {
Future<ContactPathHistory?> _loadHistoryFromStorage(
String contactPubKeyHex,
) async {
// An evicted contact may still have a queued save; it reaches the prefs
// cache synchronously, so the load below reads it.
unawaited(_writes.flush());
return await _storage.loadPathHistory(contactPubKeyHex);
final generation = _generation;
await _clearing;
await _writes.flush();
if (_disposed || generation != _generation) return null;
final history = await _storage.loadPathHistory(contactPubKeyHex);
return _disposed || generation != _generation ? null : history;
}
PathRecord? getFastestPath(String contactPubKeyHex) {
@@ -459,13 +542,38 @@ class PathHistoryService extends ChangeNotifier {
);
}
/// Runs [clear] after earlier clears and queued saves. [_clearing] itself
/// never fails, so one failed clear cannot break later loads and flushes;
/// the returned future still reports the failure to its caller.
Future<void> _queueClear(int generation, Future<void> Function() clear) {
final previous = _clearing;
final run = () async {
await previous;
await _writes.flush();
if (_disposed || generation != _generation) return;
await clear();
}();
_clearing = run.then<void>(
(_) {},
onError: (Object error, StackTrace _) {
appLogger.warn('Clearing path history failed: $error', tag: 'Storage');
},
);
return run;
}
Future<void> clearPathHistory(String contactPubKeyHex) async {
if (_disposed) return;
final generation = _generation;
_pendingLoads.remove(contactPubKeyHex);
_cache.remove(contactPubKeyHex);
_cacheAccessOrder.remove(contactPubKeyHex);
_autoRotationIndex.remove(contactPubKeyHex);
_floodStats.remove(contactPubKeyHex);
_writes.cancel(contactPubKeyHex);
await _storage.clearPathHistory(contactPubKeyHex);
await _queueClear(generation, () {
return _storage.clearPathHistory(contactPubKeyHex);
});
if (_disposed || generation != _generation) return;
_version++;
notifyListeners();
}
@@ -474,6 +582,8 @@ class PathHistoryService extends ChangeNotifier {
String contactPubKeyHex,
List<int> pathBytes,
) async {
if (_disposed) return;
final generation = _generation;
final history = _cache[contactPubKeyHex];
if (history == null) return;
@@ -485,8 +595,12 @@ class PathHistoryService extends ChangeNotifier {
recentPaths: updatedPaths,
);
final updated = _cache[contactPubKeyHex]!;
_writes.cancel(contactPubKeyHex);
await _storage.savePathHistory(contactPubKeyHex, _cache[contactPubKeyHex]!);
await _writes.flush();
if (_disposed || generation != _generation) return;
await _storage.savePathHistory(contactPubKeyHex, updated);
if (_disposed || generation != _generation) return;
_version++;
notifyListeners();
}
@@ -502,34 +616,32 @@ class PathHistoryService extends ChangeNotifier {
return null;
}
List<PathRecord> _getRankedPaths(String contactPubKeyHex) {
List<PathRecord> _getRankedPaths(
String contactPubKeyHex, {
RouteContext context = RouteContext.unknown,
}) {
final history = _cache[contactPubKeyHex];
if (history == null) return [];
// Records without hop bytes are unusable, except the direct path: zero
// hops has no bytes by definition (issue #643: rotation never tried it).
final ranked = List<PathRecord>.from(history.recentPaths)
..removeWhere((p) => p.pathBytes.isEmpty);
final fastestTripMs = _getFastestKnownTripMs(ranked);
final highestRouteWeight = _getHighestKnownRouteWeight(ranked);
..removeWhere((p) => p.pathBytes.isEmpty && p.hopCount != 0);
final now = _now();
final fastest = fastestTripMs(ranked);
final scores = {
for (final p in ranked)
p: routeExpectedScore(
p,
now: now,
fastestTripMs: fastest,
context: context,
),
};
ranked.sort((a, b) {
final scoreCompare =
_scorePathRecord(
b,
fastestTripMs: fastestTripMs,
highestRouteWeight: highestRouteWeight,
).compareTo(
_scorePathRecord(
a,
fastestTripMs: fastestTripMs,
highestRouteWeight: highestRouteWeight,
),
);
if (scoreCompare != 0) {
return scoreCompare;
}
if (a.routeWeight != b.routeWeight) {
return b.routeWeight.compareTo(a.routeWeight);
}
final scoreCompare = scores[b]!.compareTo(scores[a]!);
if (scoreCompare != 0) return scoreCompare;
final aTrip = a.tripTimeMs == 0 ? 999999 : a.tripTimeMs;
final bTrip = b.tripTimeMs == 0 ? 999999 : b.tripTimeMs;
if (aTrip != bTrip) return aTrip.compareTo(bTrip);
@@ -542,58 +654,13 @@ class PathHistoryService extends ChangeNotifier {
}
PathRecord _lowestScoredPath(List<PathRecord> paths) {
final fastestTripMs = _getFastestKnownTripMs(paths);
final highestRouteWeight = _getHighestKnownRouteWeight(paths);
double score(PathRecord p) => _scorePathRecord(
p,
fastestTripMs: fastestTripMs,
highestRouteWeight: highestRouteWeight,
);
final now = _now();
final fastest = fastestTripMs(paths);
double score(PathRecord p) =>
routeExpectedScore(p, now: now, fastestTripMs: fastest);
return paths.reduce((a, b) => score(b) < score(a) ? b : a);
}
int? _getFastestKnownTripMs(List<PathRecord> paths) {
final knownTrips = paths
.where((path) => path.tripTimeMs > 0)
.map((path) => path.tripTimeMs)
.toList();
if (knownTrips.isEmpty) return null;
return knownTrips.reduce((a, b) => a < b ? a : b);
}
double _getHighestKnownRouteWeight(List<PathRecord> paths) {
if (paths.isEmpty) return 1.0;
final highestWeight = paths
.map((path) => path.routeWeight)
.reduce((a, b) => a > b ? a : b);
return highestWeight <= 0 ? 1.0 : highestWeight;
}
double _scorePathRecord(
PathRecord path, {
required int? fastestTripMs,
required double highestRouteWeight,
}) {
final totalAttempts = path.successCount + path.failureCount;
final reliability = (path.successCount + 1) / (totalAttempts + 2);
final latency = fastestTripMs == null || path.tripTimeMs <= 0
? 0.6
: (fastestTripMs / path.tripTimeMs).clamp(0.0, 1.0);
final freshness = path.timestamp == null
? 0.0
: 1.0 /
(1.0 +
(DateTime.now().difference(path.timestamp!).inMinutes /
60.0 /
24.0));
final routeWeight = (path.routeWeight / highestRouteWeight).clamp(0.0, 1.0);
return (reliability * 0.45) +
(latency * 0.25) +
(freshness * 0.1) +
(routeWeight * 0.2);
}
bool _pathsEqual(List<int> a, List<int> b) {
return listEquals(a, b);
}
@@ -615,27 +682,44 @@ class PathHistoryService extends ChangeNotifier {
while (_cache.length > _maxCachedContacts && _cacheAccessOrder.isNotEmpty) {
final oldest = _cacheAccessOrder.removeAt(0);
_cache.remove(oldest);
_autoRotationIndex.remove(oldest);
_floodStats.remove(oldest);
}
}
/// Runs queued saves now, e.g. before the app is backgrounded.
Future<void> flushPendingWrites() => _writes.flush();
Future<void> flushPendingWrites() async {
await _clearing;
await _writes.flush();
}
@override
void dispose() {
if (_disposed) return;
unawaited(_writes.flush());
_disposed = true;
_generation++;
_pendingLoads.clear();
_cache.clear();
_cacheAccessOrder.clear();
_floodStats.clear();
super.dispose();
}
void clearAllHistories() {
if (_disposed) return;
final generation = ++_generation;
_pendingLoads.clear();
_cache.clear();
_cacheAccessOrder.clear();
_autoRotationIndex.clear();
_floodStats.clear();
_writes.dispose();
_storage.clearAllPathHistories();
// Nothing awaits this one; _queueClear logs a failure.
unawaited(
_queueClear(
generation,
_storage.clearAllPathHistories,
).catchError((Object _) {}),
);
_version = 0;
notifyListeners();
}
+198
View File
@@ -0,0 +1,198 @@
import 'dart:math' as math;
import '../models/path_history.dart';
import '../models/path_selection.dart';
/// Results lose half their weight every [routeStatsHalfLife], so a route's
/// recent behaviour outweighs what it did weeks ago.
const Duration routeStatsHalfLife = Duration(hours: 24);
/// Most results a route's faded stats hold. Fading is by time, so a route
/// used constantly would otherwise pile up so many successes that it takes
/// dozens of failures to lose its rank after its repeater dies; the cap
/// keeps it to a handful.
const double routeEvidenceCap = 16;
/// Multiplier for a route that fits what the radio hears right now (its
/// first hop, or the contact itself for the direct route, was heard).
const double routeContextFitBonus = 1.15;
/// Multiplier for a route that doesn't fit what the radio hears right now.
/// Soft on purpose: not hearing a repeater is weak evidence it's gone.
const double routeContextMissPenalty = 0.6;
/// Small bonus for the path the radio itself currently holds.
const double routeRadioPathBonus = 1.05;
/// Score multiplier for a route already tried for the same message: retries
/// lean toward something different without wasting the attempt on a route
/// much weaker than the one that just missed.
const double routeRetryRepeatPenalty = 0.5;
/// Share of the score that comes from speed; the rest is delivery odds.
const double _speedShare = 0.15;
/// Fraction of a result's weight left after the time from [since] to [now].
double routeDecayFactor(DateTime? since, DateTime now) {
if (since == null) return 1.0;
final seconds = now.difference(since).inSeconds;
if (seconds <= 0) return 1.0;
return math.pow(0.5, seconds / routeStatsHalfLife.inSeconds).toDouble();
}
/// [record]'s faded delivery and failure counts as of [now].
({double success, double failure}) fadedRouteStats(
PathRecord record,
DateTime now,
) {
final f = routeDecayFactor(record.statsAt, now);
return (success: record.recentSuccess * f, failure: record.recentFailure * f);
}
/// Faded counts after adding one result to [record] (or to a new route when
/// it is null) at [now].
({double success, double failure}) addRouteResult(
PathRecord? record, {
required bool success,
required DateTime now,
}) {
final faded = record == null
? (success: 0.0, failure: 0.0)
: fadedRouteStats(record, now);
var s = faded.success + (success ? 1 : 0);
var f = faded.failure + (success ? 0 : 1);
final total = s + f;
if (total > routeEvidenceCap) {
final scale = routeEvidenceCap / total;
s *= scale;
f *= scale;
}
return (success: s, failure: f);
}
/// How well [record] fits what the radio hears right now.
double routeContextFactor(PathRecord record, RouteContext context) {
var factor = 1.0;
final radioPath = context.radioPath;
if (radioPath != null &&
radioPath.length == record.pathBytes.length &&
_sameBytes(radioPath, record.pathBytes)) {
factor *= routeRadioPathBonus;
}
if (!context.hasNeighbourInfo) return factor;
final fits = record.hopCount == 0
? context.contactHeardDirectly
: context.firstHopHeard(record.pathBytes, record.hashWidth);
return factor * (fits ? routeContextFitBonus : routeContextMissPenalty);
}
double _speedFactor(PathRecord record, int? fastestTripMs) {
final speed = fastestTripMs == null || record.tripTimeMs <= 0
? 0.6
: (fastestTripMs / record.tripTimeMs).clamp(0.0, 1.0);
return (1 - _speedShare) + _speedShare * speed;
}
/// Fastest known trip time among [records], or null when none is known.
int? fastestTripMs(Iterable<PathRecord> records) {
int? best;
for (final r in records) {
if (r.tripTimeMs > 0 && (best == null || r.tripTimeMs < best)) {
best = r.tripTimeMs;
}
}
return best;
}
/// Deterministic rank: expected delivery odds (faded), adjusted for speed
/// and context. Used for ordering lists and choosing what to evict.
double routeExpectedScore(
PathRecord record, {
required DateTime now,
required int? fastestTripMs,
RouteContext context = RouteContext.unknown,
}) {
final stats = fadedRouteStats(record, now);
final mean = (stats.success + 1) / (stats.success + stats.failure + 2);
return mean *
_speedFactor(record, fastestTripMs) *
routeContextFactor(record, context);
}
/// Thompson sampling: draws plausible delivery odds for each route from what
/// is known about it and returns the route with the best draw. Proven routes
/// win most of the time; uncertain ones are still tried now and then, so a
/// route that starts working again gets noticed.
PathRecord pickRoute(
List<PathRecord> candidates, {
required math.Random random,
required DateTime now,
RouteContext context = RouteContext.unknown,
bool Function(PathRecord record)? triedThisMessage,
}) {
assert(candidates.isNotEmpty);
final fastest = fastestTripMs(candidates);
PathRecord? best;
var bestScore = -1.0;
for (final record in candidates) {
final stats = fadedRouteStats(record, now);
final draw = sampleBeta(random, stats.success + 1, stats.failure + 1);
final score =
draw *
_speedFactor(record, fastest) *
routeContextFactor(record, context) *
(triedThisMessage?.call(record) == true
? routeRetryRepeatPenalty
: 1.0);
if (score > bestScore) {
bestScore = score;
best = record;
}
}
return best!;
}
/// A sample from Beta([a], [b]), both > 0.
double sampleBeta(math.Random random, double a, double b) {
final x = _sampleGamma(random, a);
final y = _sampleGamma(random, b);
final sum = x + y;
return sum <= 0 ? 0.5 : x / sum;
}
/// Gamma(shape, 1) by Marsaglia–Tsang; shapes below 1 use the boost
/// Gamma(a) = Gamma(a + 1) * U^(1/a).
double _sampleGamma(math.Random random, double shape) {
if (shape < 1) {
final u = random.nextDouble();
return _sampleGamma(random, shape + 1) * math.pow(u, 1 / shape);
}
final d = shape - 1 / 3;
final c = 1 / math.sqrt(9 * d);
while (true) {
double x;
double v;
do {
x = _sampleNormal(random);
v = 1 + c * x;
} while (v <= 0);
v = v * v * v;
final u = random.nextDouble();
if (u < 1 - 0.0331 * x * x * x * x) return d * v;
if (math.log(u) < 0.5 * x * x + d * (1 - v + math.log(v))) return d * v;
}
}
double _sampleNormal(math.Random random) {
// Box–Muller; 1 - nextDouble() avoids log(0).
final u1 = 1 - random.nextDouble();
final u2 = random.nextDouble();
return math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2);
}
bool _sameBytes(List<int> a, List<int> b) {
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
+153
View File
@@ -0,0 +1,153 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import '../utils/platform_info.dart';
/// Dart half of Android's scrolling screenshot ("Capture more").
///
/// The native `FlutterScrollCapture` asks for the main scrollable on screen,
/// then has it scrolled strip by strip while it copies pixels. All sizes on
/// the channel are physical pixels in the Flutter view.
class ScrollCaptureService {
ScrollCaptureService._();
static const MethodChannel _channel = MethodChannel(
'meshcore_open/scroll_capture',
);
static ScrollableState? _target;
static double _startPixels = 0;
static void initialize() {
if (kIsWeb || !PlatformInfo.isAndroid) return;
_channel.setMethodCallHandler(_handle);
}
static Future<Object?> _handle(MethodCall call) async {
switch (call.method) {
case 'search':
return _search();
case 'start':
_startPixels = _target?.position.pixels ?? 0;
return null;
case 'scroll':
final args = call.arguments as Map<Object?, Object?>;
return _scrollTo((args['top'] as num).toDouble());
case 'end':
final target = _target;
_target = null;
if (target != null && target.mounted) {
target.position.jumpTo(_startPixels);
}
return null;
}
return null;
}
static FlutterView? get _view =>
WidgetsBinding.instance.platformDispatcher.implicitView;
/// The largest vertically scrollable, user-visible list on the top route.
static Map<String, int>? _search() {
final view = _view;
final root = WidgetsBinding.instance.rootElement;
if (view == null || root == null) return null;
final dpr = view.devicePixelRatio;
final screen = Offset.zero & (view.physicalSize / dpr);
ScrollableState? best;
Rect? bestRect;
void visit(Element element) {
if (element is StatefulElement && element.state is ScrollableState) {
final state = element.state as ScrollableState;
final rect = _candidateRect(state, element.renderObject, screen, view);
if (rect != null &&
(bestRect == null ||
rect.width * rect.height >=
bestRect!.width * bestRect!.height)) {
best = state;
bestRect = rect;
}
}
element.visitChildren(visit);
}
root.visitChildren(visit);
final rect = bestRect;
_target = best;
if (best == null || rect == null) return null;
return {
'left': (rect.left * dpr).round(),
'top': (rect.top * dpr).round(),
'right': (rect.right * dpr).round(),
'bottom': (rect.bottom * dpr).round(),
};
}
static Rect? _candidateRect(
ScrollableState state,
RenderObject? renderObject,
Rect screen,
FlutterView view,
) {
if (axisDirectionToAxis(state.axisDirection) != Axis.vertical) return null;
final position = state.position;
if (!position.hasContentDimensions ||
position.maxScrollExtent <= position.minScrollExtent) {
return null;
}
if (renderObject is! RenderBox ||
!renderObject.attached ||
!renderObject.hasSize) {
return null;
}
final rect = MatrixUtils.transformRect(
renderObject.getTransformTo(null),
Offset.zero & renderObject.size,
).intersect(screen);
if (rect.isEmpty || rect.height < 100) return null;
// Only a list the user can actually see: the topmost hit at its centre
// must be inside it (rules out lists on routes underneath, or covered
// by a sheet or dialog).
final result = HitTestResult();
WidgetsBinding.instance.hitTestInView(result, rect.center, view.viewId);
if (!result.path.any((entry) => entry.target == renderObject)) return null;
return rect;
}
/// Scrolls so the strip starting [top] physical px below the start
/// position's top edge is at the top of the list, as far as the content
/// allows. Returns how far it actually moved, in physical px.
static Future<double> _scrollTo(double top) async {
final target = _target;
final view = _view;
if (target == null || !target.mounted || view == null) return 0;
final dpr = view.devicePixelRatio;
final position = target.position;
// In a reversed list (the chat transcript) moving down the screen means
// smaller scroll offsets.
final up = target.axisDirection == AxisDirection.up;
final delta = top / dpr;
final wanted = (up ? _startPixels - delta : _startPixels + delta).clamp(
position.minScrollExtent,
position.maxScrollExtent,
);
position.jumpTo(wanted);
// Bounded: if frames are not being produced (app no longer resumed),
// waiting forever would leave the native capture request hanging.
for (var i = 0; i < 2; i++) {
await WidgetsBinding.instance.endOfFrame.timeout(
const Duration(milliseconds: 250),
onTimeout: () {},
);
}
if (!target.mounted) return 0;
final moved = up
? _startPixels - position.pixels
: position.pixels - _startPixels;
return moved * dpr;
}
}
+17 -14
View File
@@ -3,6 +3,7 @@ import '../models/delivery_observation.dart';
import '../models/path_history.dart';
import '../storage/legacy_key_migration.dart';
import '../storage/prefs_manager.dart';
import '../storage/history_store.dart';
import '../utils/app_logger.dart';
class StorageService {
@@ -64,30 +65,32 @@ class StorageService {
String contactPubKeyHex,
ContactPathHistory history,
) async {
final prefs = PrefsManager.instance;
final prefs = HistoryStore.instance;
final key = _pathHistoryKey(contactPubKeyHex);
final jsonStr = jsonEncode(history.toJson());
await prefs.setString(key, jsonStr);
}
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
final prefs = PrefsManager.instance;
final prefs = HistoryStore.instance;
final scope = _publicKeyHex;
final allowLegacyMigration =
scope.isNotEmpty && canMigrateLegacyKeys(scope);
final key = _pathHistoryKey(contactPubKeyHex);
var jsonStr = prefs.getString(key);
var jsonStr = await prefs.getString(key);
final legacyKey = '$_pathHistoryPrefix$contactPubKeyHex';
if (jsonStr == null &&
_publicKeyHex.isNotEmpty &&
canMigrateLegacyKeys(_publicKeyHex)) {
if (jsonStr == null && allowLegacyMigration) {
// Move the pre-scoping history into the first radio that loads it so
// learned routes survive the upgrade without leaking into other radios.
final legacy = prefs.getString(legacyKey);
final legacy = await prefs.getString(legacyKey);
if (legacy != null) {
await prefs.setString(key, legacy);
await prefs.remove(legacyKey);
if (await prefs.setString(key, legacy)) {
await prefs.remove(legacyKey);
}
jsonStr = legacy;
}
} else if (jsonStr == null && _publicKeyHex.isEmpty) {
jsonStr = prefs.getString(legacyKey);
} else if (jsonStr == null && scope.isEmpty) {
jsonStr = await prefs.getString(legacyKey);
}
if (jsonStr == null) return null;
@@ -101,7 +104,7 @@ class StorageService {
}
Future<void> clearPathHistory(String contactPubKeyHex) async {
final prefs = PrefsManager.instance;
final prefs = HistoryStore.instance;
await prefs.remove(_pathHistoryKey(contactPubKeyHex));
await prefs.remove('$_pathHistoryPrefix$contactPubKeyHex');
}
@@ -109,7 +112,7 @@ class StorageService {
/// Clears the path histories of the connected radio only. Histories of other
/// radios are left alone; with no radio scope set, everything is cleared.
Future<void> clearAllPathHistories() async {
final prefs = PrefsManager.instance;
final prefs = HistoryStore.instance;
final scopedPrefix = _publicKeyHex.isEmpty
? _pathHistoryPrefix
: '$_pathHistoryPrefix${_publicKeyHex}_';
@@ -117,7 +120,7 @@ class StorageService {
// radio on the next load and bring the cleared routes back.
final clearLegacy =
_publicKeyHex.isNotEmpty && canMigrateLegacyKeys(_publicKeyHex);
final pathHistoryKeys = prefs.getKeys().where((key) {
final pathHistoryKeys = (await prefs.getKeys()).where((key) {
if (key.startsWith(scopedPrefix)) return true;
return clearLegacy &&
key.startsWith(_pathHistoryPrefix) &&
+14 -2
View File
@@ -7,6 +7,7 @@ import 'package:flutter_langdetect/flutter_langdetect.dart';
import '../models/app_settings.dart';
import '../models/translation_support.dart';
import '../helpers/contact_share_message.dart';
import '../helpers/gif_helper.dart';
import '../utils/app_logger.dart';
import 'app_settings_service.dart';
@@ -142,18 +143,25 @@ class TranslationService extends ChangeNotifier {
return availableModels.isNotEmpty ? availableModels.first : null;
}
Future<void> refreshDownloadedModels() async {
Future<void> refreshDownloadedModels({bool clearMissing = false}) async {
if (_isDownloading) return;
final scanned = await _fileStore.scanDownloadedModels();
if (scanned.isEmpty && !clearMissing) return;
if (scanned.isEmpty) {
await _appSettingsService.setTranslationDownloadedModels(const []);
return;
}
final existingByPath = {
for (final model in _settings.translationDownloadedModels)
model.localPath: model,
};
final existingByName = {
for (final model in _settings.translationDownloadedModels)
model.name: model,
};
final merged = scanned.map((model) {
final existing = existingByPath[model.localPath];
final existing =
existingByPath[model.localPath] ?? existingByName[model.name];
if (existing == null) {
return model;
}
@@ -573,6 +581,10 @@ class TranslationService extends ChangeNotifier {
if (GifHelper.parseGif(trimmed) != null) {
return false;
}
// A shared contact card is data: translating it would mangle the token.
if (parseContactShare(trimmed) != null) {
return false;
}
return !(trimmed.startsWith('m:') ||
trimmed.startsWith('V1|') ||
trimmed.startsWith('r:'));