Merge branch 'dev' into ez_disable_discoveredContact_eviction_PR
This commit is contained in:
195 files changed
+26503
-6523
No files matched your search
@@ -105,6 +105,10 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(mapShowGuessedLocations: value));
|
||||
}
|
||||
|
||||
Future<void> setMapClusterNodes(bool value) async {
|
||||
await updateSettings(_settings.copyWith(mapClusterNodes: value));
|
||||
}
|
||||
|
||||
Future<void> setEnableMessageTracing(bool value) async {
|
||||
await updateSettings(_settings.copyWith(enableMessageTracing: value));
|
||||
}
|
||||
@@ -206,6 +210,18 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(maxMessageRetries: value));
|
||||
}
|
||||
|
||||
Future<void> setChannelMinHopsEnabled(bool value) async {
|
||||
await updateSettings(_settings.copyWith(channelMinHopsEnabled: value));
|
||||
}
|
||||
|
||||
Future<void> setChannelMinHops(int value) async {
|
||||
await updateSettings(_settings.copyWith(channelMinHops: value));
|
||||
}
|
||||
|
||||
Future<void> setChannelMinHopsRetries(int value) async {
|
||||
await updateSettings(_settings.copyWith(channelMinHopsRetries: value));
|
||||
}
|
||||
|
||||
Future<void> setThemeMode(String value) async {
|
||||
await updateSettings(_settings.copyWith(themeMode: value));
|
||||
}
|
||||
|
||||
@@ -70,6 +70,11 @@ class BackgroundService {
|
||||
return AppLocalizations.delegate.load(match);
|
||||
}
|
||||
|
||||
static Future<void> openBatteryOptimizationSettings() async {
|
||||
if (!PlatformInfo.isAndroid) return;
|
||||
await FlutterForegroundTask.openIgnoreBatteryOptimizationSettings();
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
if (!PlatformInfo.isAndroid) return;
|
||||
final running = await FlutterForegroundTask.isRunningService;
|
||||
|
||||
@@ -630,6 +630,9 @@ enum ImageReassemblyFailureReason {
|
||||
/// Reassembled but the metadata byte was undecodable
|
||||
/// ([ImageChunkStatus.unsupportedFormat]).
|
||||
unsupportedFormat,
|
||||
|
||||
/// Dropped by [ImageReassembler.clear] (disconnect / new session).
|
||||
disconnected,
|
||||
}
|
||||
|
||||
/// A fully reassembled image.
|
||||
@@ -852,10 +855,27 @@ class ImageReassembler {
|
||||
/// Keys of the remembered completed images (test/debug aid).
|
||||
Iterable<ImageStreamKey> get completedKeys => _recentlyCompleted.keys;
|
||||
|
||||
/// Drops everything (e.g. on disconnect). Does not fire [onFailed].
|
||||
void clear() {
|
||||
/// Drops everything (e.g. on disconnect). In-progress streams are reported
|
||||
/// through [onFailed] right away, so their bubbles stop showing "receiving";
|
||||
/// nothing is left behind for [evictExpired] to report later.
|
||||
void clear({DateTime? now}) {
|
||||
final at = now ?? _clock();
|
||||
final dropped = _pending.values.toList();
|
||||
_pending.clear();
|
||||
_recentlyCompleted.clear();
|
||||
for (final entry in dropped) {
|
||||
onFailed?.call(
|
||||
ImageReassemblyFailure(
|
||||
key: entry.key,
|
||||
total: entry.total,
|
||||
receivedDataChunks: entry.bodies.length,
|
||||
hadParity: entry.hasParity,
|
||||
firstSeen: entry.firstSeen,
|
||||
expiredAt: at,
|
||||
reason: ImageReassemblyFailureReason.disconnected,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds one received GRP_DATA blob.
|
||||
@@ -883,6 +903,12 @@ class ImageReassembler {
|
||||
// A parity chunk must carry at least its length byte.
|
||||
return ImageChunkOutcome(ImageChunkStatus.malformed, header: header);
|
||||
}
|
||||
if (!header.isParity && body.length > kImageChunkBodyBytes) {
|
||||
// The blob cap leaves room for one byte more than the XOR buffer holds;
|
||||
// such a body can never come from [buildImageChunks] and would overrun
|
||||
// parity recovery.
|
||||
return ImageChunkOutcome(ImageChunkStatus.malformed, header: header);
|
||||
}
|
||||
|
||||
final key = ImageStreamKey(
|
||||
senderPrefix: header.senderPrefix,
|
||||
|
||||
@@ -90,6 +90,10 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
String? _lastError;
|
||||
Future<void> _queue = Future<void>.value();
|
||||
ImageCodecSession? _session;
|
||||
|
||||
/// Teardown started by [handleMemoryPressure]; [_ensureSession] waits for it
|
||||
/// so a second isolate is never spawned while the first is still resident.
|
||||
Future<void>? _pendingRelease;
|
||||
ImageCodecBundle? _loadedBundle;
|
||||
ImageCodecBundle? _failedBundle;
|
||||
int _downloadedBytes = 0;
|
||||
@@ -980,6 +984,17 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
return bitstream;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Uint8List?> decodePreview(Uint8List payload) async {
|
||||
if (!canDecode) return null;
|
||||
final result = await decodeBitstream(
|
||||
bitstream: payload,
|
||||
ratePoint: aeicRatePointForUi(kImageSendRatePoint),
|
||||
resolution: kImageCodecSquareSize,
|
||||
);
|
||||
return result?.pngBytes;
|
||||
}
|
||||
|
||||
/// Encodes an already-decoded RGB image.
|
||||
///
|
||||
/// [rgbBytes] must be exactly `512 * 512 * 3` packed 8-bit RGB. Anything else
|
||||
@@ -1339,6 +1354,12 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
// ---- model memory (mirrors translation_service.dart:586-629) -------------
|
||||
|
||||
Future<ImageCodecSession?> _ensureSession(ImageCodecBundle bundle) async {
|
||||
final pendingRelease = _pendingRelease;
|
||||
if (pendingRelease != null) {
|
||||
try {
|
||||
await pendingRelease;
|
||||
} catch (_) {}
|
||||
}
|
||||
if (_session != null && _loadedBundle == bundle) {
|
||||
return _session;
|
||||
}
|
||||
@@ -1455,8 +1476,16 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
if (session != null) {
|
||||
// Ask for the big half back before the shutdown handshake, so the peak
|
||||
// does not have to wait on isolate teardown.
|
||||
await session.release(decoder: true);
|
||||
await session.dispose();
|
||||
final release = () async {
|
||||
await session.release(decoder: true);
|
||||
await session.dispose();
|
||||
}();
|
||||
_pendingRelease = release;
|
||||
try {
|
||||
await release;
|
||||
} finally {
|
||||
if (identical(_pendingRelease, release)) _pendingRelease = null;
|
||||
}
|
||||
}
|
||||
appLogger.info('Image codec model evicted', tag: 'ImageCodec');
|
||||
_notify();
|
||||
|
||||
@@ -358,6 +358,19 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
|
||||
String get urlTemplate => _buildUrlTemplate(appSettingsService.settings);
|
||||
|
||||
/// Cache key for a tile URL: the URL without its `api_key`, so rotating the
|
||||
/// Stadia key does not orphan every offline tile.
|
||||
static String tileCacheKey(String url) {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null || !uri.queryParameters.containsKey('api_key')) return url;
|
||||
final params = Map<String, String>.of(uri.queryParameters)
|
||||
..remove('api_key');
|
||||
final stripped = params.isEmpty
|
||||
? uri.replace(query: '')
|
||||
: uri.replace(queryParameters: params);
|
||||
return stripped.toString().replaceFirst(RegExp(r'\?$'), '');
|
||||
}
|
||||
|
||||
TileBuilder? get tileBuilder => null;
|
||||
|
||||
static bool shouldApplyDarkFilterForSettings(
|
||||
@@ -614,7 +627,7 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
final pending = <Future<void>>[];
|
||||
Future<void> queueDownload(String url) async {
|
||||
final future = cacheManager
|
||||
.downloadFile(url, key: url, authHeaders: authHeaders)
|
||||
.downloadFile(url, key: tileCacheKey(url), authHeaders: authHeaders)
|
||||
.then((_) {
|
||||
completed += 1;
|
||||
})
|
||||
@@ -828,6 +841,7 @@ class CachedNetworkTileProvider extends TileProvider {
|
||||
final url = getTileUrl(coordinates, options);
|
||||
return CachedNetworkImageProvider(
|
||||
url,
|
||||
cacheKey: MapTileCacheService.tileCacheKey(url),
|
||||
cacheManager: cacheManager,
|
||||
headers: headers,
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../models/message.dart';
|
||||
import '../models/path_selection.dart';
|
||||
@@ -34,7 +35,7 @@ typedef AckHashMapping = ({
|
||||
});
|
||||
|
||||
class RetryServiceConfig {
|
||||
final void Function(Contact, String, int, int) sendMessage;
|
||||
final FutureOr<void> Function(Contact, String, int, int) sendMessage;
|
||||
final void Function(String, Message) addMessage;
|
||||
final void Function(Message) updateMessage;
|
||||
final Function(Contact)? clearContactPath;
|
||||
@@ -209,21 +210,46 @@ class MessageRetryService extends ChangeNotifier {
|
||||
final messageId = queue.removeAt(0);
|
||||
if (_pendingMessages.containsKey(messageId)) {
|
||||
_activeMessages.add(messageId);
|
||||
_attemptSend(messageId).catchError((e) {
|
||||
debugPrint('_attemptSend threw for $messageId: $e');
|
||||
final msg = _pendingMessages[messageId];
|
||||
if (msg != null) {
|
||||
final failed = msg.copyWith(status: MessageStatus.failed);
|
||||
_pendingMessages[messageId] = failed;
|
||||
_config?.updateMessage(failed);
|
||||
}
|
||||
_onMessageResolved(messageId, contactKey);
|
||||
});
|
||||
_attemptSendOrFail(messageId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _attemptSendOrFail(String messageId) {
|
||||
_attemptSend(messageId).catchError((Object e) {
|
||||
debugPrint('_attemptSend threw for $messageId: $e');
|
||||
_config?.debugLogService?.warn(
|
||||
'Send failed for message $messageId: $e',
|
||||
tag: 'AckHash',
|
||||
);
|
||||
_failMessage(messageId);
|
||||
});
|
||||
}
|
||||
|
||||
/// Marks a message that could not be handed to the radio as failed and
|
||||
/// releases its in-flight slot so the contact's queue keeps moving.
|
||||
void _failMessage(String messageId) {
|
||||
final message = _pendingMessages[messageId];
|
||||
if (message == null) return;
|
||||
_timeoutTimers[messageId]?.cancel();
|
||||
if (message.status != MessageStatus.failed &&
|
||||
message.status != MessageStatus.delivered) {
|
||||
_config?.updateMessage(message.copyWith(status: MessageStatus.failed));
|
||||
}
|
||||
_cleanupMessage(messageId);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Fails every pending and queued message. Call when the radio link drops:
|
||||
/// nothing in flight can be sent or acknowledged any more.
|
||||
void failAllPending() {
|
||||
_sendQueue.clear();
|
||||
for (final messageId in _pendingMessages.keys.toList()) {
|
||||
_failMessage(messageId);
|
||||
}
|
||||
}
|
||||
|
||||
void _onMessageResolved(String messageId, String contactKey) {
|
||||
if (_resolvedMessages.contains(messageId)) return;
|
||||
_resolvedMessages.add(messageId);
|
||||
@@ -358,6 +384,9 @@ class MessageRetryService extends ChangeNotifier {
|
||||
// Compute expected ACK hash that device will return in RESP_CODE_SENT
|
||||
// IMPORTANT: Use the transformed text (with SMAZ encoding if enabled) to match device's hash
|
||||
final selfPubKey = config.getSelfPublicKey?.call();
|
||||
if (config.getSelfPublicKey != null && selfPubKey == null) {
|
||||
throw StateError('Self public key unknown; cannot track ACK');
|
||||
}
|
||||
if (selfPubKey != null) {
|
||||
final outboundText =
|
||||
config.prepareContactOutboundText?.call(contact, message.text) ??
|
||||
@@ -380,7 +409,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
|
||||
config.sendMessage(contact, message.text, attempt, timestampSeconds);
|
||||
await config.sendMessage(contact, message.text, attempt, timestampSeconds);
|
||||
}
|
||||
|
||||
bool updateMessageFromSent(int ackHash, int timeoutMs) {
|
||||
@@ -535,7 +564,8 @@ class MessageRetryService extends ChangeNotifier {
|
||||
tag: 'AckHash',
|
||||
);
|
||||
|
||||
if (message.retryCount < maxRetries - 1) {
|
||||
if (message.retryCount < maxRetries - 1 &&
|
||||
_textFitsAttempt(message, contact, message.retryCount + 1)) {
|
||||
final backoffMs = 1000 * (1 << message.retryCount);
|
||||
|
||||
if (selection != null) {
|
||||
@@ -563,7 +593,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
|
||||
_timeoutTimers[messageId] = Timer(Duration(milliseconds: backoffMs), () {
|
||||
if (_pendingMessages.containsKey(messageId)) {
|
||||
_attemptSend(messageId);
|
||||
_attemptSendOrFail(messageId);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
@@ -598,6 +628,17 @@ class MessageRetryService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// From attempt 4 on the firmware appends [0][attempt] to the payload and
|
||||
/// rejects text longer than MAX_TEXT_LEN - 2 (BaseChatMesh::composeMsgPacket).
|
||||
bool _textFitsAttempt(Message message, Contact contact, int attempt) {
|
||||
if (attempt <= maxFullLengthTextAttempt) return true;
|
||||
final outboundText =
|
||||
_config?.prepareContactOutboundText?.call(contact, message.text) ??
|
||||
message.text;
|
||||
return utf8.encode(outboundText).length <=
|
||||
maxTextPayloadBytesAfterFullLengthAttempts;
|
||||
}
|
||||
|
||||
void _moveAckHashesToHistory(String messageId) {
|
||||
final ackHashes = _expectedAckHashes.remove(messageId);
|
||||
if (ackHashes != null && ackHashes.isNotEmpty) {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../l10n/app_localizations.dart';
|
||||
|
||||
/// Name under which the main isolate registers the port that receives
|
||||
/// notification actions from the plugin's background isolate.
|
||||
const notificationReplyPortName = 'meshcore.notification_reply';
|
||||
|
||||
const notificationReplyActionId = 'reply';
|
||||
const notificationMarkReadActionId = 'mark_read';
|
||||
const notificationMuteActionId = 'mute';
|
||||
|
||||
/// Preference holding the app's language code, so the background isolate can
|
||||
/// localize its notices the same way the app does.
|
||||
const notificationLanguagePrefsKey = 'notification_language';
|
||||
|
||||
enum NotificationReplyAction { reply, markRead, mute }
|
||||
|
||||
enum NotificationReplyFailure { notConnected, unavailable, tooLong, sendFailed }
|
||||
|
||||
/// A reply or mark-as-read action taken on a message notification, e.g. from
|
||||
/// the notification shade, a watch, or Android Auto.
|
||||
class NotificationReply {
|
||||
final NotificationReplyAction action;
|
||||
final String? contactKeyHex;
|
||||
final int? channelIndex;
|
||||
final String text;
|
||||
|
||||
const NotificationReply._({
|
||||
required this.action,
|
||||
this.contactKeyHex,
|
||||
this.channelIndex,
|
||||
this.text = '',
|
||||
});
|
||||
|
||||
bool get isChannel => channelIndex != null;
|
||||
|
||||
/// Parses the plugin's action id, notification payload (`message:<keyHex>`
|
||||
/// or `channel:<index>`) and reply input. Returns null for taps, unknown
|
||||
/// actions, malformed payloads, and empty replies.
|
||||
static NotificationReply? parse({
|
||||
required String? actionId,
|
||||
required String? payload,
|
||||
String? input,
|
||||
}) {
|
||||
final NotificationReplyAction action;
|
||||
if (actionId == notificationReplyActionId) {
|
||||
action = NotificationReplyAction.reply;
|
||||
} else if (actionId == notificationMarkReadActionId) {
|
||||
action = NotificationReplyAction.markRead;
|
||||
} else if (actionId == notificationMuteActionId) {
|
||||
action = NotificationReplyAction.mute;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
final text = input?.trim() ?? '';
|
||||
if (action == NotificationReplyAction.reply && text.isEmpty) return null;
|
||||
if (payload == null) return null;
|
||||
final sep = payload.indexOf(':');
|
||||
if (sep <= 0) return null;
|
||||
final kind = payload.substring(0, sep);
|
||||
final value = payload.substring(sep + 1);
|
||||
if (kind == 'message' &&
|
||||
value.isNotEmpty &&
|
||||
value != 'null' &&
|
||||
action != NotificationReplyAction.mute) {
|
||||
return NotificationReply._(
|
||||
action: action,
|
||||
contactKeyHex: value,
|
||||
text: text,
|
||||
);
|
||||
}
|
||||
if (kind == 'channel') {
|
||||
final index = int.tryParse(value);
|
||||
if (index == null) return null;
|
||||
return NotificationReply._(
|
||||
action: action,
|
||||
channelIndex: index,
|
||||
text: text,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits [text] at word boundaries into at most [maxParts] pieces that each
|
||||
/// satisfy [fits]. Words that are too long on their own are split by
|
||||
/// character. Returns null when the text needs more than [maxParts] pieces,
|
||||
/// or when a single character doesn't fit.
|
||||
List<String>? splitMessageToFit(
|
||||
String text,
|
||||
bool Function(String part) fits, {
|
||||
int maxParts = 3,
|
||||
}) {
|
||||
final trimmed = text.trim();
|
||||
if (trimmed.isEmpty) return const [];
|
||||
if (fits(trimmed)) return [trimmed];
|
||||
|
||||
final parts = <String>[];
|
||||
var current = '';
|
||||
for (final word in trimmed.split(RegExp(r'\s+'))) {
|
||||
final candidate = current.isEmpty ? word : '$current $word';
|
||||
if (fits(candidate)) {
|
||||
current = candidate;
|
||||
continue;
|
||||
}
|
||||
if (current.isNotEmpty) parts.add(current);
|
||||
if (fits(word)) {
|
||||
current = word;
|
||||
continue;
|
||||
}
|
||||
current = '';
|
||||
for (final char in word.characters) {
|
||||
final next = '$current$char';
|
||||
if (fits(next)) {
|
||||
current = next;
|
||||
} else {
|
||||
if (current.isEmpty || !fits(char)) return null;
|
||||
parts.add(current);
|
||||
current = char;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (current.isNotEmpty) parts.add(current);
|
||||
return parts.length <= maxParts ? parts : null;
|
||||
}
|
||||
|
||||
/// Runs in the plugin's background isolate when a notification action that
|
||||
/// doesn't open the app is used. Forwards it to the main isolate, which owns
|
||||
/// the radio connection; if the app isn't running, tells the user.
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> notificationActionBackgroundHandler(
|
||||
NotificationResponse response,
|
||||
) async {
|
||||
final port = IsolateNameServer.lookupPortByName(notificationReplyPortName);
|
||||
if (port != null) {
|
||||
port.send(<String, String?>{
|
||||
'actionId': response.actionId,
|
||||
'payload': response.payload,
|
||||
'input': response.input,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (response.actionId != notificationReplyActionId) return;
|
||||
try {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
DartPluginRegistrant.ensureInitialized();
|
||||
final plugin = FlutterLocalNotificationsPlugin();
|
||||
await plugin.initialize(
|
||||
settings: const InitializationSettings(
|
||||
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
|
||||
),
|
||||
);
|
||||
final l10n = await _backgroundLocalizations();
|
||||
await plugin.show(
|
||||
id: 'reply_failed'.hashCode,
|
||||
title: l10n.notification_replyFailedTitle,
|
||||
body: l10n.notification_replyAppNotRunning,
|
||||
notificationDetails: const NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
'messages',
|
||||
'Messages',
|
||||
channelDescription: 'New message notifications',
|
||||
importance: Importance.high,
|
||||
priority: Priority.high,
|
||||
icon: '@mipmap/ic_launcher',
|
||||
),
|
||||
),
|
||||
);
|
||||
if (response.id != null) await plugin.cancel(id: response.id!);
|
||||
} catch (e) {
|
||||
debugPrint('Failed to report unsent notification reply: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<AppLocalizations> _backgroundLocalizations() async {
|
||||
String? code;
|
||||
try {
|
||||
code = (await SharedPreferences.getInstance()).getString(
|
||||
notificationLanguagePrefsKey,
|
||||
);
|
||||
} catch (_) {}
|
||||
for (final locale in [
|
||||
if (code != null) Locale(code),
|
||||
PlatformDispatcher.instance.locale,
|
||||
]) {
|
||||
try {
|
||||
return lookupAppLocalizations(locale);
|
||||
} catch (_) {}
|
||||
}
|
||||
return lookupAppLocalizations(const Locale('en'));
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io' show Platform, File;
|
||||
import 'dart:isolate';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
@@ -8,7 +10,9 @@ import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
import '../helpers/message_url_image_helper.dart';
|
||||
import '../helpers/reaction_helper.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/platform_info.dart';
|
||||
import 'notification_reply.dart';
|
||||
|
||||
class NotificationService {
|
||||
static final NotificationService _instance = NotificationService._internal();
|
||||
@@ -25,10 +29,48 @@ class NotificationService {
|
||||
/// Set the locale for notification strings (call when app locale changes)
|
||||
void setLocale(Locale locale) {
|
||||
_locale = locale;
|
||||
// The background action isolate reads this to localize its notices.
|
||||
try {
|
||||
PrefsManager.instance.setString(
|
||||
notificationLanguagePrefsKey,
|
||||
locale.languageCode,
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
AppLocalizations get _l10n => lookupAppLocalizations(_locale);
|
||||
|
||||
String? _selfName;
|
||||
|
||||
/// Name of the connected radio, shown as the sender of your own replies.
|
||||
void setSelfName(String? name) {
|
||||
_selfName = name;
|
||||
}
|
||||
|
||||
// Recent messages per conversation notification id, so each notification
|
||||
// shows the conversation (Android MessagingStyle, used by Android Auto).
|
||||
static const _maxConversationMessages = 6;
|
||||
final Map<int, _Conversation> _conversations = {};
|
||||
|
||||
// Single-subscription so actions that arrive before the connector listens
|
||||
// (e.g. during startup) are buffered instead of dropped.
|
||||
final StreamController<NotificationReply> _replies =
|
||||
StreamController<NotificationReply>();
|
||||
ReceivePort? _replyPort;
|
||||
|
||||
/// Reply, mark-as-read and mute actions taken on message notifications.
|
||||
/// Has a single listener (the connector).
|
||||
Stream<NotificationReply> get replies => _replies.stream;
|
||||
|
||||
/// Stops receiving notification actions. The background handler then tells
|
||||
/// the user the app isn't running instead of forwarding to nobody.
|
||||
void releaseReplyPort() {
|
||||
if (_replyPort == null) return;
|
||||
IsolateNameServer.removePortNameMapping(notificationReplyPortName);
|
||||
_replyPort!.close();
|
||||
_replyPort = null;
|
||||
}
|
||||
|
||||
String _logSafe(String value) {
|
||||
final sanitized = value.replaceAll(RegExp(r'[\x00-\x1F\x7F]'), ' ');
|
||||
return Uri.encodeComponent(sanitized);
|
||||
@@ -98,13 +140,48 @@ class NotificationService {
|
||||
await _notifications.initialize(
|
||||
settings: initSettings,
|
||||
onDidReceiveNotificationResponse: _onNotificationTapped,
|
||||
onDidReceiveBackgroundNotificationResponse:
|
||||
notificationActionBackgroundHandler,
|
||||
);
|
||||
_registerReplyPort();
|
||||
_isInitialized = true;
|
||||
} catch (e) {
|
||||
debugPrint('Error initializing notifications: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void _registerReplyPort() {
|
||||
if (kIsWeb || _replyPort != null) return;
|
||||
final port = ReceivePort();
|
||||
IsolateNameServer.removePortNameMapping(notificationReplyPortName);
|
||||
IsolateNameServer.registerPortWithName(
|
||||
port.sendPort,
|
||||
notificationReplyPortName,
|
||||
);
|
||||
port.listen((dynamic message) {
|
||||
if (message is! Map) return;
|
||||
_dispatchAction(
|
||||
actionId: message['actionId'] as String?,
|
||||
payload: message['payload'] as String?,
|
||||
input: message['input'] as String?,
|
||||
);
|
||||
});
|
||||
_replyPort = port;
|
||||
}
|
||||
|
||||
void _dispatchAction({
|
||||
required String? actionId,
|
||||
required String? payload,
|
||||
String? input,
|
||||
}) {
|
||||
final reply = NotificationReply.parse(
|
||||
actionId: actionId,
|
||||
payload: payload,
|
||||
input: input,
|
||||
);
|
||||
if (reply != null) _replies.add(reply);
|
||||
}
|
||||
|
||||
static bool _isDbusSessionAvailable() {
|
||||
final addr = Platform.environment['DBUS_SESSION_BUS_ADDRESS'];
|
||||
if (addr != null && addr.isNotEmpty) return true;
|
||||
@@ -123,9 +200,11 @@ class NotificationService {
|
||||
|
||||
// Cached "are we allowed to post notifications" result. Null = not yet
|
||||
// determined. Avoids calling _notifications.show() when it would only throw
|
||||
// "You must request notifications permissions first" (every web build, and
|
||||
// Android 13+ before the user grants the permission).
|
||||
// "You must request notifications permissions first" (every web build).
|
||||
// Android denials are never cached so a later grant in system settings is
|
||||
// picked up without restarting the app.
|
||||
bool? _canNotify;
|
||||
static const _permissionRequestedKey = 'notification_permission_requested';
|
||||
|
||||
Future<bool> _ensureCanNotify() async {
|
||||
if (!await _ensureInitialized()) return false;
|
||||
@@ -143,8 +222,9 @@ class NotificationService {
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>();
|
||||
if (androidPlugin != null) {
|
||||
final enabled = await androidPlugin.areNotificationsEnabled();
|
||||
return _canNotify = enabled ?? false;
|
||||
final enabled = await androidPlugin.areNotificationsEnabled() ?? false;
|
||||
if (enabled) _canNotify = true;
|
||||
return enabled;
|
||||
}
|
||||
|
||||
// iOS/macOS request permission during initialize(); desktop has no gate.
|
||||
@@ -163,8 +243,8 @@ class NotificationService {
|
||||
>();
|
||||
if (androidPlugin != null) {
|
||||
final granted = await androidPlugin.requestNotificationsPermission();
|
||||
_canNotify = granted ?? false;
|
||||
return _canNotify!;
|
||||
if (granted == true) _canNotify = true;
|
||||
return granted ?? false;
|
||||
}
|
||||
|
||||
// iOS permissions are requested during initialization
|
||||
@@ -178,13 +258,25 @@ class NotificationService {
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
_canNotify = granted ?? false;
|
||||
return _canNotify!;
|
||||
if (granted == true) _canNotify = true;
|
||||
return granted ?? false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Asks for the Android 13+ notification permission the first time it is
|
||||
/// needed. Never re-prompts after the user has answered once; iOS/macOS
|
||||
/// already prompt during [initialize].
|
||||
Future<void> requestPermissionsOnce() async {
|
||||
if (!PlatformInfo.isAndroid || !await _ensureInitialized()) return;
|
||||
final prefs = PrefsManager.instance;
|
||||
if (prefs.getBool(_permissionRequestedKey) ?? false) return;
|
||||
if (await _ensureCanNotify()) return;
|
||||
await prefs.setBool(_permissionRequestedKey, true);
|
||||
await requestPermissions();
|
||||
}
|
||||
|
||||
/// Format special message types for human-readable notifications.
|
||||
static String formatNotificationText(String text) {
|
||||
final trimmed = text.trim();
|
||||
@@ -218,12 +310,85 @@ class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showMessageNotificationImpl({
|
||||
required String contactName,
|
||||
List<AndroidNotificationAction> _conversationActions(bool isChannel) => [
|
||||
AndroidNotificationAction(
|
||||
notificationReplyActionId,
|
||||
_l10n.notification_actionReply,
|
||||
inputs: [
|
||||
AndroidNotificationActionInput(label: _l10n.notification_replyHint),
|
||||
],
|
||||
semanticAction: SemanticAction.reply,
|
||||
allowGeneratedReplies: true,
|
||||
cancelNotification: false,
|
||||
),
|
||||
AndroidNotificationAction(
|
||||
notificationMarkReadActionId,
|
||||
_l10n.notification_actionMarkRead,
|
||||
semanticAction: SemanticAction.markAsRead,
|
||||
invisible: true,
|
||||
),
|
||||
if (isChannel)
|
||||
AndroidNotificationAction(
|
||||
notificationMuteActionId,
|
||||
_l10n.notification_actionMuteChannel,
|
||||
semanticAction: SemanticAction.mute,
|
||||
),
|
||||
];
|
||||
|
||||
// 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;
|
||||
return AndroidNotificationDetails(
|
||||
conversation.isChannel ? 'channel_messages' : 'messages',
|
||||
conversation.isChannel ? 'Channel Messages' : 'Messages',
|
||||
channelDescription: conversation.isChannel
|
||||
? 'New channel message notifications'
|
||||
: 'New message notifications',
|
||||
importance: Importance.high,
|
||||
priority: Priority.high,
|
||||
icon: '@mipmap/ic_launcher',
|
||||
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),
|
||||
),
|
||||
actions: _conversationActions(conversation.isChannel),
|
||||
);
|
||||
}
|
||||
|
||||
DarwinNotificationDetails _darwinDetails(String? imagePath, int? badge) =>
|
||||
DarwinNotificationDetails(
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
badgeNumber: badge,
|
||||
attachments: imagePath != null
|
||||
? <DarwinNotificationAttachment>[
|
||||
DarwinNotificationAttachment(imagePath),
|
||||
]
|
||||
: null,
|
||||
);
|
||||
|
||||
Future<void> _showConversationNotificationImpl({
|
||||
required int id,
|
||||
required String payload,
|
||||
required String title,
|
||||
required bool isChannel,
|
||||
required String message,
|
||||
required bool urlImagesEnabled,
|
||||
String? contactId,
|
||||
String? senderName,
|
||||
int? badgeCount,
|
||||
bool silent = false,
|
||||
}) async {
|
||||
if (!await _ensureCanNotify()) return;
|
||||
|
||||
@@ -231,66 +396,158 @@ class NotificationService {
|
||||
message,
|
||||
urlImagesEnabled: urlImagesEnabled,
|
||||
);
|
||||
final preview = formatNotificationText(message.trim());
|
||||
final body = preview.isEmpty
|
||||
? _l10n.notification_receivedNewMessage
|
||||
: preview;
|
||||
|
||||
final androidDetails = AndroidNotificationDetails(
|
||||
'messages',
|
||||
'Messages',
|
||||
channelDescription: 'New message notifications',
|
||||
importance: Importance.high,
|
||||
priority: Priority.high,
|
||||
icon: '@mipmap/ic_launcher',
|
||||
number: badgeCount,
|
||||
styleInformation: imagePath != null
|
||||
? BigPictureStyleInformation(
|
||||
FilePathAndroidBitmap(imagePath),
|
||||
summaryText: formatNotificationText(message),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
|
||||
final iosDetails = DarwinNotificationDetails(
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
badgeNumber: badgeCount,
|
||||
attachments: imagePath != null
|
||||
? <DarwinNotificationAttachment>[
|
||||
DarwinNotificationAttachment(imagePath),
|
||||
]
|
||||
: null,
|
||||
);
|
||||
|
||||
final macDetails = DarwinNotificationDetails(
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
badgeNumber: badgeCount,
|
||||
attachments: imagePath != null
|
||||
? <DarwinNotificationAttachment>[
|
||||
DarwinNotificationAttachment(imagePath),
|
||||
]
|
||||
: null,
|
||||
final conversation =
|
||||
_conversations.putIfAbsent(
|
||||
id,
|
||||
() => _Conversation(
|
||||
title: title,
|
||||
payload: payload,
|
||||
isChannel: isChannel,
|
||||
),
|
||||
)
|
||||
..title = title
|
||||
..badgeCount = badgeCount
|
||||
..imagePath = imagePath;
|
||||
final sender = isChannel ? (senderName ?? title) : title;
|
||||
conversation.add(
|
||||
Message(
|
||||
body,
|
||||
DateTime.now(),
|
||||
Person(key: isChannel ? 'sender:$sender' : payload, name: sender),
|
||||
),
|
||||
_maxConversationMessages,
|
||||
);
|
||||
|
||||
final notificationDetails = NotificationDetails(
|
||||
android: androidDetails,
|
||||
iOS: iosDetails,
|
||||
macOS: macDetails,
|
||||
android: _androidConversationDetails(
|
||||
conversation,
|
||||
badgeCount: badgeCount,
|
||||
silent: silent,
|
||||
),
|
||||
iOS: _darwinDetails(imagePath, badgeCount),
|
||||
macOS: _darwinDetails(imagePath, badgeCount),
|
||||
);
|
||||
|
||||
try {
|
||||
await _notifications.show(
|
||||
id: contactId?.hashCode ?? 0,
|
||||
title: contactName,
|
||||
body: formatNotificationText(message),
|
||||
id: id,
|
||||
title: title,
|
||||
body: _collapsedBody(conversation),
|
||||
notificationDetails: notificationDetails,
|
||||
payload: 'message:$contactId',
|
||||
payload: payload,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('Failed to show message notification: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Text shown when the notification is collapsed. Channel messages keep
|
||||
/// the sender prefix, including after your own reply.
|
||||
String _collapsedBody(_Conversation conversation) {
|
||||
final last = conversation.messages.last;
|
||||
if (!conversation.isChannel) return last.text;
|
||||
final sender = last.person?.name ?? _selfName ?? _l10n.notification_you;
|
||||
return '$sender: ${last.text}';
|
||||
}
|
||||
|
||||
int _conversationId(NotificationReply reply) => reply.isChannel
|
||||
? reply.channelIndex!.hashCode
|
||||
: reply.contactKeyHex!.hashCode;
|
||||
|
||||
/// Adds the user's reply to the conversation notification. Android keeps
|
||||
/// showing a progress spinner on a replied notification until it is updated.
|
||||
/// Pass the current [badgeCount]: an update replaces the whole notification,
|
||||
/// and the Android launcher badge comes from the notification number.
|
||||
Future<void> showOwnReply(
|
||||
NotificationReply reply,
|
||||
String text, {
|
||||
int? badgeCount,
|
||||
}) async {
|
||||
if (!await _ensureInitialized()) return;
|
||||
final id = _conversationId(reply);
|
||||
final conversation = _conversations[id];
|
||||
if (conversation == null) {
|
||||
await _notifications.cancel(id: id);
|
||||
return;
|
||||
}
|
||||
conversation.badgeCount = badgeCount ?? conversation.badgeCount;
|
||||
conversation.add(
|
||||
Message(text, DateTime.now(), null),
|
||||
_maxConversationMessages,
|
||||
);
|
||||
await _repostConversation(id, conversation);
|
||||
}
|
||||
|
||||
/// Tells the user a notification reply could not be sent.
|
||||
Future<void> showReplyFailed(
|
||||
NotificationReply reply,
|
||||
NotificationReplyFailure failure, {
|
||||
int? badgeCount,
|
||||
}) async {
|
||||
if (!await _ensureInitialized()) return;
|
||||
final reason = switch (failure) {
|
||||
NotificationReplyFailure.notConnected =>
|
||||
_l10n.notification_replyNotConnected,
|
||||
NotificationReplyFailure.unavailable =>
|
||||
_l10n.notification_replyUnavailable,
|
||||
NotificationReplyFailure.tooLong => _l10n.notification_replyTooLong,
|
||||
NotificationReplyFailure.sendFailed => _l10n.notification_replySendFailed,
|
||||
};
|
||||
final id = _conversationId(reply);
|
||||
final conversation = _conversations[id];
|
||||
if (conversation != null) {
|
||||
conversation.badgeCount = badgeCount ?? conversation.badgeCount;
|
||||
await _repostConversation(id, conversation);
|
||||
} else {
|
||||
await _notifications.cancel(id: id);
|
||||
}
|
||||
try {
|
||||
await _notifications.show(
|
||||
id: 'reply_failed:$id'.hashCode,
|
||||
title: _l10n.notification_replyFailedTitle,
|
||||
body: reason,
|
||||
notificationDetails: const NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
'messages',
|
||||
'Messages',
|
||||
channelDescription: 'New message notifications',
|
||||
importance: Importance.high,
|
||||
priority: Priority.high,
|
||||
icon: '@mipmap/ic_launcher',
|
||||
),
|
||||
),
|
||||
payload: conversation?.payload,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('Failed to show reply failure notification: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _repostConversation(int id, _Conversation conversation) async {
|
||||
try {
|
||||
await _notifications.show(
|
||||
id: id,
|
||||
title: conversation.title,
|
||||
body: _collapsedBody(conversation),
|
||||
notificationDetails: NotificationDetails(
|
||||
android: _androidConversationDetails(
|
||||
conversation,
|
||||
badgeCount: conversation.badgeCount,
|
||||
silent: true,
|
||||
),
|
||||
),
|
||||
payload: conversation.payload,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('Failed to update message notification: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showAdvertNotificationImpl({
|
||||
required String contactName,
|
||||
required String contactType,
|
||||
@@ -340,86 +597,6 @@ class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showChannelMessageNotificationImpl({
|
||||
required String channelName,
|
||||
required String message,
|
||||
required bool urlImagesEnabled,
|
||||
int? channelIndex,
|
||||
int? badgeCount,
|
||||
}) async {
|
||||
if (!await _ensureCanNotify()) return;
|
||||
|
||||
final imagePath = await _resolveNotificationImagePath(
|
||||
message,
|
||||
urlImagesEnabled: urlImagesEnabled,
|
||||
);
|
||||
|
||||
final androidDetails = AndroidNotificationDetails(
|
||||
'channel_messages',
|
||||
'Channel Messages',
|
||||
channelDescription: 'New channel message notifications',
|
||||
importance: Importance.high,
|
||||
priority: Priority.high,
|
||||
icon: '@mipmap/ic_launcher',
|
||||
number: badgeCount,
|
||||
styleInformation: imagePath != null
|
||||
? BigPictureStyleInformation(
|
||||
FilePathAndroidBitmap(imagePath),
|
||||
summaryText: formatNotificationText(message),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
|
||||
final iosDetails = DarwinNotificationDetails(
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
badgeNumber: badgeCount,
|
||||
attachments: imagePath != null
|
||||
? <DarwinNotificationAttachment>[
|
||||
DarwinNotificationAttachment(imagePath),
|
||||
]
|
||||
: null,
|
||||
);
|
||||
|
||||
final macDetails = DarwinNotificationDetails(
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
badgeNumber: badgeCount,
|
||||
attachments: imagePath != null
|
||||
? <DarwinNotificationAttachment>[
|
||||
DarwinNotificationAttachment(imagePath),
|
||||
]
|
||||
: null,
|
||||
);
|
||||
|
||||
final notificationDetails = NotificationDetails(
|
||||
android: androidDetails,
|
||||
iOS: iosDetails,
|
||||
macOS: macDetails,
|
||||
);
|
||||
|
||||
final preview = formatNotificationText(message.trim());
|
||||
final body = preview.isEmpty
|
||||
? _l10n.notification_receivedNewMessage
|
||||
: preview;
|
||||
|
||||
try {
|
||||
await _notifications.show(
|
||||
id:
|
||||
channelIndex?.hashCode ??
|
||||
DateTime.now().millisecondsSinceEpoch & 0x7FFFFFFF,
|
||||
title: channelName,
|
||||
body: body,
|
||||
notificationDetails: notificationDetails,
|
||||
payload: 'channel:$channelIndex',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('Failed to show channel notification: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a privacy-safe identifier for debug logging.
|
||||
/// - advert: shows device name (body contains contactName)
|
||||
/// - message: shows "from: sender" (avoids logging message content)
|
||||
@@ -445,6 +622,7 @@ class NotificationService {
|
||||
}
|
||||
|
||||
Future<void> cancelAll() async {
|
||||
_conversations.clear();
|
||||
await _notifications.cancelAll();
|
||||
}
|
||||
|
||||
@@ -458,6 +636,7 @@ class NotificationService {
|
||||
int totalUnreadCount,
|
||||
) async {
|
||||
if (!await _ensureInitialized()) return;
|
||||
_conversations.remove(contactId.hashCode);
|
||||
await _notifications.cancel(id: contactId.hashCode);
|
||||
await _updateBadge(totalUnreadCount);
|
||||
}
|
||||
@@ -468,6 +647,7 @@ class NotificationService {
|
||||
int totalUnreadCount,
|
||||
) async {
|
||||
if (!await _ensureInitialized()) return;
|
||||
_conversations.remove(channelIndex.hashCode);
|
||||
await _notifications.cancel(id: channelIndex.hashCode);
|
||||
await _updateBadge(totalUnreadCount);
|
||||
}
|
||||
@@ -563,7 +743,8 @@ class NotificationService {
|
||||
_PendingNotification(
|
||||
type: _NotificationType.channelMessage,
|
||||
title: channelName,
|
||||
body: '$senderName: $message',
|
||||
body: message,
|
||||
senderName: senderName,
|
||||
urlImagesEnabled: urlImagesEnabled,
|
||||
id: channelIndex?.toString(),
|
||||
badgeCount: badgeCount,
|
||||
@@ -573,10 +754,20 @@ class NotificationService {
|
||||
|
||||
void _queueNotification(_PendingNotification notification) {
|
||||
final now = DateTime.now();
|
||||
final throttled =
|
||||
_lastNotificationTime != null &&
|
||||
now.difference(_lastNotificationTime!) < _minNotificationInterval;
|
||||
|
||||
// Messages always update their conversation notification so the reply
|
||||
// action stays available; during a burst they update silently.
|
||||
if (notification.type != _NotificationType.advert) {
|
||||
_showNotificationImmediately(notification, silent: throttled);
|
||||
if (!throttled) _lastNotificationTime = now;
|
||||
return;
|
||||
}
|
||||
|
||||
// If we recently showed a notification, start batching
|
||||
if (_lastNotificationTime != null &&
|
||||
now.difference(_lastNotificationTime!) < _minNotificationInterval) {
|
||||
if (throttled) {
|
||||
_pendingNotifications.add(notification);
|
||||
debugPrint(
|
||||
'[Notification] queued: ${notification.type.name} (${_getNotificationIdentifier(notification)})',
|
||||
@@ -618,17 +809,21 @@ class NotificationService {
|
||||
}
|
||||
|
||||
Future<void> _showNotificationImmediately(
|
||||
_PendingNotification notification,
|
||||
) async {
|
||||
_PendingNotification notification, {
|
||||
bool silent = false,
|
||||
}) async {
|
||||
try {
|
||||
switch (notification.type) {
|
||||
case _NotificationType.message:
|
||||
await _showMessageNotificationImpl(
|
||||
contactName: notification.title,
|
||||
await _showConversationNotificationImpl(
|
||||
id: notification.id?.hashCode ?? 0,
|
||||
payload: 'message:${notification.id}',
|
||||
title: notification.title,
|
||||
isChannel: false,
|
||||
message: notification.body,
|
||||
urlImagesEnabled: notification.urlImagesEnabled,
|
||||
contactId: notification.id,
|
||||
badgeCount: notification.badgeCount,
|
||||
silent: silent,
|
||||
);
|
||||
break;
|
||||
case _NotificationType.advert:
|
||||
@@ -639,12 +834,19 @@ class NotificationService {
|
||||
);
|
||||
break;
|
||||
case _NotificationType.channelMessage:
|
||||
await _showChannelMessageNotificationImpl(
|
||||
channelName: notification.title,
|
||||
final channelIndex = int.tryParse(notification.id ?? '');
|
||||
await _showConversationNotificationImpl(
|
||||
id:
|
||||
channelIndex?.hashCode ??
|
||||
DateTime.now().millisecondsSinceEpoch & 0x7FFFFFFF,
|
||||
payload: 'channel:$channelIndex',
|
||||
title: notification.title,
|
||||
isChannel: true,
|
||||
message: notification.body,
|
||||
senderName: notification.senderName,
|
||||
urlImagesEnabled: notification.urlImagesEnabled,
|
||||
channelIndex: int.tryParse(notification.id ?? ''),
|
||||
badgeCount: notification.badgeCount,
|
||||
silent: silent,
|
||||
);
|
||||
break;
|
||||
}
|
||||
@@ -653,39 +855,15 @@ class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showBatchSummary(List<_PendingNotification> batch) async {
|
||||
if (!await _ensureCanNotify()) return;
|
||||
/// Only adverts are batched; messages always update their conversation
|
||||
/// notification instead.
|
||||
Future<void> _showBatchSummary(List<_PendingNotification> adverts) async {
|
||||
if (adverts.isEmpty || !await _ensureCanNotify()) return;
|
||||
|
||||
// Group by type
|
||||
final messages = batch
|
||||
.where((n) => n.type == _NotificationType.message)
|
||||
.toList();
|
||||
final adverts = batch
|
||||
.where((n) => n.type == _NotificationType.advert)
|
||||
.toList();
|
||||
final channelMsgs = batch
|
||||
.where((n) => n.type == _NotificationType.channelMessage)
|
||||
.toList();
|
||||
|
||||
// Build summary text using localized plurals
|
||||
final parts = <String>[];
|
||||
if (messages.isNotEmpty) {
|
||||
parts.add(_l10n.notification_messagesCount(messages.length));
|
||||
}
|
||||
if (channelMsgs.isNotEmpty) {
|
||||
parts.add(_l10n.notification_channelMessagesCount(channelMsgs.length));
|
||||
}
|
||||
if (adverts.isNotEmpty) {
|
||||
parts.add(_l10n.notification_newNodesCount(adverts.length));
|
||||
}
|
||||
|
||||
if (parts.isEmpty) return;
|
||||
|
||||
// Show first few device names in batch summary for debugging (only if adverts exist)
|
||||
final deviceInfo = adverts.isNotEmpty
|
||||
? ' (${adverts.take(5).map((n) => _logSafe(n.body)).join(', ')}${adverts.length > 5 ? ', ...' : ''})'
|
||||
: '';
|
||||
debugPrint('[Notification] batch summary: ${parts.join(", ")}$deviceInfo');
|
||||
final summary = _l10n.notification_newNodesCount(adverts.length);
|
||||
final deviceInfo =
|
||||
' (${adverts.take(5).map((n) => _logSafe(n.body)).join(', ')}${adverts.length > 5 ? ', ...' : ''})';
|
||||
debugPrint('[Notification] batch summary: $summary$deviceInfo');
|
||||
|
||||
const androidDetails = AndroidNotificationDetails(
|
||||
'batch_summary',
|
||||
@@ -702,7 +880,7 @@ class NotificationService {
|
||||
await _notifications.show(
|
||||
id: 'batch_summary'.hashCode,
|
||||
title: _l10n.notification_activityTitle,
|
||||
body: parts.join(', '),
|
||||
body: summary,
|
||||
notificationDetails: notificationDetails,
|
||||
payload: 'batch',
|
||||
);
|
||||
@@ -719,6 +897,7 @@ class _PendingNotification {
|
||||
final _NotificationType type;
|
||||
final String title;
|
||||
final String body;
|
||||
final String? senderName;
|
||||
final bool urlImagesEnabled;
|
||||
final String? id;
|
||||
final int? badgeCount;
|
||||
@@ -727,8 +906,29 @@ class _PendingNotification {
|
||||
required this.type,
|
||||
required this.title,
|
||||
required this.body,
|
||||
this.senderName,
|
||||
this.urlImagesEnabled = false,
|
||||
this.id,
|
||||
this.badgeCount,
|
||||
});
|
||||
}
|
||||
|
||||
class _Conversation {
|
||||
String title;
|
||||
int? badgeCount;
|
||||
String? imagePath;
|
||||
final String payload;
|
||||
final bool isChannel;
|
||||
final List<Message> messages = [];
|
||||
|
||||
_Conversation({
|
||||
required this.title,
|
||||
required this.payload,
|
||||
required this.isChannel,
|
||||
});
|
||||
|
||||
void add(Message message, int max) {
|
||||
messages.add(message);
|
||||
if (messages.length > max) messages.removeRange(0, messages.length - max);
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
final Map<String, ContactPathHistory> _cache = {};
|
||||
final Map<String, int> _autoRotationIndex = {};
|
||||
final Map<String, _FloodStats> _floodStats = {};
|
||||
final Set<String> _pendingLoads = {};
|
||||
final Map<String, List<_DeferredPathRecord>> _deferredRecords = {};
|
||||
final Map<String, Future<void>> _pendingLoads = {};
|
||||
|
||||
// LRU cache eviction tracking
|
||||
static const int _maxCachedContacts = 50;
|
||||
@@ -23,6 +22,16 @@ class PathHistoryService extends ChangeNotifier {
|
||||
|
||||
PathHistoryService(this._storage);
|
||||
|
||||
void setDevicePublicKey(String publicKeyHex) {
|
||||
_storage.setPublicKeyHex = publicKeyHex;
|
||||
_cache.clear();
|
||||
_cacheAccessOrder.clear();
|
||||
_autoRotationIndex.clear();
|
||||
_floodStats.clear();
|
||||
_version++;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> initialize() async {
|
||||
// Load cached path histories on startup if needed
|
||||
}
|
||||
@@ -40,7 +49,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
pathBytes: contact.path,
|
||||
successCount: 0,
|
||||
failureCount: 0,
|
||||
routeWeight: initialWeight,
|
||||
initialWeight: initialWeight,
|
||||
timestamp: null,
|
||||
);
|
||||
}
|
||||
@@ -74,6 +83,20 @@ class PathHistoryService extends ChangeNotifier {
|
||||
double maxWeight = 5.0,
|
||||
}) {
|
||||
if (pathBytes.isEmpty || hopCount < 0) return;
|
||||
if (!_cache.containsKey(contactPubKeyHex)) {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
if (!_cache.containsKey(contactPubKeyHex)) return;
|
||||
recordFloodPathAttribution(
|
||||
contactPubKeyHex: contactPubKeyHex,
|
||||
pathBytes: pathBytes,
|
||||
hopCount: hopCount,
|
||||
tripTimeMs: tripTimeMs,
|
||||
successIncrement: successIncrement,
|
||||
maxWeight: maxWeight,
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final existing = _findPathRecord(contactPubKeyHex, pathBytes);
|
||||
final successCount = (existing?.successCount ?? 0) + 1;
|
||||
@@ -124,6 +147,22 @@ class PathHistoryService extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_cache.containsKey(contactPubKeyHex)) {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
if (!_cache.containsKey(contactPubKeyHex)) return;
|
||||
recordPathResult(
|
||||
contactPubKeyHex,
|
||||
selection,
|
||||
success: success,
|
||||
tripTimeMs: tripTimeMs,
|
||||
successIncrement: successIncrement,
|
||||
failureDecrement: failureDecrement,
|
||||
maxWeight: maxWeight,
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final existing = _findPathRecord(contactPubKeyHex, selection.pathBytes);
|
||||
final successCount = (existing?.successCount ?? 0) + (success ? 1 : 0);
|
||||
final failureCount = (existing?.failureCount ?? 0) + (success ? 0 : 1);
|
||||
@@ -222,73 +261,11 @@ class PathHistoryService extends ChangeNotifier {
|
||||
required List<int> pathBytes,
|
||||
required int successCount,
|
||||
required int failureCount,
|
||||
double routeWeight = 1.0,
|
||||
double? routeWeight,
|
||||
double initialWeight = 1.0,
|
||||
DateTime? timestamp,
|
||||
}) {
|
||||
var history = _cache[contactPubKeyHex];
|
||||
|
||||
if (history == null) {
|
||||
// If a load is already in progress, defer this record
|
||||
if (_pendingLoads.contains(contactPubKeyHex)) {
|
||||
_deferredRecords.putIfAbsent(contactPubKeyHex, () => []);
|
||||
_deferredRecords[contactPubKeyHex]!.add(
|
||||
_DeferredPathRecord(
|
||||
hopCount: hopCount,
|
||||
tripTimeMs: tripTimeMs,
|
||||
wasFloodDiscovery: wasFloodDiscovery,
|
||||
pathBytes: pathBytes,
|
||||
successCount: successCount,
|
||||
failureCount: failureCount,
|
||||
routeWeight: routeWeight,
|
||||
timestamp: timestamp,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
_pendingLoads.add(contactPubKeyHex);
|
||||
_loadHistoryFromStorage(contactPubKeyHex).then((loaded) {
|
||||
_cache[contactPubKeyHex] =
|
||||
loaded ??
|
||||
ContactPathHistory(
|
||||
contactPubKeyHex: contactPubKeyHex,
|
||||
recentPaths: [],
|
||||
);
|
||||
_addPathRecordInternal(
|
||||
contactPubKeyHex,
|
||||
hopCount,
|
||||
tripTimeMs,
|
||||
wasFloodDiscovery,
|
||||
pathBytes,
|
||||
successCount,
|
||||
failureCount,
|
||||
routeWeight,
|
||||
timestamp,
|
||||
);
|
||||
|
||||
// Apply any deferred records
|
||||
final deferred = _deferredRecords.remove(contactPubKeyHex);
|
||||
if (deferred != null) {
|
||||
for (final record in deferred) {
|
||||
_addPathRecordInternal(
|
||||
contactPubKeyHex,
|
||||
record.hopCount,
|
||||
record.tripTimeMs,
|
||||
record.wasFloodDiscovery,
|
||||
record.pathBytes,
|
||||
record.successCount,
|
||||
record.failureCount,
|
||||
record.routeWeight,
|
||||
record.timestamp,
|
||||
);
|
||||
}
|
||||
}
|
||||
_pendingLoads.remove(contactPubKeyHex);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
_addPathRecordInternal(
|
||||
void add() => _addPathRecordInternal(
|
||||
contactPubKeyHex,
|
||||
hopCount,
|
||||
tripTimeMs,
|
||||
@@ -297,8 +274,34 @@ class PathHistoryService extends ChangeNotifier {
|
||||
successCount,
|
||||
failureCount,
|
||||
routeWeight,
|
||||
initialWeight,
|
||||
timestamp,
|
||||
);
|
||||
|
||||
if (_cache.containsKey(contactPubKeyHex)) {
|
||||
add();
|
||||
} else {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) => 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);
|
||||
});
|
||||
}
|
||||
|
||||
void _addPathRecordInternal(
|
||||
@@ -309,7 +312,8 @@ class PathHistoryService extends ChangeNotifier {
|
||||
List<int> pathBytes,
|
||||
int successCount,
|
||||
int failureCount,
|
||||
double routeWeight,
|
||||
double? routeWeight,
|
||||
double initialWeight,
|
||||
DateTime? timestamp,
|
||||
) {
|
||||
var history = _cache[contactPubKeyHex];
|
||||
@@ -326,6 +330,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
wasFloodDiscovery = existing.wasFloodDiscovery || wasFloodDiscovery;
|
||||
timestamp ??= existing.timestamp;
|
||||
}
|
||||
routeWeight ??= existing?.routeWeight ?? initialWeight;
|
||||
|
||||
final newRecord = PathRecord(
|
||||
hopCount: hopCount,
|
||||
@@ -361,6 +366,24 @@ class PathHistoryService extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Whether this contact's history is in the in-memory cache.
|
||||
bool isCached(String contactPubKeyHex) =>
|
||||
_cache.containsKey(contactPubKeyHex);
|
||||
|
||||
/// Paths already in memory, without loading from storage or changing the
|
||||
/// cache order. For bulk readers that must not churn the 50-contact cache.
|
||||
List<PathRecord> peekRecentPaths(String contactPubKeyHex) =>
|
||||
_cache[contactPubKeyHex]?.recentPaths ?? const [];
|
||||
|
||||
/// Reads saved paths straight from storage without adding them to the
|
||||
/// cache, evicting anything, or notifying listeners.
|
||||
Future<List<PathRecord>> readStoredPaths(String contactPubKeyHex) async {
|
||||
final cached = _cache[contactPubKeyHex];
|
||||
if (cached != null) return cached.recentPaths;
|
||||
final stored = await _loadHistoryFromStorage(contactPubKeyHex);
|
||||
return stored?.recentPaths ?? const [];
|
||||
}
|
||||
|
||||
List<PathRecord> getRecentPaths(String contactPubKeyHex) {
|
||||
final history = _cache[contactPubKeyHex];
|
||||
if (history != null) {
|
||||
@@ -368,11 +391,8 @@ class PathHistoryService extends ChangeNotifier {
|
||||
return history.recentPaths;
|
||||
}
|
||||
|
||||
_loadHistoryFromStorage(contactPubKeyHex).then((loaded) {
|
||||
if (loaded != null) {
|
||||
_cache[contactPubKeyHex] = loaded;
|
||||
_trackAccess(contactPubKeyHex);
|
||||
_evictIfNeeded();
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
if (_cache[contactPubKeyHex]?.recentPaths.isNotEmpty ?? false) {
|
||||
_version++;
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -579,28 +599,6 @@ class PathHistoryService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
class _DeferredPathRecord {
|
||||
final int hopCount;
|
||||
final int tripTimeMs;
|
||||
final bool wasFloodDiscovery;
|
||||
final List<int> pathBytes;
|
||||
final int successCount;
|
||||
final int failureCount;
|
||||
final double routeWeight;
|
||||
final DateTime? timestamp;
|
||||
|
||||
_DeferredPathRecord({
|
||||
required this.hopCount,
|
||||
required this.tripTimeMs,
|
||||
required this.wasFloodDiscovery,
|
||||
required this.pathBytes,
|
||||
required this.successCount,
|
||||
required this.failureCount,
|
||||
this.routeWeight = 1.0,
|
||||
this.timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
class _FloodStats {
|
||||
int successCount = 0;
|
||||
int failureCount = 0;
|
||||
|
||||
@@ -66,6 +66,10 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
String? _dirPath;
|
||||
Future<String>? _pending;
|
||||
|
||||
/// Last queued sidecar operation per id. Writes share one `.tmp` path, so
|
||||
/// two in flight for the same id would interleave; each waits for the last.
|
||||
final Map<String, Future<void>> _sidecarOps = <String, Future<void>>{};
|
||||
|
||||
FileReceivedImageBlobStore({
|
||||
Future<Directory> Function()? baseDirectory,
|
||||
this.directoryName = 'received_images',
|
||||
@@ -190,7 +194,19 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
/// atomic within a directory on every platform we ship, so a reader either
|
||||
/// sees the old record or the new one.
|
||||
@override
|
||||
Future<void> writeSidecar(String streamId, String json) async {
|
||||
Future<void> writeSidecar(String streamId, String json) =>
|
||||
_serializeSidecar(streamId, () => _writeSidecarNow(streamId, json));
|
||||
|
||||
Future<void> _serializeSidecar(String streamId, Future<void> Function() op) {
|
||||
final previous = _sidecarOps[streamId] ?? Future<void>.value();
|
||||
final next = previous.then((_) => op());
|
||||
_sidecarOps[streamId] = next;
|
||||
return next.whenComplete(() {
|
||||
if (identical(_sidecarOps[streamId], next)) _sidecarOps.remove(streamId);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _writeSidecarNow(String streamId, String json) async {
|
||||
try {
|
||||
final finalPath = await _pathFor(streamId, _sidecarExt);
|
||||
final tmpPath = await _pathFor(streamId, _tmpExt);
|
||||
@@ -207,10 +223,11 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> deleteSidecar(String streamId) async {
|
||||
await _delete(streamId, _sidecarExt);
|
||||
await _delete(streamId, _tmpExt);
|
||||
}
|
||||
Future<void> deleteSidecar(String streamId) =>
|
||||
_serializeSidecar(streamId, () async {
|
||||
await _delete(streamId, _sidecarExt);
|
||||
await _delete(streamId, _tmpExt);
|
||||
});
|
||||
|
||||
/// Startup scan. Also the only place orphaned bytes are reaped: anything
|
||||
/// whose sidecar is gone is invisible to the store and therefore to the
|
||||
|
||||
@@ -595,6 +595,10 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// True when the queue stopped because the codec was busy encoding. Cleared
|
||||
/// by anything that could plausibly have freed it.
|
||||
bool _parkedOnBusyDecoder = false;
|
||||
|
||||
/// Set by [handleMemoryPressure] so the decode it cancels is parked rather
|
||||
/// than reported as corrupt.
|
||||
bool _cancelRequested = false;
|
||||
bool _foreground = true;
|
||||
bool _disposed = false;
|
||||
|
||||
@@ -775,10 +779,13 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
// `conflicting` means the reassembler threw the old stream away and
|
||||
// restarted from this chunk. A stream that had already been surfaced
|
||||
// keeps its id (and therefore its message) only if it was still
|
||||
// receiving; anything else gets a fresh entry.
|
||||
// receiving; anything else gets a fresh entry. The same goes for a
|
||||
// plain `accepted`: once an entry is past `receiving` the reassembler
|
||||
// reports its stragglers as `duplicate`, so an accepted chunk on that
|
||||
// key is a new image reusing the 8-bit id and must not overwrite it.
|
||||
final resets = outcome.status == ImageChunkStatus.conflicting;
|
||||
if (existing != null &&
|
||||
(!resets || existing.state == ReceivedImageState.receiving)) {
|
||||
existing.state == ReceivedImageState.receiving) {
|
||||
final updated = existing.copyWith(
|
||||
state: ReceivedImageState.receiving,
|
||||
receivedChunks: resets
|
||||
@@ -824,7 +831,9 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
channelIndex: channelIndex,
|
||||
),
|
||||
);
|
||||
if (entry == null) return null;
|
||||
if (entry == null || entry.state != ReceivedImageState.receiving) {
|
||||
return null;
|
||||
}
|
||||
_queue.remove(entry.streamId);
|
||||
return _store(
|
||||
entry.copyWith(
|
||||
@@ -847,7 +856,9 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
) async {
|
||||
final key = result.key;
|
||||
var entry = entryForKey(key);
|
||||
if (entry == null) {
|
||||
// A one-chunk image completes without an `accepted` first, so the key may
|
||||
// still point at an older, finished image that reused the id.
|
||||
if (entry == null || entry.state != ReceivedImageState.receiving) {
|
||||
final streamId = _uniqueStreamId(
|
||||
senderPrefix: key.senderPrefix,
|
||||
imgId: key.imgId,
|
||||
@@ -906,7 +917,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
// Already completed by a later chunk; the failure is stale.
|
||||
return entry;
|
||||
}
|
||||
return _store(
|
||||
final failed = await _store(
|
||||
entry.copyWith(
|
||||
// `isCorrupt` means every chunk arrived but the bytes were unusable
|
||||
// (CRC-16 mismatch or an undecodable metadata byte). The UI must say
|
||||
@@ -919,6 +930,8 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
error: failure.isCorrupt ? failure.reason.name : null,
|
||||
),
|
||||
);
|
||||
await evictToBudget(protect: failed.streamId);
|
||||
return failed;
|
||||
}
|
||||
|
||||
/// Records the local user's own send so the outgoing bubble can show the real
|
||||
@@ -1027,6 +1040,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// Cancels the running decode and stops the queue; the entry goes back to
|
||||
/// `reassembled` and will be picked up again later.
|
||||
Future<void> handleMemoryPressure() async {
|
||||
_cancelRequested = true;
|
||||
decoder?.cancelCodecJob();
|
||||
_queue.clear();
|
||||
for (final entry in _entries.values.toList()) {
|
||||
@@ -1190,6 +1204,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
final started = _clock();
|
||||
_cancelRequested = false;
|
||||
await _store(entry.copyWith(state: ReceivedImageState.decoding));
|
||||
|
||||
ImageCodecResult? result;
|
||||
@@ -1201,7 +1216,14 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
);
|
||||
} catch (error) {
|
||||
final current = _entries[entry.streamId] ?? entry;
|
||||
if (!_foreground) {
|
||||
if (_cancelRequested) {
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
needsManualDecode: true,
|
||||
),
|
||||
);
|
||||
} else if (!_foreground) {
|
||||
await _store(current.copyWith(state: ReceivedImageState.reassembled));
|
||||
} else {
|
||||
await _store(
|
||||
@@ -1224,6 +1246,16 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
final png = result.pngBytes;
|
||||
if (result.status != ImageCodecStatus.completed || png == null) {
|
||||
if (_cancelRequested) {
|
||||
// The codec reports a killed job as `failed`; the bitstream is fine.
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
needsManualDecode: true,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
@@ -1348,9 +1380,15 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
final evicted = <String>[];
|
||||
final now = _clock();
|
||||
|
||||
// 1. Age budget: nothing survives, not even the bitstream.
|
||||
// 1. Age budget: nothing survives, not even the bitstream. A failed image
|
||||
// has no bubble worth keeping, so it goes entirely, sidecar included.
|
||||
for (final entry in _entries.values.toList()) {
|
||||
if (now.difference(entry.firstSeen) <= maxAge) continue;
|
||||
if (entry.state.isFailure) {
|
||||
await deleteImage(entry.streamId);
|
||||
evicted.add(entry.streamId);
|
||||
continue;
|
||||
}
|
||||
if (!entry.pngStored && !entry.bitstreamStored) continue;
|
||||
await blobs.deletePng(entry.streamId);
|
||||
await blobs.deleteBitstream(entry.streamId);
|
||||
@@ -1414,6 +1452,22 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
evicted.add(victim.streamId);
|
||||
}
|
||||
|
||||
// 3. Failed entries hold no PNG, so the loop above never counts them; cap
|
||||
// them by entry count, oldest first, or a noisy mesh grows the sidecars
|
||||
// (and the startup load) without bound.
|
||||
if (_entries.length > maxImages) {
|
||||
final failures =
|
||||
_entries.values
|
||||
.where((e) => e.state.isFailure && e.streamId != protect)
|
||||
.toList()
|
||||
..sort((a, b) => a.firstSeen.compareTo(b.firstSeen));
|
||||
for (final victim in failures) {
|
||||
if (_entries.length <= maxImages) break;
|
||||
await deleteImage(victim.streamId);
|
||||
evicted.add(victim.streamId);
|
||||
}
|
||||
}
|
||||
|
||||
if (evicted.isNotEmpty) _notify();
|
||||
return evicted;
|
||||
}
|
||||
|
||||
@@ -23,19 +23,22 @@ class RepeaterCommandService {
|
||||
int _prefixCounter = 0;
|
||||
|
||||
static const int maxRetries = 5;
|
||||
static final RegExp _prefixPattern = RegExp(r'^[0-9A-Fa-f]{2}\|');
|
||||
|
||||
RepeaterCommandService(this._connector);
|
||||
|
||||
/// Send a CLI command to a repeater with automatic retries
|
||||
/// Returns a future that completes when a response is received or after max retries
|
||||
/// Returns a future that completes when a response is received or after max retries.
|
||||
/// With [raw], the command is sent verbatim without the `XX|` reply prefix.
|
||||
Future<String> sendCommand(
|
||||
Contact repeater,
|
||||
String command, {
|
||||
Function(String)? onResponse,
|
||||
Function(int)? onAttempt,
|
||||
int retries = maxRetries,
|
||||
bool raw = false,
|
||||
}) async {
|
||||
command = normalizeRepeaterClockSyncCommand(command);
|
||||
if (!raw) command = normalizeRepeaterClockSyncCommand(command);
|
||||
final attemptCount = retries < 1 ? 1 : retries;
|
||||
final selection = await _connector.preparePathForContactSend(repeater);
|
||||
|
||||
@@ -47,6 +50,7 @@ class RepeaterCommandService {
|
||||
command,
|
||||
selection,
|
||||
attempt,
|
||||
raw,
|
||||
);
|
||||
onResponse?.call(response);
|
||||
return response;
|
||||
@@ -63,6 +67,7 @@ class RepeaterCommandService {
|
||||
String command,
|
||||
PathSelection selection,
|
||||
int attempt,
|
||||
bool raw,
|
||||
) async {
|
||||
final repeaterKey = repeater.publicKeyHex;
|
||||
final prefix = _nextPrefixToken();
|
||||
@@ -73,7 +78,7 @@ class RepeaterCommandService {
|
||||
_pendingByPrefix[prefix] = commandId;
|
||||
|
||||
try {
|
||||
final framedCommand = '$prefix$command';
|
||||
final framedCommand = raw ? command : '$prefix$command';
|
||||
final pathLengthValue = selection.useFlood ? -1 : selection.hopCount;
|
||||
final timestampSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
_connector.trackRepeaterAck(
|
||||
@@ -123,6 +128,15 @@ class RepeaterCommandService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send [line] verbatim and don't wait for a reply. While `region load` is
|
||||
/// active the firmware consumes each line before prefix stripping and
|
||||
/// sends nothing back (simple_repeater/MyMesh.cpp handleCommand).
|
||||
Future<void> sendUnansweredLine(Contact repeater, String line) {
|
||||
return _connector.sendFrame(
|
||||
buildSendCliCommandFrame(repeater.publicKey, line),
|
||||
);
|
||||
}
|
||||
|
||||
/// Call this when a text message response is received from a repeater
|
||||
void handleResponse(Contact repeater, String responseText) {
|
||||
// Find pending command for this repeater and complete it
|
||||
@@ -130,14 +144,17 @@ class RepeaterCommandService {
|
||||
|
||||
String? commandId;
|
||||
String responsePayload = responseText;
|
||||
if (responseText.length >= 3 && responseText[2] == '|') {
|
||||
final prefix = responseText.substring(0, 3);
|
||||
if (_prefixPattern.hasMatch(responseText)) {
|
||||
final prefix = responseText.substring(0, 3).toUpperCase();
|
||||
commandId = _pendingByPrefix[prefix];
|
||||
if (commandId == null || !commandId.startsWith('${repeaterKey}_')) {
|
||||
return;
|
||||
}
|
||||
responsePayload = responseText.substring(3).trimLeft();
|
||||
}
|
||||
|
||||
commandId ??= _pendingCommands.keys.firstWhere(
|
||||
(id) => id.startsWith(repeaterKey),
|
||||
(id) => id.startsWith('${repeaterKey}_'),
|
||||
orElse: () => '',
|
||||
);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:convert';
|
||||
import '../models/delivery_observation.dart';
|
||||
import '../models/path_history.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
class StorageService {
|
||||
static const String _pathHistoryPrefix = 'path_history_';
|
||||
@@ -11,6 +12,14 @@ class StorageService {
|
||||
'repeater_auto_clock_sync_after_login';
|
||||
static const String _deliveryObservationsKey = 'delivery_observations';
|
||||
|
||||
String _publicKeyHex = '';
|
||||
set setPublicKeyHex(String value) =>
|
||||
_publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
|
||||
|
||||
String _pathHistoryKey(String contactPubKeyHex) => _publicKeyHex.isEmpty
|
||||
? '$_pathHistoryPrefix$contactPubKeyHex'
|
||||
: '$_pathHistoryPrefix${_publicKeyHex}_$contactPubKeyHex';
|
||||
|
||||
Future<Map<String, bool>> _loadRepeaterAutoClockSyncAfterLogin() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final jsonStr = prefs.getString(_repeaterAutoClockSyncAfterLoginKey);
|
||||
@@ -48,15 +57,18 @@ class StorageService {
|
||||
ContactPathHistory history,
|
||||
) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
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 key = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
final jsonStr = prefs.getString(key);
|
||||
final key = _pathHistoryKey(contactPubKeyHex);
|
||||
// Fall back to the pre-scoping key so learned routes survive the upgrade.
|
||||
final jsonStr =
|
||||
prefs.getString(key) ??
|
||||
prefs.getString('$_pathHistoryPrefix$contactPubKeyHex');
|
||||
|
||||
if (jsonStr == null) return null;
|
||||
|
||||
@@ -70,8 +82,8 @@ class StorageService {
|
||||
|
||||
Future<void> clearPathHistory(String contactPubKeyHex) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
await prefs.remove(key);
|
||||
await prefs.remove(_pathHistoryKey(contactPubKeyHex));
|
||||
await prefs.remove('$_pathHistoryPrefix$contactPubKeyHex');
|
||||
}
|
||||
|
||||
Future<void> clearAllPathHistories() async {
|
||||
@@ -173,14 +185,24 @@ class StorageService {
|
||||
|
||||
if (jsonStr == null) return [];
|
||||
|
||||
final List<dynamic> list;
|
||||
try {
|
||||
final list = jsonDecode(jsonStr) as List;
|
||||
return list
|
||||
.map((e) => DeliveryObservation.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
list = jsonDecode(jsonStr) as List<dynamic>;
|
||||
} catch (e) {
|
||||
appLogger.warn('Stored delivery observations are unreadable: $e');
|
||||
return [];
|
||||
}
|
||||
final observations = <DeliveryObservation>[];
|
||||
for (final e in list) {
|
||||
try {
|
||||
observations.add(
|
||||
DeliveryObservation.fromJson(e as Map<String, dynamic>),
|
||||
);
|
||||
} catch (err) {
|
||||
appLogger.warn('Skipping malformed delivery observation: $err');
|
||||
}
|
||||
}
|
||||
return observations;
|
||||
}
|
||||
|
||||
Future<void> clearDeliveryObservations() async {
|
||||
|
||||
@@ -58,7 +58,10 @@ class TranslationFileStore {
|
||||
required Stream<List<int>> chunks,
|
||||
}) async {
|
||||
final directoryPath = await modelDirectoryPath();
|
||||
final file = File('$directoryPath/$fileName');
|
||||
final finalPath = '$directoryPath/$fileName';
|
||||
// Hidden until complete, so a killed download is swept by
|
||||
// [scanDownloadedModels] instead of being registered as a model.
|
||||
final file = File(_partPath(directoryPath, fileName));
|
||||
final sink = file.openWrite();
|
||||
var fileSizeBytes = 0;
|
||||
var completed = false;
|
||||
@@ -74,8 +77,9 @@ class TranslationFileStore {
|
||||
await file.delete();
|
||||
}
|
||||
}
|
||||
await file.rename(finalPath);
|
||||
return DownloadedModelFile(
|
||||
localPath: file.path,
|
||||
localPath: finalPath,
|
||||
fileSizeBytes: fileSizeBytes,
|
||||
);
|
||||
}
|
||||
@@ -91,7 +95,8 @@ class TranslationFileStore {
|
||||
}) async {
|
||||
final dir = await modelDirectoryPath();
|
||||
final finalPath = '$dir/$fileName';
|
||||
final sink = File(finalPath).openWrite();
|
||||
final partPath = _partPath(dir, fileName);
|
||||
final sink = File(partPath).openWrite();
|
||||
var totalSize = 0;
|
||||
var completed = false;
|
||||
try {
|
||||
@@ -110,14 +115,18 @@ class TranslationFileStore {
|
||||
}
|
||||
}
|
||||
if (!completed) {
|
||||
final finalFile = File(finalPath);
|
||||
if (finalFile.existsSync()) {
|
||||
await finalFile.delete();
|
||||
final partFile = File(partPath);
|
||||
if (partFile.existsSync()) {
|
||||
await partFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
await File(partPath).rename(finalPath);
|
||||
return DownloadedModelFile(localPath: finalPath, fileSizeBytes: totalSize);
|
||||
}
|
||||
|
||||
String _partPath(String dir, String fileName) =>
|
||||
fileName.startsWith('.') ? '$dir/$fileName.part' : '$dir/.$fileName.part';
|
||||
}
|
||||
|
||||
class DownloadedModelFile {
|
||||
|
||||
@@ -271,10 +271,19 @@ class TranslationService extends ChangeNotifier {
|
||||
_downloadTotalBytes ??= response.contentLength;
|
||||
_notify();
|
||||
final trackedStream = _trackDownloadProgress(response.stream);
|
||||
return await _fileStore.writeModelBytes(
|
||||
final downloaded = await _fileStore.writeModelBytes(
|
||||
fileName: fileName,
|
||||
chunks: trackedStream,
|
||||
);
|
||||
final expected = response.contentLength;
|
||||
if (expected != null && downloaded.fileSizeBytes != expected) {
|
||||
await _fileStore.deleteFile(downloaded.localPath);
|
||||
throw StateError(
|
||||
'Model download incomplete: '
|
||||
'${downloaded.fileSizeBytes} of $expected bytes',
|
||||
);
|
||||
}
|
||||
return downloaded;
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
@@ -350,10 +359,17 @@ class TranslationService extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
final trackedStream = _trackDownloadProgress(response.stream);
|
||||
await _fileStore.writeModelBytes(
|
||||
final downloaded = await _fileStore.writeModelBytes(
|
||||
fileName: chunkPath.split(RegExp(r'[/\\]')).last,
|
||||
chunks: trackedStream,
|
||||
);
|
||||
final expected = end - start + 1;
|
||||
if (downloaded.fileSizeBytes != expected) {
|
||||
throw StateError(
|
||||
'Range download incomplete: '
|
||||
'${downloaded.fileSizeBytes} of $expected bytes',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void cancelDownload() {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ffi';
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
|
||||
import 'package:ffi/ffi.dart';
|
||||
import 'package:flserial/flserial.dart';
|
||||
import 'package:flserial/flserial_exception.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -32,6 +35,18 @@ class UsbSerialService {
|
||||
String? _connectedPortKey;
|
||||
String? _connectedPortLabel;
|
||||
FlSerial? _serial;
|
||||
|
||||
/// Non-null while a disconnect teardown (native close in a helper isolate,
|
||||
/// then subscription cancel) is running.
|
||||
Future<void>? _activeDisconnect;
|
||||
|
||||
/// Exists while a native close runs in a helper isolate. flserial's slot
|
||||
/// table is process-global and survives a hot restart, but
|
||||
/// [_activeDisconnect] does not, so a fresh isolate checks this marker
|
||||
/// before fl_free() tears down a slot that is still inside close().
|
||||
static final String _pendingClosePath =
|
||||
'${Directory.systemTemp.path}/meshcore_open_usb_close_$pid';
|
||||
static const Duration _maxPendingClose = Duration(seconds: 45);
|
||||
AppDebugLogService? _debugLogService;
|
||||
Object? _lastError;
|
||||
|
||||
@@ -120,6 +135,33 @@ class UsbSerialService {
|
||||
throw UnsupportedError('USB serial is not supported on this platform.');
|
||||
}
|
||||
|
||||
// A previous disconnect may still be running: on desktop its native close
|
||||
// waits out the kernel's closing_wait in a helper isolate, and the
|
||||
// teardown only marks the transport disconnected afterwards. Reopening
|
||||
// before it finishes would let the old teardown overwrite the new
|
||||
// connection's state (and, on desktop, race fl_free()/fl_close() over the
|
||||
// process-global flserial_tab). Wait for the whole teardown — on every
|
||||
// platform — before claiming the `connecting` state.
|
||||
final pendingDisconnect = _activeDisconnect;
|
||||
if (pendingDisconnect != null) {
|
||||
_debugLogService?.info(
|
||||
'Waiting for the previous USB disconnect to finish before reopening',
|
||||
tag: 'USB Serial',
|
||||
);
|
||||
try {
|
||||
await pendingDisconnect;
|
||||
} catch (_) {
|
||||
// Failures are already logged by the teardown path.
|
||||
}
|
||||
|
||||
// The await above is a suspension point: another caller may have claimed
|
||||
// the transport while this one waited.
|
||||
if (_status == UsbSerialStatus.connected ||
|
||||
_status == UsbSerialStatus.connecting) {
|
||||
throw StateError('USB serial transport is already active');
|
||||
}
|
||||
}
|
||||
|
||||
_status = UsbSerialStatus.connecting;
|
||||
var normalizedPortName = normalizeUsbPortName(portName);
|
||||
_frameDecoder.reset();
|
||||
@@ -157,6 +199,9 @@ class UsbSerialService {
|
||||
//
|
||||
// This must happen before we register any new NativeCallable, so it must
|
||||
// be the very first thing we do in the desktop branch.
|
||||
// (the previous teardown was already awaited above)
|
||||
await _waitForOrphanedNativeClose();
|
||||
|
||||
try {
|
||||
bindings.fl_free();
|
||||
bindings.fl_init(16);
|
||||
@@ -289,9 +334,23 @@ class UsbSerialService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
if (_status == UsbSerialStatus.disconnected) return;
|
||||
/// Tears the transport down. Re-entrant calls (e.g. the `onDone` handler
|
||||
/// firing while a disconnect is already running) join the in-flight
|
||||
/// teardown instead of racing it.
|
||||
Future<void> disconnect() {
|
||||
final pending = _activeDisconnect;
|
||||
if (pending != null) return pending;
|
||||
if (_status == UsbSerialStatus.disconnected) return Future<void>.value();
|
||||
final teardown = _disconnectInternal();
|
||||
_activeDisconnect = teardown;
|
||||
return teardown.whenComplete(() {
|
||||
if (identical(_activeDisconnect, teardown)) {
|
||||
_activeDisconnect = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _disconnectInternal() async {
|
||||
final portLabel = _connectedPortLabel ?? _connectedPortKey;
|
||||
_debugLogService?.info(
|
||||
'USB disconnect starting port=${portLabel ?? 'unknown'}',
|
||||
@@ -322,11 +381,13 @@ class UsbSerialService {
|
||||
try {
|
||||
if (serial?.isOpen() == FlOpenStatus.open) {
|
||||
serial?.setDTR(false);
|
||||
serial?.closePort();
|
||||
}
|
||||
} catch (_) {
|
||||
// Ignore errors while closing.
|
||||
}
|
||||
if (serial != null) {
|
||||
await _closePortOffUiIsolate(serial);
|
||||
}
|
||||
// Note: we do NOT call free() here; that would globally reset native
|
||||
// state for all ports. The global reset is done in connect() instead,
|
||||
// before the next open, which is the safer place to do it.
|
||||
@@ -362,20 +423,150 @@ class UsbSerialService {
|
||||
);
|
||||
}
|
||||
|
||||
/// Closes the native port without blocking the Dart UI isolate.
|
||||
///
|
||||
/// `close(2)` on a tty whose output has not been drained by the peer blocks
|
||||
/// in the kernel for the line discipline's `closing_wait` (30s by default —
|
||||
/// measured 30.4s on Linux with a CDC-ACM device that never reads its bulk
|
||||
/// OUT endpoint, e.g. a MeshCore board flashed with a BLE-only companion
|
||||
/// build). `FlSerial.closePort()` is a synchronous FFI call, so running it
|
||||
/// inline freezes the whole app for that entire window. `fl_close()` only
|
||||
/// touches process-global native state, so it is safe to run in a helper
|
||||
/// isolate; the Dart-side cleanup that `closePort()` also performs is
|
||||
/// replicated here afterwards.
|
||||
Future<void> _closePortOffUiIsolate(FlSerial serial) async {
|
||||
final flh = serial.flh;
|
||||
if (flh < 0) {
|
||||
// Already closed synchronously by dispose(), which also closed the
|
||||
// stream and freed both I/O buffers.
|
||||
return;
|
||||
}
|
||||
serial.flh = -1;
|
||||
final startedAt = DateTime.now();
|
||||
final markerPath = _pendingClosePath;
|
||||
try {
|
||||
File(markerPath).writeAsStringSync('');
|
||||
} catch (_) {}
|
||||
try {
|
||||
await Isolate.run(() {
|
||||
bindings.fl_close(flh);
|
||||
try {
|
||||
File(markerPath).deleteSync();
|
||||
} catch (_) {}
|
||||
});
|
||||
} catch (error) {
|
||||
// Spawning the helper failed, so the native slot and its SerialThread
|
||||
// are still alive with no reachable handle. Close it inline instead —
|
||||
// that blocks, but only in this already-degraded path.
|
||||
_debugLogService?.warn(
|
||||
'Off-isolate USB port close failed ($error); closing inline',
|
||||
tag: 'USB Serial',
|
||||
);
|
||||
try {
|
||||
bindings.fl_close(flh);
|
||||
} catch (_) {
|
||||
// Ignore errors while closing.
|
||||
}
|
||||
}
|
||||
try {
|
||||
File(markerPath).deleteSync();
|
||||
} catch (_) {}
|
||||
final elapsed = DateTime.now().difference(startedAt);
|
||||
if (elapsed > const Duration(seconds: 1)) {
|
||||
_debugLogService?.warn(
|
||||
'Native USB port close took ${elapsed.inMilliseconds}ms — the device '
|
||||
'was not draining its serial input',
|
||||
tag: 'USB Serial',
|
||||
);
|
||||
}
|
||||
try {
|
||||
await serial.onSerialData.close();
|
||||
} catch (_) {
|
||||
// Ignore errors while releasing Dart-side resources.
|
||||
}
|
||||
_releaseSerialBuffers(serial);
|
||||
}
|
||||
|
||||
/// Waits for a native close left running by a previous isolate (hot
|
||||
/// restart during a slow close). Bounded by the marker's age so a stale
|
||||
/// marker — its helper isolate killed before deleting it — cannot block
|
||||
/// forever.
|
||||
Future<void> _waitForOrphanedNativeClose() async {
|
||||
final marker = File(_pendingClosePath);
|
||||
try {
|
||||
if (!marker.existsSync()) return;
|
||||
_debugLogService?.info(
|
||||
'Waiting for a USB port close left over from a previous isolate',
|
||||
tag: 'USB Serial',
|
||||
);
|
||||
final deadline = marker.lastModifiedSync().add(_maxPendingClose);
|
||||
while (marker.existsSync() && DateTime.now().isBefore(deadline)) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 250));
|
||||
}
|
||||
if (marker.existsSync()) marker.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// Frees the two calloc'd I/O buffers `openPort()` allocated and clears the
|
||||
/// pointer fields. `FlSerial.closePort()` is never used for this: it tests
|
||||
/// the buffers' first byte (`.value`) instead of their address, so it
|
||||
/// usually leaks them.
|
||||
void _releaseSerialBuffers(FlSerial serial) {
|
||||
try {
|
||||
if (serial.serialReadBuff.address != 0) {
|
||||
calloc.free(serial.serialReadBuff);
|
||||
}
|
||||
serial.serialReadBuff = Pointer.fromAddress(0);
|
||||
if (serial.serialWriteBuff.address != 0) {
|
||||
calloc.free(serial.serialWriteBuff);
|
||||
}
|
||||
serial.serialWriteBuff = Pointer.fromAddress(0);
|
||||
} catch (_) {
|
||||
// Ignore errors while releasing Dart-side resources.
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
// Synchronously close the native port so the SerialThread exits before
|
||||
// the Dart isolate is torn down (e.g. on hot restart). The async
|
||||
// disconnect() path via unawaited() offers no ordering guarantee — the
|
||||
// isolate may die before the Future resolves, leaving the thread alive
|
||||
// with a dangling NativeCallable pointer.
|
||||
final pendingDisconnect = _activeDisconnect;
|
||||
if (pendingDisconnect != null) {
|
||||
// A disconnect is already running and owns the teardown ordering
|
||||
// (native close first, subscription cancel after). Re-entering
|
||||
// disconnect() here would cancel the subscription underneath it, so
|
||||
// only chain the frame-controller cleanup onto that teardown.
|
||||
unawaited(pendingDisconnect.whenComplete(_closeFrameController));
|
||||
return;
|
||||
}
|
||||
if (_useDesktopFlSerial) {
|
||||
final serial = _serial;
|
||||
try {
|
||||
if (serial?.isOpen() == FlOpenStatus.open) {
|
||||
serial?.setDTR(false);
|
||||
serial?.closePort(); // synchronous C call — kills the SerialThread
|
||||
_serial = null;
|
||||
if (serial != null) {
|
||||
// Close on any live handle, not only when isOpen() reports `open`:
|
||||
// flserial keeps a valid slot (and a running SerialThread) when the
|
||||
// port is in an I/O error state, and _serial is already unreachable.
|
||||
final flh = serial.flh;
|
||||
if (flh >= 0) {
|
||||
try {
|
||||
serial.setDTR(false);
|
||||
} catch (_) {
|
||||
// Line-control failure must not skip the close below.
|
||||
}
|
||||
serial.flh = -1;
|
||||
try {
|
||||
bindings.fl_close(
|
||||
flh,
|
||||
); // synchronous C call — kills the SerialThread
|
||||
} catch (_) {}
|
||||
unawaited(serial.onSerialData.close());
|
||||
}
|
||||
} catch (_) {}
|
||||
// _serial is gone, so the disconnect() below can no longer reach the
|
||||
// buffers: release them here.
|
||||
_releaseSerialBuffers(serial);
|
||||
}
|
||||
}
|
||||
// Kick off the full async teardown for anything else (subscription cancel,
|
||||
// stream controller close). These are best-effort at dispose time.
|
||||
@@ -383,6 +574,14 @@ class UsbSerialService {
|
||||
}
|
||||
|
||||
void _handleSerialData(FlSerialEventArgs event) {
|
||||
if (_status == UsbSerialStatus.disconnecting ||
|
||||
_status == UsbSerialStatus.disconnected) {
|
||||
// Teardown already invalidated the native handle; a callback queued
|
||||
// before that would make readList() throw and publish a spurious
|
||||
// transport error that triggers another disconnect. Data that arrives
|
||||
// while still `connecting` is kept — the decoder buffers it.
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final bytes = event.serial.readList();
|
||||
if (bytes.isNotEmpty) {
|
||||
@@ -399,7 +598,9 @@ class UsbSerialService {
|
||||
return;
|
||||
}
|
||||
if (data is ByteData) {
|
||||
_ingestRawBytes(data.buffer.asUint8List());
|
||||
_ingestRawBytes(
|
||||
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),
|
||||
);
|
||||
return;
|
||||
}
|
||||
_addFrameError(
|
||||
@@ -412,7 +613,11 @@ class UsbSerialService {
|
||||
}
|
||||
|
||||
void _handleSerialDone() {
|
||||
final wasConnected = _status == UsbSerialStatus.connected;
|
||||
unawaited(disconnect());
|
||||
if (wasConnected) {
|
||||
_addFrameError(StateError('USB serial connection closed'));
|
||||
}
|
||||
}
|
||||
|
||||
void _ingestRawBytes(Uint8List bytes) {
|
||||
|
||||
Reference in new issue
Block a user