From 296eab20ca6b4655dc9b29b732e7fd95e565540c Mon Sep 17 00:00:00 2001 From: shortwavesurfer2009 Date: Sun, 4 Oct 2026 00:48:51 -0400 Subject: [PATCH 01/67] Add low battery notification channel with threshold alerts --- lib/connector/meshcore_connector.dart | 27 ++++++++ lib/l10n/app_en.arb | 13 ++++ lib/l10n/app_localizations.dart | 12 ++++ lib/l10n/app_localizations_bg.dart | 8 +++ lib/l10n/app_localizations_de.dart | 8 +++ lib/l10n/app_localizations_en.dart | 8 +++ lib/l10n/app_localizations_es.dart | 8 +++ lib/l10n/app_localizations_fr.dart | 8 +++ lib/l10n/app_localizations_hu.dart | 8 +++ lib/l10n/app_localizations_it.dart | 8 +++ lib/l10n/app_localizations_ja.dart | 8 +++ lib/l10n/app_localizations_ko.dart | 8 +++ lib/l10n/app_localizations_nl.dart | 8 +++ lib/l10n/app_localizations_pl.dart | 8 +++ lib/l10n/app_localizations_pt.dart | 8 +++ lib/l10n/app_localizations_ru.dart | 8 +++ lib/l10n/app_localizations_sk.dart | 8 +++ lib/l10n/app_localizations_sl.dart | 8 +++ lib/l10n/app_localizations_sv.dart | 8 +++ lib/l10n/app_localizations_uk.dart | 8 +++ lib/l10n/app_localizations_zh.dart | 8 +++ lib/services/notification_service.dart | 45 +++++++++++++ untranslated.json | 87 +++++++++++++++++++++++++- 23 files changed, 327 insertions(+), 1 deletion(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 7874bc18..5b96b31f 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -266,6 +266,10 @@ class MeshCoreConnector extends ChangeNotifier { Stopwatch? _airtimeBumpStopwatch; int _prevTotalAirSecs = 0; int? _batteryMillivolts; + // Thresholds (percent) that trigger a low-battery notification once per + // crossing, re-arming 5 points above the threshold after recharge. + static const List _lowBatteryThresholds = [25, 10]; + final Set _batteryAlertedThresholds = {}; double? _selfLatitude; double? _selfLongitude; final List _directRepeaters = List.empty(growable: true); @@ -3139,6 +3143,7 @@ class MeshCoreConnector extends ChangeNotifier { _autoAddMaxHops = null; _contactsStorageFull = false; _batteryMillivolts = null; + _batteryAlertedThresholds.clear(); _repeaterBatterySnapshots.clear(); _batteryRequested = false; _awaitingSelfInfo = false; @@ -5357,6 +5362,7 @@ class MeshCoreConnector extends ChangeNotifier { _batteryMillivolts = reader.readUInt16LE(); _storageUsedKb = reader.readUInt32LE(); _storageTotalKb = reader.readUInt32LE(); + _checkLowBatteryThresholds(); final volts = (_batteryMillivolts! / 1000.0).toStringAsFixed(2); _appDebugLogService?.info( 'Pulled battery: $volts V ($_batteryMillivolts mV)', @@ -5371,6 +5377,27 @@ class MeshCoreConnector extends ChangeNotifier { } } + void _checkLowBatteryThresholds() { + final percent = batteryPercent; + if (percent == null) return; + + for (final threshold in _lowBatteryThresholds) { + if (percent <= threshold && + !_batteryAlertedThresholds.contains(threshold)) { + _batteryAlertedThresholds.add(threshold); + NotificationService().showLowBatteryNotification( + batteryPercent: percent, + threshold: threshold, + ); + } else if (percent > threshold + 5 && + _batteryAlertedThresholds.contains(threshold)) { + // Re-arm once the battery recovers 5 points above the threshold, + // so a recharge + discharge cycle alerts again without flapping. + _batteryAlertedThresholds.remove(threshold); + } + } + } + void _checkManualAddContacts() async { // If manual add contacts is enabled, set auto add config and other params. // and disable it after diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 47f2dba6..a8718ea7 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2573,6 +2573,19 @@ "contacts_contactAdvertCopied": "Advert copied to Clipboard.", "contacts_contactAdvertCopyFailed": "Copying advert to Clipboard failed.", "notification_activityTitle": "MeshCore Activity", + "notification_lowBatteryTitle": "Low battery", + "@notification_lowBatteryTitle": { + "description": "Title of the low battery notification" + }, + "notification_lowBatteryBody": "Device battery is at {percent}%", + "@notification_lowBatteryBody": { + "description": "Body of the low battery notification", + "placeholders": { + "percent": { + "type": "int" + } + } + }, "notification_messagesCount": "{count} {count, plural, =1{message} other{messages}}", "@notification_messagesCount": { "placeholders": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 66eedf4c..c5c9e414 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -7924,6 +7924,18 @@ abstract class AppLocalizations { /// **'MeshCore Activity'** String get notification_activityTitle; + /// Title of the low battery notification + /// + /// In en, this message translates to: + /// **'Low battery'** + String get notification_lowBatteryTitle; + + /// Body of the low battery notification + /// + /// In en, this message translates to: + /// **'Device battery is at {percent}%'** + String notification_lowBatteryBody(int percent); + /// No description provided for @notification_messagesCount. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index c54ab2ee..c1c2ac7f 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -4597,6 +4597,14 @@ class AppLocalizationsBg extends AppLocalizations { @override String get notification_activityTitle => 'Активност на MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index ca2ada41..e33166ef 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -4608,6 +4608,14 @@ class AppLocalizationsDe extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore Aktivität'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 70ce610f..b2f769bf 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -4533,6 +4533,14 @@ class AppLocalizationsEn extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore Activity'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index f0c31cb3..1a1f1e81 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -4599,6 +4599,14 @@ class AppLocalizationsEs extends AppLocalizations { @override String get notification_activityTitle => 'Actividad de MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 0385315d..176f8008 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -4619,6 +4619,14 @@ class AppLocalizationsFr extends AppLocalizations { @override String get notification_activityTitle => 'Activité MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 0b909253..e42e58d3 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -4597,6 +4597,14 @@ class AppLocalizationsHu extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore tevékenység'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index e737afdd..d29f0045 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -4604,6 +4604,14 @@ class AppLocalizationsIt extends AppLocalizations { @override String get notification_activityTitle => 'Attività MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 86130828..65f7d04e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -4373,6 +4373,14 @@ class AppLocalizationsJa extends AppLocalizations { @override String get notification_activityTitle => 'メッシュコアの活動'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 94c0f3bd..c8ca6e2b 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -4384,6 +4384,14 @@ class AppLocalizationsKo extends AppLocalizations { @override String get notification_activityTitle => '메쉬코어 활동'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 0c7a199a..9369eb42 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -4575,6 +4575,14 @@ class AppLocalizationsNl extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore Activiteit'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index fbe65401..42862a06 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -4623,6 +4623,14 @@ class AppLocalizationsPl extends AppLocalizations { @override String get notification_activityTitle => 'Aktywność MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 4c3b7c43..19e4552a 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -4601,6 +4601,14 @@ class AppLocalizationsPt extends AppLocalizations { @override String get notification_activityTitle => 'Atividade MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b197ce46..1916766f 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -4607,6 +4607,14 @@ class AppLocalizationsRu extends AppLocalizations { @override String get notification_activityTitle => 'Активность MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 2818ab6b..daf8043e 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -4581,6 +4581,14 @@ class AppLocalizationsSk extends AppLocalizations { @override String get notification_activityTitle => 'Aktivita MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index ab8ba209..de74a7b3 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -4579,6 +4579,14 @@ class AppLocalizationsSl extends AppLocalizations { @override String get notification_activityTitle => 'Aktivnost MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index aa6022e0..f5fc9e5e 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -4557,6 +4557,14 @@ class AppLocalizationsSv extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore Aktivitet'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index c3e5f7a0..be816508 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -4607,6 +4607,14 @@ class AppLocalizationsUk extends AppLocalizations { @override String get notification_activityTitle => 'Активність MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index d9d7281e..a9f91a99 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -4285,6 +4285,14 @@ class AppLocalizationsZh extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore 活动'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(int percent) { + return 'Device battery is at $percent%'; + } + @override String notification_messagesCount(int count) { return '$count 条消息'; diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 83714cfa..333466e4 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -597,6 +597,51 @@ class NotificationService { } } + /// Posts a low-battery alert for the connected device. + /// + /// Uses a per-threshold notification id so each alert level updates its own + /// notification instead of stacking. Bypasses the rate-limit queue, which + /// only handles message and advert notifications. + Future showLowBatteryNotification({ + required int batteryPercent, + required int threshold, + }) async { + if (!await _ensureCanNotify()) return; + + const androidDetails = AndroidNotificationDetails( + 'low_battery', + 'Low Battery', + channelDescription: 'Low battery alerts for the connected device', + importance: Importance.high, + priority: Priority.high, + icon: '@mipmap/ic_launcher', + ); + + const darwinDetails = DarwinNotificationDetails( + presentAlert: true, + presentBadge: false, + presentSound: true, + ); + + const notificationDetails = NotificationDetails( + android: androidDetails, + iOS: darwinDetails, + macOS: darwinDetails, + ); + + try { + await _notifications.show( + id: 'low_battery:$threshold'.hashCode, + title: _l10n.notification_lowBatteryTitle, + body: _l10n.notification_lowBatteryBody(batteryPercent), + notificationDetails: notificationDetails, + payload: 'low_battery', + ); + } catch (e) { + debugPrint('Failed to show low battery 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) diff --git a/untranslated.json b/untranslated.json index 9e26dfee..440e93f0 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,86 @@ -{} \ No newline at end of file +{ + "bg": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "de": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "es": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "fr": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "hu": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "it": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "ja": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "ko": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "nl": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "pl": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "pt": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "ru": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "sk": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "sl": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "sv": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "uk": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "zh": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ] +} From c161bffc837adcc12dc38fda8dc6b241f47eddf5 Mon Sep 17 00:00:00 2001 From: shortwavesurfer2009 Date: Mon, 5 Oct 2026 19:19:08 -0400 Subject: [PATCH 02/67] fold path hash size into radio settings --- lib/models/radio_settings.dart | 2 ++ lib/screens/settings_screen.dart | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lib/models/radio_settings.dart b/lib/models/radio_settings.dart index f7c4709c..6b3eee84 100644 --- a/lib/models/radio_settings.dart +++ b/lib/models/radio_settings.dart @@ -50,6 +50,7 @@ class RadioSettings { final LoRaSpreadingFactor spreadingFactor; final LoRaCodingRate codingRate; final int txPowerDbm; + final int pathHashByteWidth; RadioSettings({ required this.frequencyMHz, @@ -57,6 +58,7 @@ class RadioSettings { required this.spreadingFactor, required this.codingRate, required this.txPowerDbm, + this.pathHashByteWidth = 1, // app default; presets override if needed }); // Regional preset configurations diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 502e0f18..c94e23f2 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1526,10 +1526,14 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { LoRaCodingRate _codingRate = LoRaCodingRate.cr4_5; final _txPowerController = TextEditingController(text: '20'); bool _clientRepeat = false; + int _pathHashByteWidth = 1; int? _selectedPresetIndex; _RadioSettingsSnapshot? _lastNonRepeatSnapshot; String? _frequencyError; String? _txPowerError; + bool get _supportsPathHashMode => + (widget.connector.firmwareVerCode ?? 0) >= + _minFirmwareVerCodeForPathHashMode; AppDebugLogService get _appLog => Provider.of(context, listen: false); @@ -1583,6 +1587,7 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { _txPowerController.text = widget.connector.currentTxPower.toString(); } + _pathHashByteWidth = widget.connector.pathHashByteWidth; _clientRepeat = widget.connector.clientRepeat ?? false; _selectedPresetIndex = _findMatchingPresetIndex(); if (_clientRepeat) { @@ -1752,6 +1757,7 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { _spreadingFactor = preset.spreadingFactor; _codingRate = preset.codingRate; _txPowerController.text = preset.txPowerDbm.toString(); + _pathHashByteWidth = preset.pathHashByteWidth; _selectedPresetIndex = index; _lastNonRepeatSnapshot = baseSnapshot; } @@ -1911,6 +1917,10 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { return; } await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower)); + if (_supportsPathHashMode && + _pathHashByteWidth != widget.connector.pathHashByteWidth) { + await widget.connector.setPathHashMode(_pathHashByteWidth - 1); + } final selfInfo = widget.connector.receivedFrames .firstWhere((f) => f.isNotEmpty && f[0] == respCodeSelfInfo) .timeout(const Duration(seconds: 5)); @@ -2144,6 +2154,34 @@ class _RadioSettingsDialogState extends State<_RadioSettingsDialog> { }, ), const SizedBox(height: 16), + if (_supportsPathHashMode) ...[ + DropdownButtonFormField( + initialValue: _pathHashByteWidth, + decoration: InputDecoration( + labelText: l10n.repeater_pathHashMode, + border: const OutlineInputBorder(), + ), + items: [ + DropdownMenuItem( + value: 1, + child: Text(l10n.repeater_pathHashModeOption0), + ), + DropdownMenuItem( + value: 2, + child: Text(l10n.repeater_pathHashModeOption1), + ), + DropdownMenuItem( + value: 3, + child: Text(l10n.repeater_pathHashModeOption2), + ), + ], + onChanged: (value) { + if (value == null) return; + setState(() => _pathHashByteWidth = value); + }, + ), + const SizedBox(height: 16), + ], TextField( controller: _txPowerController, onChanged: (_) => _handleManualSettingsChanged('tx power'), From a4a7e007329aeb811cf80dfea1beb2c5638ad18e Mon Sep 17 00:00:00 2001 From: ericz Date: Sun, 11 Oct 2026 13:14:14 +0200 Subject: [PATCH 03/67] upload url image or file to ipfs --- lib/helpers/ipfs_upload_helper.dart | 187 ++++++++++ lib/helpers/message_url_image_helper.dart | 83 ++++- lib/l10n/app_en.arb | 24 ++ lib/l10n/app_localizations.dart | 102 ++++++ lib/l10n/app_localizations_bg.dart | 58 +++ lib/l10n/app_localizations_de.dart | 58 +++ lib/l10n/app_localizations_en.dart | 58 +++ lib/l10n/app_localizations_es.dart | 58 +++ lib/l10n/app_localizations_fr.dart | 58 +++ lib/l10n/app_localizations_hu.dart | 58 +++ lib/l10n/app_localizations_it.dart | 58 +++ lib/l10n/app_localizations_ja.dart | 58 +++ lib/l10n/app_localizations_ko.dart | 58 +++ lib/l10n/app_localizations_nl.dart | 58 +++ lib/l10n/app_localizations_pl.dart | 58 +++ lib/l10n/app_localizations_pt.dart | 58 +++ lib/l10n/app_localizations_ru.dart | 58 +++ lib/l10n/app_localizations_sk.dart | 58 +++ lib/l10n/app_localizations_sl.dart | 58 +++ lib/l10n/app_localizations_sv.dart | 58 +++ lib/l10n/app_localizations_uk.dart | 58 +++ lib/l10n/app_localizations_zh.dart | 58 +++ lib/main.dart | 8 + lib/models/app_settings.dart | 57 +++ lib/screens/app_settings_screen.dart | 328 ++++++++++++++++- lib/screens/channel_chat_screen.dart | 129 ++++++- lib/screens/chat_screen.dart | 178 +++++++-- lib/services/app_settings_service.dart | 18 + lib/services/notification_service.dart | 11 +- .../message_url_image_helper_test.dart | 95 ++++- test/models/model_changes_test.dart | 17 + .../tcp_transport_service_native_test.dart | 52 ++- untranslated.json | 342 +++++++++++++++++- 33 files changed, 2594 insertions(+), 81 deletions(-) create mode 100644 lib/helpers/ipfs_upload_helper.dart diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart new file mode 100644 index 00000000..8d294568 --- /dev/null +++ b/lib/helpers/ipfs_upload_helper.dart @@ -0,0 +1,187 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +import '../models/app_settings.dart'; + +class IpfsUploadHelper { + static http.Client? httpClient; + + static String mimeTypeForFileName(String fileName) { + switch (fileName.toLowerCase().split('.').last) { + case 'jpg': + case 'jpeg': + return 'image/jpeg'; + case 'png': + return 'image/png'; + case 'gif': + return 'image/gif'; + case 'webp': + return 'image/webp'; + case 'heic': + return 'image/heic'; + default: + return 'application/octet-stream'; + } + } + + static Future uploadImageWithSettings({ + required AppSettings settings, + required Uint8List bytes, + required String fileName, + required String mimeType, + }) { + return uploadImage( + bytes: bytes, + fileName: fileName, + mimeType: mimeType, + uploadEndpoint: settings.uploadIpfsEndpoint, + uploadApiKey: settings.uploadIpfsApiKey, + uploadGateway: settings.uploadIpfsGateway, + ); + } + + static Future uploadImage({ + required Uint8List bytes, + required String fileName, + required String mimeType, + required String uploadEndpoint, + required String uploadApiKey, + String uploadGateway = '', + }) async { + final endpoint = uploadEndpoint.trim(); + if (endpoint.isEmpty) { + throw ArgumentError('Configure an IPFS upload endpoint first.'); + } + + final token = uploadApiKey.trim(); + final endpointUri = Uri.parse(endpoint); + final endpointHost = endpointUri.host.toLowerCase(); + final isPinata = + endpointHost.contains('pinata') || + endpoint.toLowerCase().contains('pinfiletoipfs'); + final isFilebase = endpointHost.contains('filebase'); + final isKubo = !isPinata && !isFilebase; + final safeFileName = _sanitizeUploadFileName(fileName); + if (isFilebase && token.isEmpty) { + throw ArgumentError('Filebase RPC requires an API token.'); + } + + final Uri uploadUri; + final request = http.MultipartRequest('POST', endpointUri) + ..files.add( + http.MultipartFile.fromBytes('file', bytes, filename: safeFileName), + ); + + if (isPinata) { + if (token.isEmpty) { + throw ArgumentError('Pinata requires an API key or JWT.'); + } + request.headers['Authorization'] = 'Bearer $token'; + request.fields['pinataOptions'] = jsonEncode({'cidVersion': 1}); + request.fields['pinataMetadata'] = jsonEncode({'name': safeFileName}); + uploadUri = endpointUri; + } else { + final parameters = {'cid-version': '1'}; + if (isKubo) parameters['pin'] = 'true'; + uploadUri = endpointUri.replace( + queryParameters: {...endpointUri.queryParameters, ...parameters}, + ); + if (token.isNotEmpty) { + request.headers['Authorization'] = 'Bearer $token'; + } + } + + final finalRequest = request.url == uploadUri + ? request + : (http.MultipartRequest('POST', uploadUri) + ..headers.addAll(request.headers) + ..fields.addAll(request.fields) + ..files.addAll(request.files)); + final client = httpClient; + final response = await (client == null + ? finalRequest.send() + : client.send(finalRequest)); + final body = await response.stream.bytesToString(); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw Exception('IPFS upload failed (${response.statusCode}): $body'); + } + + final cid = _extractUploadCid(body, isPinata: isPinata); + if (cid == null || cid.isEmpty) { + throw Exception('IPFS upload did not return a CID.'); + } + + if (isKubo) { + await _copyKuboFileToMfs( + endpoint: endpoint, + cid: cid, + fileName: safeFileName, + authorization: token.isEmpty ? null : 'Bearer $token', + ); + } + + final gateway = normalizeIpfsGateway(uploadGateway); + return gateway.isEmpty ? 'ipfs://$cid' : '$gateway$cid'; + } + + static Future _copyKuboFileToMfs({ + required String endpoint, + required String cid, + required String fileName, + required String? authorization, + }) async { + final uploadUri = Uri.parse(endpoint); + final copyPath = uploadUri.path.replaceFirst( + RegExp(r'/add/?$'), + '/files/cp', + ); + if (copyPath == uploadUri.path) { + throw ArgumentError('Kubo upload endpoint must end with /add.'); + } + + final mfsPath = '/meshcore_uploads/$cid-$fileName'; + final copyUri = uploadUri.replace( + path: copyPath, + query: + 'arg=${Uri.encodeQueryComponent('/ipfs/$cid')}' + '&arg=${Uri.encodeQueryComponent(mfsPath)}&parents=true', + ); + final headers = authorization == null + ? {} + : {'Authorization': authorization}; + final client = httpClient; + final response = await (client == null + ? http.post(copyUri, headers: headers) + : client.post(copyUri, headers: headers)); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw Exception( + 'Kubo MFS import failed (${response.statusCode}): ${response.body}', + ); + } + } + + static String _sanitizeUploadFileName(String name) { + final cleaned = name.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_').trim(); + return cleaned.isEmpty ? 'shared-image' : cleaned; + } + + static String? _extractUploadCid(String body, {required bool isPinata}) { + final lines = const LineSplitter() + .convert(body) + .where((line) => line.trim().isNotEmpty) + .toList(); + for (final line in lines.reversed) { + try { + final decoded = jsonDecode(line); + if (decoded is! Map) continue; + final value = isPinata ? decoded['IpfsHash'] : decoded['Hash']; + if (value is String && value.isNotEmpty) return value; + } catch (_) { + continue; + } + } + return null; + } +} diff --git a/lib/helpers/message_url_image_helper.dart b/lib/helpers/message_url_image_helper.dart index 3f2a7835..30eb4e2f 100644 --- a/lib/helpers/message_url_image_helper.dart +++ b/lib/helpers/message_url_image_helper.dart @@ -1,10 +1,14 @@ import 'dart:async'; import 'dart:collection'; +import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:http/http.dart' as http; +import 'ipfs_upload_helper.dart'; +import '../models/app_settings.dart'; + /// Finds and renders image URLs embedded in ordinary text messages. /// /// This is deliberately separate from MeshCore's transmitted channel-image @@ -22,6 +26,41 @@ class MessageUrlImageHelper { @visibleForTesting static http.Client? httpClient; + /// Compatibility facade for the dedicated IPFS upload helper. + static Future uploadImageWithSettings({ + required AppSettings settings, + required Uint8List bytes, + required String fileName, + required String mimeType, + }) { + IpfsUploadHelper.httpClient = httpClient; + return IpfsUploadHelper.uploadImageWithSettings( + settings: settings, + bytes: bytes, + fileName: fileName, + mimeType: mimeType, + ); + } + + static Future uploadImage({ + required Uint8List bytes, + required String fileName, + required String mimeType, + required String uploadEndpoint, + required String uploadApiKey, + String uploadGateway = '', + }) async { + IpfsUploadHelper.httpClient = httpClient; + return IpfsUploadHelper.uploadImage( + bytes: bytes, + fileName: fileName, + mimeType: mimeType, + uploadEndpoint: uploadEndpoint, + uploadApiKey: uploadApiKey, + uploadGateway: uploadGateway, + ); + } + static final RegExp _pyxPattern = RegExp( r'''https?://pyx\.li/\?i=([A-Za-z0-9_-]+)''', caseSensitive: false, @@ -57,7 +96,10 @@ class MessageUrlImageHelper { _imagePattern.hasMatch(text); } - static Future parse(String text) async { + static Future parse( + String text, { + String publicGateway = AppSettings.defaultPublicIpfsGateway, + }) async { final trimmed = text.trim(); if (trimmed.isEmpty) return null; @@ -74,7 +116,9 @@ class MessageUrlImageHelper { final ipfsCidMatch = _ipfsCidPattern.firstMatch(trimmed); if (ipfsCidMatch != null) { final cid = _trimBoundary(ipfsCidMatch.group(1)!); - return 'https://ipfs.io/ipfs/$cid'; + final gateway = normalizeIpfsGateway(publicGateway); + if (gateway.isEmpty) return null; + return '$gateway$cid'; } final ibbMatch = _ibbSharePattern.firstMatch(trimmed); @@ -96,8 +140,11 @@ class MessageUrlImageHelper { return null; } - static Future parseVerified(String text) async { - final imageUrl = await parse(text); + static Future parseVerified( + String text, { + String publicGateway = AppSettings.defaultPublicIpfsGateway, + }) async { + final imageUrl = await parse(text, publicGateway: publicGateway); if (imageUrl == null) return null; final verified = await _verifyImageUrl(imageUrl); @@ -110,20 +157,22 @@ class MessageUrlImageHelper { /// be retried when a message is shown again. static Future parseVerifiedForMessage( String messageId, - String text, - ) { - final cached = _messageImageCache.remove(messageId); + String text, { + String publicGateway = AppSettings.defaultPublicIpfsGateway, + }) { + final cacheKey = '$messageId|$publicGateway'; + final cached = _messageImageCache.remove(cacheKey); if (cached != null) { - _messageImageCache[messageId] = cached; + _messageImageCache[cacheKey] = cached; return cached; } - final parsing = parseVerified(text); - _messageImageCache[messageId] = parsing; + final parsing = parseVerified(text, publicGateway: publicGateway); + _messageImageCache[cacheKey] = parsing; parsing.then((imageUrl) { if (imageUrl == null && - identical(_messageImageCache[messageId], parsing)) { - _messageImageCache.remove(messageId); + identical(_messageImageCache[cacheKey], parsing)) { + _messageImageCache.remove(cacheKey); } else if (imageUrl != null) { while (_messageImageCache.length > _maxMessageImageCacheEntries) { _messageImageCache.remove(_messageImageCache.keys.first); @@ -207,11 +256,13 @@ class MessageUrlImageFutureBuilder extends StatefulWidget { super.key, required this.messageId, required this.text, + required this.publicGateway, required this.builder, }); final String messageId; final String text; + final String publicGateway; final AsyncWidgetBuilder builder; @override @@ -229,6 +280,7 @@ class _MessageUrlImageFutureBuilderState _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( widget.messageId, widget.text, + publicGateway: widget.publicGateway, ); } @@ -239,6 +291,13 @@ class _MessageUrlImageFutureBuilderState _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( widget.messageId, widget.text, + publicGateway: widget.publicGateway, + ); + } else if (oldWidget.publicGateway != widget.publicGateway) { + _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( + widget.messageId, + widget.text, + publicGateway: widget.publicGateway, ); } } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index caa51590..a30412c9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -448,6 +448,20 @@ "appSettings_routeWeightFailureDecrementSubtitle": "Weight removed from a path after failed delivery", "appSettings_maxMessageRetries": "Max Message Retries", "appSettings_maxMessageRetriesSubtitle": "Number of retry attempts before marking a message as failed", + "appSettings_ipfsImageLinks": "IPFS provider configuration", + "appSettings_ipfsImageLinksSubtitle": "Upload for url Images (or Files) via IPFS provider and default gateway to receive", + "appSettings_publicIpfsGateway": "Public gateway", + "appSettings_ipfsGatewayDeactivated": "Deactivated", + "appSettings_ipfsGatewayPinata": "Pinata", + "appSettings_ipfsGatewayFilebase": "Filebase", + "appSettings_ipfsGatewayCustom": "Custom (Kubo)", + "appSettings_uploadIpfsProvider": "Upload provider", + "appSettings_uploadIpfsGateway": "Upload gateway", + "appSettings_uploadIpfsGatewaySubtitle": "Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.", + "appSettings_uploadIpfsEndpoint": "Upload endpoint", + "appSettings_uploadIpfsEndpointSubtitle": "The API endpoint used to upload files", + "appSettings_uploadIpfsApiKey": "Upload API key", + "appSettings_ipfsImageLinksDescription": "Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.", "appSettings_battery": "Battery", "appSettings_batteryChemistry": "Battery Chemistry", "appSettings_batteryChemistryPerDevice": "Set per device ({deviceName})", @@ -910,6 +924,16 @@ "chat_removeGif": "Remove GIF", "chat_cancelReply": "Cancel reply", "chat_sendImageLora": "Send low-res image over radio", + "chat_sendImageIpfs": "Send image or file via IPFS", + "chat_ipfsUploadFailed": "IPFS upload failed: {error}", + "@chat_ipfsUploadFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "chat_ipfsUploadNotConfigured": "Configure an IPFS upload provider in App Settings first.", "chat_imagePickFailed": "Couldn't open that image", "@chat_imagePickFailed": { "description": "Shown when picking or reading a photo to send fails" diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 4b1af121..4f1b928a 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -1924,6 +1924,90 @@ abstract class AppLocalizations { /// **'Number of retry attempts before marking a message as failed'** String get appSettings_maxMessageRetriesSubtitle; + /// No description provided for @appSettings_ipfsImageLinks. + /// + /// In en, this message translates to: + /// **'IPFS provider configuration'** + String get appSettings_ipfsImageLinks; + + /// No description provided for @appSettings_ipfsImageLinksSubtitle. + /// + /// In en, this message translates to: + /// **'Upload for url Images (or Files) via IPFS provider and default gateway to receive'** + String get appSettings_ipfsImageLinksSubtitle; + + /// No description provided for @appSettings_publicIpfsGateway. + /// + /// In en, this message translates to: + /// **'Public gateway'** + String get appSettings_publicIpfsGateway; + + /// No description provided for @appSettings_ipfsGatewayDeactivated. + /// + /// In en, this message translates to: + /// **'Deactivated'** + String get appSettings_ipfsGatewayDeactivated; + + /// No description provided for @appSettings_ipfsGatewayPinata. + /// + /// In en, this message translates to: + /// **'Pinata'** + String get appSettings_ipfsGatewayPinata; + + /// No description provided for @appSettings_ipfsGatewayFilebase. + /// + /// In en, this message translates to: + /// **'Filebase'** + String get appSettings_ipfsGatewayFilebase; + + /// No description provided for @appSettings_ipfsGatewayCustom. + /// + /// In en, this message translates to: + /// **'Custom (Kubo)'** + String get appSettings_ipfsGatewayCustom; + + /// No description provided for @appSettings_uploadIpfsProvider. + /// + /// In en, this message translates to: + /// **'Upload provider'** + String get appSettings_uploadIpfsProvider; + + /// No description provided for @appSettings_uploadIpfsGateway. + /// + /// In en, this message translates to: + /// **'Upload gateway'** + String get appSettings_uploadIpfsGateway; + + /// No description provided for @appSettings_uploadIpfsGatewaySubtitle. + /// + /// In en, this message translates to: + /// **'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'** + String get appSettings_uploadIpfsGatewaySubtitle; + + /// No description provided for @appSettings_uploadIpfsEndpoint. + /// + /// In en, this message translates to: + /// **'Upload endpoint'** + String get appSettings_uploadIpfsEndpoint; + + /// No description provided for @appSettings_uploadIpfsEndpointSubtitle. + /// + /// In en, this message translates to: + /// **'The API endpoint used to upload files'** + String get appSettings_uploadIpfsEndpointSubtitle; + + /// No description provided for @appSettings_uploadIpfsApiKey. + /// + /// In en, this message translates to: + /// **'Upload API key'** + String get appSettings_uploadIpfsApiKey; + + /// No description provided for @appSettings_ipfsImageLinksDescription. + /// + /// In en, this message translates to: + /// **'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'** + String get appSettings_ipfsImageLinksDescription; + /// No description provided for @appSettings_battery. /// /// In en, this message translates to: @@ -3112,6 +3196,24 @@ abstract class AppLocalizations { /// **'Send low-res image over radio'** String get chat_sendImageLora; + /// No description provided for @chat_sendImageIpfs. + /// + /// In en, this message translates to: + /// **'Send image or file via IPFS'** + String get chat_sendImageIpfs; + + /// No description provided for @chat_ipfsUploadFailed. + /// + /// In en, this message translates to: + /// **'IPFS upload failed: {error}'** + String chat_ipfsUploadFailed(String error); + + /// No description provided for @chat_ipfsUploadNotConfigured. + /// + /// In en, this message translates to: + /// **'Configure an IPFS upload provider in App Settings first.'** + String get chat_ipfsUploadNotConfigured; + /// Shown when picking or reading a photo to send fails /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index bb999a01..2cf51388 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1058,6 +1058,52 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Брой опити за повторно изпращане, преди съобщението да бъде маркирано като неуспешно.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Батерия'; @@ -1749,6 +1795,18 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_sendImageLora => 'Изпращане на изображение чрез MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Не мог да откривам та изображин'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 7c099a2a..4917478d 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1053,6 +1053,52 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Anzahl der Versuche, eine Nachricht erneut zu senden, bevor sie als fehlgeschlagen markiert wird.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Akku'; @@ -1748,6 +1794,18 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_sendImageLora => 'Bild über MeshCore senden'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Konnte dieses Bild nicht öffnen.'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index ce4fc6cc..3fb9d784 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1037,6 +1037,52 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Number of retry attempts before marking a message as failed'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Battery'; @@ -1717,6 +1763,18 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_sendImageLora => 'Send low-res image over radio'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Couldn\'t open that image'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 21d23fdd..c67dda31 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1050,6 +1050,52 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Número de intentos de reintento antes de marcar un mensaje como fallido.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batería'; @@ -1744,6 +1790,18 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_sendImageLora => 'Enviar imagen mediante MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'No pude abrir esa imagen'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 94a4133f..3c78016c 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1056,6 +1056,52 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Nombre de tentatives avant de marquer un message comme ayant échoué.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batterie'; @@ -1748,6 +1794,18 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_sendImageLora => 'Envoyer une image via MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Je n\'ai pas pu ouvrir cette image'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index d02c4227..59442375 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1045,6 +1045,52 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Az üzenet sikertelenként való megjelölése előtti újrapróbálkozások száma'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Akkumulátor'; @@ -1738,6 +1784,18 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_sendImageLora => 'Kép küldése MeshCore-on keresztül'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Nem tudtam ezt a fenti fényre kapni'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 877c0975..881a1b64 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1056,6 +1056,52 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Numero di tentativi di riprova prima di considerare un messaggio come fallito.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batteria'; @@ -1748,6 +1794,18 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_sendImageLora => 'Invia immagine tramite MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Non sono riuscito ad aprire quell\'immagine'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 240eea50..7d745b3b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -993,6 +993,52 @@ class AppLocalizationsJa extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => 'メッセージを失敗として扱うまでの再試行回数'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'バッテリー'; @@ -1661,6 +1707,18 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_sendImageLora => 'MeshCore経由で画像を送信'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'その画像を開けませんでした'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index d4b9be2d..f6a74b65 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -997,6 +997,52 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => '메시지를 실패로 처리하기 전 시도 횟수'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => '배터리'; @@ -1666,6 +1712,18 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_sendImageLora => 'MeshCore를 통해 이미지 보내기'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => '그 이미지를 열 수 없었어요.'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index db418ab4..4b65ca26 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1046,6 +1046,52 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Aantal pogingen om een bericht opnieuw te versturen voordat het als mislukt wordt gemarkeerd'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batterij'; @@ -1734,6 +1780,18 @@ class AppLocalizationsNl extends AppLocalizations { String get chat_sendImageLora => 'Afbeelding in lage resolutie via radio verzenden'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Kon die afbeelding niet openen'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index a1959873..c9864fd0 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1062,6 +1062,52 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Liczba prób ponownego wysłania wiadomości przed oznaczaniem jej jako nieudanej'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Bateria'; @@ -1763,6 +1809,18 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_sendImageLora => 'Wyślij obraz przez MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Nie mogłem otworzyć tego obrazu'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index bab9270c..c0954bfe 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1054,6 +1054,52 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Número de tentativas de reenvio antes de classificar uma mensagem como falha.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Bateria'; @@ -1744,6 +1790,18 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_sendImageLora => 'Enviar imagem via MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Não consegui abrir essa imagem'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 4882c690..756e3276 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1059,6 +1059,52 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Количество попыток повторной отправки сообщения перед тем, как пометить его как неудачное.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Батарея'; @@ -1748,6 +1794,18 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_sendImageLora => 'Отправить изображение через MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Не удалось открыть это изображение'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 72213043..b86d8563 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1045,6 +1045,52 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Počet pokusov o odošleť pred označením správy ako neúspešnej'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batéria'; @@ -1736,6 +1782,18 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_sendImageLora => 'Odoslať obrázok cez MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Nesmiela jsem otvoriť tento obrázok'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index d84d6857..423a51c3 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1047,6 +1047,52 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Število poskusov ponovnega poslanja, preden se sporočilo označuje kot neuspešno'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Baterija'; @@ -1735,6 +1781,18 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_sendImageLora => 'Pošlji sliko prek MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Nispeval sem tega ta slik'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index c760c91f..70ed34eb 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1036,6 +1036,52 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Antal försök att skicka om ett meddelande innan det markeras som misslyckat.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batteri'; @@ -1723,6 +1769,18 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chat_sendImageLora => 'Skicka bild via MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Kunde inte öppna bilden'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 72ef4c94..194fffc5 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1049,6 +1049,52 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Кількість спроб повторного відправлення повідомлення перед тим, як позначити його як невдале'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Батарея'; @@ -1738,6 +1784,18 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_sendImageLora => 'Надіслати зображення через MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Неможливо відкрити це изображення'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 88df6c9c..46ffc0ba 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -979,6 +979,52 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => '在将消息标记为失败之前,允许尝试的次数'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => '电池'; @@ -1643,6 +1689,18 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_sendImageLora => '通过 MeshCore 发送图片'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => '无法打开该图片'; diff --git a/lib/main.dart b/lib/main.dart index f5f54751..02550f25 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -132,6 +132,14 @@ void main() async { // Initialize notification service final notificationService = NotificationService(); + notificationService.setPublicIpfsGateway( + appSettingsService.settings.publicIpfsGateway, + ); + appSettingsService.addListener(() { + notificationService.setPublicIpfsGateway( + appSettingsService.settings.publicIpfsGateway, + ); + }); await notificationService.initialize(); await backgroundService.initialize(); backgroundService.setLanguageOverrideProvider( diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index ef954f28..99ef609a 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -3,6 +3,32 @@ import 'translation_support.dart'; enum UnitSystem { metric, imperial } +String normalizeIpfsGateway(String value) { + var gateway = value.trim(); + if (gateway.isEmpty) return gateway; + if (!gateway.startsWith('http://') && !gateway.startsWith('https://')) { + gateway = 'https://$gateway'; + } + gateway = gateway.replaceAll('{cid}', ''); + if (gateway.endsWith('/ipfs')) gateway = '$gateway/'; + if (!gateway.endsWith('/ipfs/')) { + gateway = '${gateway.endsWith('/') ? gateway : '$gateway/'}ipfs/'; + } + return gateway; +} + +String migratePublicIpfsGateway(String? value) { + final gateway = value?.trim(); + if (gateway == null || + gateway == 'https://ipfs.io/ipfs/' || + gateway == 'https://ipfs.io/ipfs' || + gateway == 'https://dweb.link/ipfs/' || + gateway == 'https://dweb.link/ipfs') { + return AppSettings.defaultPublicIpfsGateway; + } + return gateway; +} + extension UnitSystemValue on UnitSystem { String get value { switch (this) { @@ -78,6 +104,7 @@ class Cyr2LatProfile { class AppSettings { static const Object _unset = Object(); static const String stadiaDemo = '51bd0381-4685-4666-bae8-48940f6d77c0'; + static const String defaultPublicIpfsGateway = ''; final bool clearPathOnMaxRetry; final bool mapShowRepeaters; @@ -130,6 +157,10 @@ class AppSettings { final int tcpServerPort; final bool jumpToOldestUnread; final bool imageMessagesEnabled; + final String publicIpfsGateway; + final String uploadIpfsGateway; + final String uploadIpfsEndpoint; + final String uploadIpfsApiKey; /// Whether a received image is decoded as soon as it is reassembled. /// @@ -180,6 +211,10 @@ class AppSettings { return apiKey; } + String get effectiveUploadIpfsGateway { + return uploadIpfsGateway.trim(); + } + bool get usesstadiaDemo => effectiveMapTileApiKey == stadiaDemo; Map get cyr2latCharMap { @@ -239,6 +274,10 @@ class AppSettings { this.tcpServerPort = 0, this.jumpToOldestUnread = false, this.imageMessagesEnabled = false, + this.publicIpfsGateway = defaultPublicIpfsGateway, + this.uploadIpfsGateway = '', + this.uploadIpfsEndpoint = '', + this.uploadIpfsApiKey = '', this.imageProcessAutomatically = false, this.imageCodecEnabled = false, this.imageCodecSelectedModelId, @@ -321,6 +360,10 @@ class AppSettings { 'tcp_server_port': tcpServerPort, 'jump_to_oldest_unread': jumpToOldestUnread, 'image_messages_enabled': imageMessagesEnabled, + 'public_ipfs_gateway': publicIpfsGateway, + 'upload_ipfs_gateway': uploadIpfsGateway, + 'upload_ipfs_endpoint': uploadIpfsEndpoint, + 'upload_ipfs_api_key': uploadIpfsApiKey, 'image_process_automatically': imageProcessAutomatically, 'image_codec_enabled': imageCodecEnabled, 'image_codec_selected_model_id': imageCodecSelectedModelId, @@ -428,6 +471,12 @@ class AppSettings { tcpServerPort: json['tcp_server_port'] as int? ?? 0, jumpToOldestUnread: json['jump_to_oldest_unread'] as bool? ?? false, imageMessagesEnabled: json['image_messages_enabled'] as bool? ?? false, + publicIpfsGateway: migratePublicIpfsGateway( + json['public_ipfs_gateway'] as String?, + ), + uploadIpfsGateway: json['upload_ipfs_gateway'] as String? ?? '', + uploadIpfsEndpoint: json['upload_ipfs_endpoint'] as String? ?? '', + uploadIpfsApiKey: json['upload_ipfs_api_key'] as String? ?? '', imageProcessAutomatically: json['image_process_automatically'] as bool? ?? false, imageCodecEnabled: json['image_codec_enabled'] as bool? ?? false, @@ -548,6 +597,10 @@ class AppSettings { int? tcpServerPort, bool? jumpToOldestUnread, bool? imageMessagesEnabled, + String? publicIpfsGateway, + String? uploadIpfsGateway, + String? uploadIpfsEndpoint, + String? uploadIpfsApiKey, bool? imageProcessAutomatically, bool? imageCodecEnabled, Object? imageCodecSelectedModelId = _unset, @@ -633,6 +686,10 @@ class AppSettings { tcpServerPort: tcpServerPort ?? this.tcpServerPort, jumpToOldestUnread: jumpToOldestUnread ?? this.jumpToOldestUnread, imageMessagesEnabled: imageMessagesEnabled ?? this.imageMessagesEnabled, + publicIpfsGateway: publicIpfsGateway ?? this.publicIpfsGateway, + uploadIpfsGateway: uploadIpfsGateway ?? this.uploadIpfsGateway, + uploadIpfsEndpoint: uploadIpfsEndpoint ?? this.uploadIpfsEndpoint, + uploadIpfsApiKey: uploadIpfsApiKey ?? this.uploadIpfsApiKey, imageProcessAutomatically: imageProcessAutomatically ?? this.imageProcessAutomatically, imageCodecEnabled: imageCodecEnabled ?? this.imageCodecEnabled, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index d32a443b..64325ac4 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -701,6 +701,18 @@ class AppSettingsScreen extends StatelessWidget { ), ], const Divider(height: 1, indent: 16), + ListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + leading: const Icon(Icons.link_outlined, size: 20), + title: Text(context.l10n.appSettings_ipfsImageLinks), + subtitle: Text(context.l10n.appSettings_ipfsImageLinksSubtitle), + trailing: const Icon(Icons.chevron_right, size: 18), + onTap: () => _showIpfsImageLinksDialog(context, settingsService), + ), + const Divider(height: 1, indent: 16), _ScrollIntoViewOnce( enabled: focusImageMessages, child: SwitchListTile( @@ -723,7 +735,6 @@ class AppSettingsScreen extends StatelessWidget { ), ), if (settingsService.settings.imageMessagesEnabled) ...[ - const Divider(height: 1, indent: 16), SwitchListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, @@ -751,6 +762,16 @@ class AppSettingsScreen extends StatelessWidget { } } + void _showIpfsImageLinksDialog( + BuildContext context, + AppSettingsService settingsService, + ) { + showDialog( + context: context, + builder: (_) => _IpfsImageLinksDialog(settingsService: settingsService), + ); + } + /// Model registry for image messages: the download entry point, the /// downloaded weights, and — when the build simply cannot run the codec — /// [ImageCodecService.unavailableReason] instead of a dead download button. @@ -2649,6 +2670,311 @@ class AppSettingsScreen extends StatelessWidget { } } +class _IpfsImageLinksDialog extends StatefulWidget { + const _IpfsImageLinksDialog({required this.settingsService}); + + final AppSettingsService settingsService; + + @override + State<_IpfsImageLinksDialog> createState() => _IpfsImageLinksDialogState(); +} + +class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { + late final TextEditingController _publicController; + late final TextEditingController _uploadGatewayController; + late final TextEditingController _endpointController; + late final TextEditingController _apiKeyController; + late final String _currentApiKey; + late final String _maskedApiKey; + late String _selectedGateway; + late String _selectedUploadProvider; + bool _apiKeyEditing = false; + bool _apiKeyChanged = false; + + @override + void initState() { + super.initState(); + final settings = widget.settingsService.settings; + _publicController = TextEditingController( + text: normalizeIpfsGateway(settings.publicIpfsGateway), + ); + _uploadGatewayController = TextEditingController( + text: normalizeIpfsGateway(settings.uploadIpfsGateway), + ); + _endpointController = TextEditingController( + text: settings.uploadIpfsEndpoint, + ); + _currentApiKey = settings.uploadIpfsApiKey.trim(); + _maskedApiKey = _currentApiKey.isEmpty ? '' : _maskApiKey(_currentApiKey); + _apiKeyController = TextEditingController(text: _maskedApiKey); + _selectedGateway = _gatewayPreset(_publicController.text); + _selectedUploadProvider = _uploadProvider( + _uploadGatewayController.text, + _endpointController.text, + _currentApiKey, + ); + } + + @override + void dispose() { + _publicController.dispose(); + _uploadGatewayController.dispose(); + _endpointController.dispose(); + _apiKeyController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AlertDialog( + title: Text(l10n.appSettings_ipfsImageLinks), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(l10n.appSettings_ipfsImageLinksDescription), + const SizedBox(height: 12), + DropdownButtonFormField( + initialValue: _selectedGateway, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.appSettings_publicIpfsGateway, + ), + items: [ + DropdownMenuItem( + value: 'deactivated', + child: Text(l10n.appSettings_ipfsGatewayDeactivated), + ), + DropdownMenuItem( + value: 'pinata', + child: Text(l10n.appSettings_ipfsGatewayPinata), + ), + DropdownMenuItem( + value: 'filebase', + child: Text(l10n.appSettings_ipfsGatewayFilebase), + ), + DropdownMenuItem( + value: 'custom', + child: Text(l10n.appSettings_ipfsGatewayCustom), + ), + ], + onChanged: _selectGateway, + ), + const SizedBox(height: 10), + TextField( + controller: _publicController, + decoration: InputDecoration( + labelText: l10n.appSettings_publicIpfsGateway, + ), + keyboardType: TextInputType.url, + autocorrect: false, + onChanged: (_) { + if (_selectedGateway != 'custom') { + setState(() => _selectedGateway = 'custom'); + } + }, + ), + const Divider(height: 20), + DropdownButtonFormField( + initialValue: _selectedUploadProvider, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.appSettings_uploadIpfsProvider, + ), + items: [ + DropdownMenuItem( + value: 'pinata', + child: Text(l10n.appSettings_ipfsGatewayPinata), + ), + DropdownMenuItem( + value: 'filebase', + child: Text(l10n.appSettings_ipfsGatewayFilebase), + ), + DropdownMenuItem( + value: 'custom', + child: Text(l10n.appSettings_ipfsGatewayCustom), + ), + DropdownMenuItem( + value: 'deactivated', + child: Text(l10n.appSettings_ipfsGatewayDeactivated), + ), + ], + onChanged: _selectUploadProvider, + ), + const SizedBox(height: 10), + TextField( + controller: _uploadGatewayController, + decoration: InputDecoration( + labelText: l10n.appSettings_uploadIpfsGateway, + helperText: l10n.appSettings_uploadIpfsGatewaySubtitle, + helperMaxLines: 3, + ), + keyboardType: TextInputType.url, + autocorrect: false, + onChanged: (_) => _markCustomUploadProvider(), + ), + const SizedBox(height: 10), + TextField( + controller: _endpointController, + decoration: InputDecoration( + labelText: l10n.appSettings_uploadIpfsEndpoint, + helperText: l10n.appSettings_uploadIpfsEndpointSubtitle, + helperMaxLines: 3, + ), + keyboardType: TextInputType.url, + autocorrect: false, + onChanged: (_) => _markCustomUploadProvider(), + ), + const SizedBox(height: 10), + TextField( + controller: _apiKeyController, + decoration: InputDecoration( + labelText: l10n.appSettings_uploadIpfsApiKey, + ), + autocorrect: false, + enableSuggestions: false, + onTap: () { + if (_apiKeyEditing) return; + setState(() { + _apiKeyEditing = true; + _apiKeyController.clear(); + }); + }, + onChanged: (_) { + _apiKeyChanged = true; + _markCustomUploadProvider(); + }, + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + TextButton(onPressed: _save, child: Text(l10n.common_save)), + ], + ); + } + + void _selectGateway(String? value) { + if (value == null) return; + setState(() { + _selectedGateway = value; + final preset = _gatewayValue(value); + if (preset != null) _publicController.text = preset; + }); + } + + void _selectUploadProvider(String? value) { + if (value == null) return; + setState(() { + _selectedUploadProvider = value; + final preset = _uploadPreset(value); + if (preset != null) { + _uploadGatewayController.text = preset.gateway; + _endpointController.text = preset.endpoint; + if (value == 'deactivated') _apiKeyController.clear(); + } + }); + } + + void _markCustomUploadProvider() { + if (_selectedUploadProvider != 'custom') { + setState(() => _selectedUploadProvider = 'custom'); + } + } + + Future _save() async { + final deactivated = _selectedUploadProvider == 'deactivated'; + await widget.settingsService.setIpfsImageSettings( + publicGateway: _publicController.text, + uploadGateway: deactivated ? '' : _uploadGatewayController.text, + uploadEndpoint: deactivated ? '' : _endpointController.text, + uploadApiKey: deactivated + ? '' + : _apiKeyChanged + ? _apiKeyController.text + : _currentApiKey, + ); + if (mounted) Navigator.pop(context); + } + + String _gatewayPreset(String value) { + if (value.isEmpty) return 'deactivated'; + if (value == 'https://gateway.pinata.cloud/ipfs/' || + value == 'https://gateway.pinata.cloud/ipfs') { + return 'pinata'; + } + if (value == 'https://ipfs.filebase.io/ipfs/' || + value == 'https://ipfs.filebase.io/ipfs') { + return 'filebase'; + } + return 'custom'; + } + + String? _gatewayValue(String preset) { + switch (preset) { + case 'deactivated': + return ''; + case 'pinata': + return 'https://gateway.pinata.cloud/ipfs/'; + case 'filebase': + return 'https://ipfs.filebase.io/ipfs/'; + case 'custom': + return 'http://127.0.0.1:8080/ipfs/'; + default: + return null; + } + } + + String _uploadProvider(String gateway, String endpoint, String apiKey) { + if (gateway.isEmpty && endpoint.isEmpty && apiKey.isEmpty) { + return 'deactivated'; + } + if (gateway == 'https://gateway.pinata.cloud/ipfs/' && + endpoint == 'https://api.pinata.cloud/pinning/pinFileToIPFS') { + return 'pinata'; + } + if (gateway == 'https://ipfs.filebase.io/ipfs/' && + endpoint == 'https://rpc.filebase.io/api/v0/add') { + return 'filebase'; + } + return 'custom'; + } + + ({String gateway, String endpoint})? _uploadPreset(String preset) { + switch (preset) { + case 'pinata': + return ( + gateway: 'https://gateway.pinata.cloud/ipfs/', + endpoint: 'https://api.pinata.cloud/pinning/pinFileToIPFS', + ); + case 'filebase': + return ( + gateway: 'https://ipfs.filebase.io/ipfs/', + endpoint: 'https://rpc.filebase.io/api/v0/add', + ); + case 'custom': + return ( + gateway: 'http://127.0.0.1:8080/ipfs/', + endpoint: 'http://127.0.0.1:5001/api/v0/add', + ); + case 'deactivated': + return (gateway: '', endpoint: ''); + default: + return null; + } + } + + String _maskApiKey(String value) { + if (value.length <= 8) return '********'; + return '${value.substring(0, 4)}...${value.substring(value.length - 4)}'; + } +} + /// Owns the [TextEditingController] for the manual model URL field so it /// survives rebuilds of the parent [Consumer3]. class _TranslationUrlField extends StatefulWidget { diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 7f592dd5..3ec9a4bd 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -6,6 +6,7 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; +import 'package:file_selector/file_selector.dart' as file_selector; import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; @@ -18,6 +19,7 @@ import '../helpers/chat_scroll_controller.dart'; import '../connector/meshcore_protocol.dart'; import '../helpers/cyr2lat.dart'; import '../helpers/gif_helper.dart'; +import '../helpers/ipfs_upload_helper.dart'; import '../helpers/message_url_image_helper.dart'; import '../helpers/path_helper.dart'; import '../helpers/reaction_helper.dart'; @@ -40,7 +42,6 @@ import '../widgets/received_image_message.dart'; import '../widgets/byte_count_input.dart'; import '../widgets/chat_day_separator.dart'; import '../widgets/empty_state.dart'; - import '../widgets/chat_zoom_wrapper.dart'; import '../widgets/emoji_picker.dart'; import '../widgets/gif_message.dart'; @@ -613,6 +614,7 @@ class _ChannelChatScreenState extends State { bool urlImagesEnabled, ) { final settingsService = context.watch(); + final publicIpfsGateway = settingsService.settings.publicIpfsGateway; final enableTracing = settingsService.settings.enableMessageTracing; final regionOnHopsLine = settingsService.settings.regionOnHopsLine; final isOutgoing = message.isOutgoing; @@ -788,6 +790,7 @@ class _ChannelChatScreenState extends State { MessageUrlImageFutureBuilder( messageId: message.messageId, text: message.text, + publicGateway: publicIpfsGateway, builder: (context, snapshot) { final imageAttachment = snapshot.data; @@ -1360,6 +1363,113 @@ class _ChannelChatScreenState extends State { ); } + Future _sendImageViaIpfs() async { + final l10n = context.l10n; + final settings = context.read().settings; + if (settings.uploadIpfsEndpoint.trim().isEmpty) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadNotConfigured), + ); + return; + } + + final file_selector.XFile? file; + try { + file = await file_selector.openFile(); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (file == null) return; + if (!mounted) return; + + final Uint8List bytes; + try { + bytes = await file.readAsBytes(); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (!mounted) return; + if (bytes.isEmpty) { + showDismissibleSnackBar( + context, + content: Text( + l10n.chat_ipfsUploadFailed('The selected file is empty.'), + ), + ); + return; + } + + final String messageUrl; + try { + messageUrl = await IpfsUploadHelper.uploadImageWithSettings( + settings: settings, + bytes: bytes, + fileName: file.name, + mimeType: IpfsUploadHelper.mimeTypeForFileName(file.name), + ); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (!mounted) return; + + final connector = context.read(); + final existingText = _textController.text.trim(); + final combinedText = existingText.isEmpty + ? '$messageUrl ' + : '$messageUrl\n$existingText'; + final maxBytes = maxChannelMessageBytes(connector.selfName); + var messageText = combinedText; + var outboundText = connector.prepareChannelOutboundText( + widget.channel.index, + messageText, + ); + if (utf8.encode(outboundText).length > maxBytes && + existingText.isNotEmpty) { + final originalCharacters = existingText.characters.toList(); + for (var count = originalCharacters.length - 1; count >= 0; count--) { + final shortened = originalCharacters.take(count).join(); + final candidate = '$messageUrl\n$shortened'; + final encoded = connector.prepareChannelOutboundText( + widget.channel.index, + candidate, + ); + if (utf8.encode(encoded).length <= maxBytes) { + messageText = candidate; + outboundText = encoded; + break; + } + } + } + if (utf8.encode(outboundText).length > maxBytes) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_messageTooLong(maxBytes)), + ); + return; + } + _textController.value = TextEditingValue( + text: messageText, + selection: TextSelection.collapsed(offset: messageText.length), + ); + _textFieldFocusNode.requestFocus(); + } + /// Takes no [BuildContext]: it uses the [State]'s own, so the `mounted` /// checks around each `await` are the ones that actually govern it. Future _showImageSendPreview() async { @@ -2110,6 +2220,20 @@ class _ChannelChatScreenState extends State { ), ); } + if (settings.uploadIpfsEndpoint.trim().isNotEmpty) { + items.add( + PopupMenuItem( + value: 'ipfs-image', + child: Row( + children: [ + const Icon(Icons.cloud_upload_outlined), + const SizedBox(width: 12), + Text(context.l10n.chat_sendImageIpfs), + ], + ), + ), + ); + } final selfConnector = context .read(); if (hasShareableLocation( @@ -2159,6 +2283,9 @@ class _ChannelChatScreenState extends State { case 'meshcore-image': _showImageSendPreview(); break; + case 'ipfs-image': + _sendImageViaIpfs(); + break; case 'send-my-location': await _shareMyLocation( context.read(), diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index e5d71c3f..348c61fc 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; +import 'package:file_selector/file_selector.dart' as file_selector; import 'package:provider/provider.dart'; import '../utils/app_logger.dart'; @@ -20,6 +21,7 @@ import '../widgets/message_status_icon.dart'; import '../widgets/empty_state.dart'; import '../helpers/chat_scroll_controller.dart'; import '../helpers/gif_helper.dart'; +import '../helpers/ipfs_upload_helper.dart'; import '../models/channel_message.dart'; import '../models/contact.dart'; import '../l10n/contact_localization.dart'; @@ -507,7 +509,46 @@ class _ChatScreenState extends State { Offset.zero, ancestor: overlay, ); - const menuHeight = 2 * kMinInteractiveDimension + 16; + final items = >[ + PopupMenuItem( + value: 'gif', + child: Row( + children: [ + const Icon(Icons.gif_box), + const SizedBox(width: 12), + Text(context.l10n.chat_sendGif), + ], + ), + ), + ]; + if (settings.uploadIpfsEndpoint.trim().isNotEmpty) { + items.add( + PopupMenuItem( + value: 'ipfs-image', + child: Row( + children: [ + const Icon(Icons.cloud_upload_outlined), + const SizedBox(width: 12), + Text(context.l10n.chat_sendImageIpfs), + ], + ), + ), + ); + } + items.add( + PopupMenuItem( + value: 'send-my-location', + child: Row( + children: [ + const Icon(Icons.my_location), + const SizedBox(width: 12), + Text(context.l10n.chat_shareMyLocation), + ], + ), + ), + ); + final menuHeight = + items.length * kMinInteractiveDimension + 16; final menuTop = (buttonOffset.dy - menuHeight).clamp( 8.0, overlay.size.height, @@ -524,28 +565,7 @@ class _ChatScreenState extends State { final selected = await showMenu( context: menuContext, position: position, - items: [ - PopupMenuItem( - value: 'gif', - child: Row( - children: [ - const Icon(Icons.gif_box), - const SizedBox(width: 12), - Text(context.l10n.chat_sendGif), - ], - ), - ), - PopupMenuItem( - value: 'send-my-location', - child: Row( - children: [ - const Icon(Icons.my_location), - const SizedBox(width: 12), - Text(context.l10n.chat_shareMyLocation), - ], - ), - ), - ], + items: items, ); if (!mounted || !menuContext.mounted) return; if (selected == null) return; @@ -553,6 +573,9 @@ class _ChatScreenState extends State { case 'gif': _showGifPicker(context); break; + case 'ipfs-image': + _sendImageViaIpfs(); + break; case 'send-my-location': await _shareMyLocation( context.read(), @@ -572,6 +595,7 @@ class _ChatScreenState extends State { // No image button here: the image wire format is GRP_DATA, a // channel primitive with no DM equivalent (see the note at the // top of this file). + // IPFS shares a URL as ordinary text instead. Expanded( child: ValueListenableBuilder( valueListenable: _textController, @@ -722,6 +746,112 @@ class _ChatScreenState extends State { ); } + Future _sendImageViaIpfs() async { + final l10n = context.l10n; + final settings = context.read().settings; + if (settings.uploadIpfsEndpoint.trim().isEmpty) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadNotConfigured), + ); + return; + } + + final file_selector.XFile? file; + try { + file = await file_selector.openFile(); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (file == null || !mounted) return; + + final Uint8List bytes; + try { + bytes = await file.readAsBytes(); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (!mounted) return; + if (bytes.isEmpty) { + showDismissibleSnackBar( + context, + content: Text( + l10n.chat_ipfsUploadFailed('The selected file is empty.'), + ), + ); + return; + } + + final String messageUrl; + try { + messageUrl = await IpfsUploadHelper.uploadImageWithSettings( + settings: settings, + bytes: bytes, + fileName: file.name, + mimeType: IpfsUploadHelper.mimeTypeForFileName(file.name), + ); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (!mounted) return; + + final connector = context.read(); + final contact = _resolveContact(connector); + final existingText = _textController.text.trim(); + var messageText = existingText.isEmpty + ? '$messageUrl ' + : '$messageUrl\n$existingText'; + final maxBytes = maxContactMessageBytes(); + var encodedText = connector.prepareContactOutboundText( + contact, + messageText, + ); + if (utf8.encode(encodedText).length > maxBytes && existingText.isNotEmpty) { + final originalCharacters = existingText.characters.toList(); + for (var count = originalCharacters.length - 1; count >= 0; count--) { + final shortened = originalCharacters.take(count).join(); + final candidate = '$messageUrl\n$shortened'; + final candidateEncoded = connector.prepareContactOutboundText( + contact, + candidate, + ); + if (utf8.encode(candidateEncoded).length <= maxBytes) { + messageText = candidate; + encodedText = candidateEncoded; + break; + } + } + } + if (utf8.encode(encodedText).length > maxBytes) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_messageTooLong(maxBytes)), + ); + return; + } + + _textController.value = TextEditingValue( + text: messageText, + selection: TextSelection.collapsed(offset: messageText.length), + ); + _textFieldFocusNode.requestFocus(); + } + Future _showTranslationOptions() async { final settingsService = context.read(); final settings = settingsService.settings; @@ -1502,6 +1632,7 @@ class _MessageBubble extends StatelessWidget { final urlImagesEnabled = context.select( (connector) => connector.isContactUrlImagesEnabled(sourceId), ); + final publicIpfsGateway = settingsService.settings.publicIpfsGateway; // Bubble colors — outgoing uses MeshPalette.me / meBorder / meInk. final bubbleColor = isFailed @@ -1664,6 +1795,7 @@ class _MessageBubble extends StatelessWidget { MessageUrlImageFutureBuilder( messageId: message.messageId, text: message.text, + publicGateway: publicIpfsGateway, builder: (context, snapshot) { final imageAttachment = snapshot.data; diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 5a810588..42f4d33a 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -317,6 +317,24 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(imageMessagesEnabled: value)); } + Future setIpfsImageSettings({ + required String publicGateway, + required String uploadGateway, + required String uploadEndpoint, + required String uploadApiKey, + }) async { + final normalizedPublicGateway = normalizeIpfsGateway(publicGateway); + final normalizedUploadGateway = normalizeIpfsGateway(uploadGateway); + await updateSettings( + _settings.copyWith( + publicIpfsGateway: normalizedPublicGateway, + uploadIpfsGateway: normalizedUploadGateway, + uploadIpfsEndpoint: uploadEndpoint.trim(), + uploadIpfsApiKey: uploadApiKey.trim(), + ), + ); + } + /// See [AppSettings.imageProcessAutomatically]. `main.dart` mirrors this into /// `ReceivedImageStore.processAutomatically` on every settings change; the /// store applies it to future arrivals only, so flipping it does not diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 66963a39..3e457138 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -11,6 +11,7 @@ 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 '../models/app_settings.dart'; import '../storage/prefs_manager.dart'; import '../utils/platform_info.dart'; import 'notification_reply.dart'; @@ -26,6 +27,11 @@ class NotificationService { // Locale for localized notification strings Locale _locale = const Locale('en'); + String _publicIpfsGateway = AppSettings.defaultPublicIpfsGateway; + + void setPublicIpfsGateway(String gateway) { + _publicIpfsGateway = gateway.trim(); + } /// Set the locale for notification strings (call when app locale changes) void setLocale(Locale locale) { @@ -297,7 +303,10 @@ class NotificationService { }) async { if (!urlImagesEnabled) return null; - final imageUrl = await MessageUrlImageHelper.parseVerified(text); + final imageUrl = await MessageUrlImageHelper.parseVerified( + text, + publicGateway: _publicIpfsGateway, + ); if (imageUrl == null) return null; try { diff --git a/test/helpers/message_url_image_helper_test.dart b/test/helpers/message_url_image_helper_test.dart index 11e1b022..35f9a6a2 100644 --- a/test/helpers/message_url_image_helper_test.dart +++ b/test/helpers/message_url_image_helper_test.dart @@ -1,3 +1,5 @@ +import 'dart:typed_data'; + import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; @@ -48,29 +50,94 @@ void main() { ); }); - test('parses direct ipfs cid urls', () async { - final attachment = await MessageUrlImageHelper.parse( - 'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', - ); + test( + 'does not resolve ipfs cid links with the default gateway deactivated', + () async { + expect( + await MessageUrlImageHelper.parse( + 'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ), + isNull, + ); + expect( + await MessageUrlImageHelper.parse( + 'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ), + isNull, + ); + }, + ); - expect(attachment, isNotNull); - expect( - attachment, - 'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', - ); - }); - - test('parses direct ipfs cid urls without double slashes', () async { + test('uses the configured public gateway for direct ipfs cid urls', () async { final attachment = await MessageUrlImageHelper.parse( - 'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + 'ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + publicGateway: 'https://gateway.example.com', ); expect( attachment, - 'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + 'https://gateway.example.com/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', ); }); + test( + 'does not resolve ipfs cid links when the download gateway is empty', + () async { + final attachment = await MessageUrlImageHelper.parse( + 'ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + publicGateway: '', + ); + + expect(attachment, isNull); + }, + ); + + test('does not upload when the upload endpoint is empty', () async { + var requestCount = 0; + MessageUrlImageHelper.httpClient = MockClient((request) async { + requestCount++; + return http.Response('{}', 200); + }); + + await expectLater( + MessageUrlImageHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: '', + uploadApiKey: '', + ), + throwsArgumentError, + ); + expect(requestCount, 0); + }); + + test( + 'uploads and returns an ipfs scheme when upload gateway is empty', + () async { + MessageUrlImageHelper.httpClient = MockClient((request) async { + expect(request.method, 'POST'); + return http.Response( + '{"Hash":"bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly"}', + 200, + ); + }); + + final message = await MessageUrlImageHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: 'http://127.0.0.1:5001/api/v0/add', + uploadApiKey: '', + ); + + expect( + message, + 'ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + ); + }, + ); + test('parses http image urls', () async { final attachment = await MessageUrlImageHelper.parse( 'see this image https://example.com/picture.png?size=large additional text', diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index b96666e3..6cd5dc04 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -443,6 +443,23 @@ void main() { expect(settings.evictDiscoveredContactsEnabled, isFalse); }); + test('public IPFS gateway defaults to deactivated and preserves empty', () { + expect(AppSettings.fromJson({}).publicIpfsGateway, isEmpty); + expect( + AppSettings.fromJson({'public_ipfs_gateway': ''}).publicIpfsGateway, + isEmpty, + ); + }); + + test('empty upload gateway does not fall back to the download gateway', () { + final settings = AppSettings( + publicIpfsGateway: 'https://gateway.example.com/ipfs/', + uploadIpfsGateway: '', + ); + + expect(settings.effectiveUploadIpfsGateway, isEmpty); + }); + test( 'fromJson with missing new fields uses defaults (backward compat)', () { diff --git a/test/services/tcp_transport_service_native_test.dart b/test/services/tcp_transport_service_native_test.dart index 3cb9629c..72edf22e 100644 --- a/test/services/tcp_transport_service_native_test.dart +++ b/test/services/tcp_transport_service_native_test.dart @@ -61,34 +61,30 @@ int _readIntOption(Socket socket, int level, int option) { } void main() { - test( - 'connect enables TCP keepalive with short probe timings', - () async { - final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); - final overrides = _CapturingConnectOverrides(); - final service = TcpTransportService(); - try { - await IOOverrides.runZoned( - () => service.connect( - host: InternetAddress.loopbackIPv4.address, - port: server.port, - ), - socketConnect: overrides.socketConnect, - ); - final socket = overrides.socket!; - // Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5, - // TCP_KEEPCNT 6. - expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3); - } finally { - await service.disconnect(); - await server.close(); - } - }, - skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones', - ); + test('connect enables TCP keepalive with short probe timings', () async { + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final overrides = _CapturingConnectOverrides(); + final service = TcpTransportService(); + try { + await IOOverrides.runZoned( + () => service.connect( + host: InternetAddress.loopbackIPv4.address, + port: server.port, + ), + socketConnect: overrides.socketConnect, + ); + final socket = overrides.socket!; + // Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5, + // TCP_KEEPCNT 6. + expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3); + } finally { + await service.disconnect(); + await server.close(); + } + }, skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones'); test('connect/disconnect updates TCP transport state', () async { final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); diff --git a/untranslated.json b/untranslated.json index 9e26dfee..c4c655a3 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,341 @@ -{} \ No newline at end of file +{ + "bg": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "de": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "es": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "fr": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "hu": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "it": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "ja": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "ko": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "nl": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "pl": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "pt": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "ru": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "sk": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "sl": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "sv": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "uk": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "zh": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ] +} From de6632d70ecb69abe4eef46bbb2c81075c1d88a0 Mon Sep 17 00:00:00 2001 From: ZIER Date: Tue, 13 Oct 2026 11:19:29 +0200 Subject: [PATCH 04/67] fix crash in chat_screen.dart, try to resolve test error. --- lib/connector/meshcore_connector.dart | 16 +++++----- lib/screens/app_settings_screen.dart | 21 +++++++------ lib/screens/chat_screen.dart | 43 +++++++++++++++------------ 3 files changed, 43 insertions(+), 37 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 03b03944..57ef9fc1 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -3794,6 +3794,9 @@ class MeshCoreConnector extends ChangeNotifier { if (pendingAck != null) { _pendingGenericAckQueue.remove(pendingAck); } + if (_activeTransport == MeshCoreTransportType.tcp) { + unawaited(disconnect(manual: false)); + } rethrow; } @@ -5846,17 +5849,16 @@ class MeshCoreConnector extends ChangeNotifier { _findChannelByIndex(index)?.storageId ?? _slotChannelIds[index]; // Delete by setting empty name and zero PSK await sendFrame(buildSetChannelFrame(index, '', Uint8List(16))); + _channelMessages.remove(index); + _processedChannelReactions.remove(index); + // Refresh before clearing history so messages from an in-flight queue sync + // cannot recreate the channel's stored history after it has been deleted. + await getChannels(force: true); // Another slot holding the same PSK keeps the shared history. - final stillHeld = _channels.any( - (channel) => channel.index != index && channel.storageId == channelId, - ); + final stillHeld = _slotChannelIds.containsValue(channelId); if (channelId != null && !stillHeld) { await _clearChannelStorage(channelId); } - _channelMessages.remove(index); - _processedChannelReactions.remove(index); - // Refresh channels after deleting - await getChannels(force: true); } /// Removes everything persisted for [channelId]: messages, settings, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index fd5065e8..16a21dc1 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -675,7 +675,16 @@ class AppSettingsScreen extends StatelessWidget { onChanged: settingsService.setChannelMinHopsCountRepeaters, ), ], - const Divider(height: 1, indent: 16), + ], + ); + } + + Widget _buildImageMessagesContent( + BuildContext context, + AppSettingsService settingsService, + ) { + return Column( + children: [ ListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, @@ -688,16 +697,6 @@ class AppSettingsScreen extends StatelessWidget { onTap: () => _showIpfsImageLinksDialog(context, settingsService), ), const Divider(height: 1, indent: 16), - ], - ); - } - - Widget _buildImageMessagesContent( - BuildContext context, - AppSettingsService settingsService, - ) { - return Column( - children: [ _ScrollIntoViewOnce( enabled: focusImageMessages, child: SwitchListTile( diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index d0c6e9c0..5456ea55 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -507,9 +507,6 @@ class _ChatScreenState extends State { final useEncoder = connector.isContactSmazEnabled(keyHex) || connector.isContactCyr2LatEnabled(keyHex); - final showIpfsAction = context.select( - (s) => s.settings.uploadIpfsEndpoint.trim().isNotEmpty, - ); return ChatComposer( controller: _textController, focusNode: _textFieldFocusNode, @@ -525,24 +522,32 @@ class _ChatScreenState extends State { sendTooltip: context.l10n.chat_sendMessageTo( _resolveContact(connector).name, ), - actionsBuilder: () => [ - ChatComposerAction( - id: 'gif', - icon: Icons.gif_box, - label: context.l10n.chat_sendGif, - ), - if (showIpfsAction) + actionsBuilder: () { + final showIpfsAction = context + .read() + .settings + .uploadIpfsEndpoint + .trim() + .isNotEmpty; + return [ ChatComposerAction( - id: 'ipfs-image', - icon: Icons.cloud_upload_outlined, - label: context.l10n.chat_sendImageIpfs, + id: 'gif', + icon: Icons.gif_box, + label: context.l10n.chat_sendGif, ), - ChatComposerAction( - id: 'send-my-location', - icon: Icons.my_location, - label: context.l10n.chat_shareMyLocation, - ), - ], + if (showIpfsAction) + ChatComposerAction( + id: 'ipfs-image', + icon: Icons.cloud_upload_outlined, + label: context.l10n.chat_sendImageIpfs, + ), + ChatComposerAction( + id: 'send-my-location', + icon: Icons.my_location, + label: context.l10n.chat_shareMyLocation, + ), + ]; + }, onAction: (action) { if (!mounted) return; switch (action) { From 2474389099238cd044f81632d66a830c36a0cdc1 Mon Sep 17 00:00:00 2001 From: just-stuff-tm <133525672+just-stuff-tm@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:07:07 -0400 Subject: [PATCH 05/67] Fix Linux USB open crash and the glibc 2.39 release bundle. BETA-99.0.0 segfaults when a USB companion transmits as soon as the port opens, and the Linux release fails to load on Ubuntu 24.04 and Linux Mint 22 (glibc 2.39). Fixes #600. fl_open starts SerialThread before Dart installs fl_set_callback. A Seeed Wio Tracker L1 sends bytes immediately, and the reader called that null pointer (segfault at ip 0, FlSerial+0x44b8). Vendor MeshEnvy/flserial e1864de under third_party/flserial. That is the 0.3.5 FFI API this app already calls (openPort, setCallback, setByteSize8, setDTR), not official grzesl/flserial 0.7.3. The reader waits until the callback is set, and the port mutexes are initialized before the thread starts. Merging this makes zjs81/meshcore-open the owner of that vendored copy. The release libflserial.so needed GLIBC_2.42 for cfsetispeed and cfsetospeed, so USB discovery failed on glibc 2.39 before the port opened. Bind those symbols at GLIBC_2.2.5 and pass the legacy baud values those symbols expect. 115200 is octal 0010002. glibc 2.42 turned the B* macros into plain numbers, so passing 115200 to the old symbol would select the wrong rate. flutter_onnxruntime 1.9.0 needs libonnxruntime.so.1 from ONNX Runtime 1.28.3. The zip did not ship that file, and the plugin RUNPATH was the build machine's download directory. The loader uses the plugin path for this library. The install copies libonnxruntime.so, .so.1, .so.1.28.3, and libonnxruntime_providers_shared.so into bundle/lib. The plugin build RPATH is $ORIGIN followed by the download directory: $ORIGIN is bundle/lib at runtime, and the download directory is what ld needs while linking. Dropping it makes the release link fail. The executable keeps DT_RPATH $ORIGIN/lib for its own plugins. Checked on Ubuntu 26.04.1 (glibc 2.43) with Flutter 3.47.7. Opening /dev/ttyACM0 at 115200 set both termios2 speeds to 115200 and delivered data after fl_set_callback (last length 402). The built libflserial.so has no GLIBC_2.42 requirement. flutter build linux --release succeeded. With the plugin's absolute build path removed and LD_LIBRARY_PATH unset, ldd resolved libonnxruntime.so.1 from bundle/lib. --- linux/CMakeLists.txt | 47 + pubspec.yaml | 8 +- third_party/flserial/.clang-format | 3 + .../flserial/.github/workflows/flutter.yml | 53 + third_party/flserial/.gitignore | 29 + third_party/flserial/.metadata | 42 + third_party/flserial/.vscode/launch.json | 45 + third_party/flserial/CHANGELOG.md | 49 + third_party/flserial/LICENSE | 21 + third_party/flserial/README.md | 63 + third_party/flserial/analysis_options.yaml | 4 + third_party/flserial/android/.gitignore | 9 + third_party/flserial/android/build.gradle | 66 + third_party/flserial/android/settings.gradle | 1 + .../android/src/main/AndroidManifest.xml | 3 + third_party/flserial/ffigen.yaml | 19 + third_party/flserial/ios/Classes/flserial.c | 3 + third_party/flserial/ios/flserial.podspec | 28 + third_party/flserial/lib/flserial.dart | 452 +++++++ .../lib/flserial_bindings_generated.dart | 216 ++++ .../flserial/lib/flserial_exception.dart | 6 + third_party/flserial/lib/main.dart | 2 + third_party/flserial/linux/CMakeLists.txt | 22 + .../flserial/macos/Classes/flserial.cpp | 377 ++++++ third_party/flserial/macos/Classes/flserial.h | 79 ++ .../macos/Classes/native_libs/include/cglob.h | 104 ++ .../Classes/native_libs/include/ringbuffer.h | 144 +++ .../native_libs/include/serial/impl/unix.h | 221 ++++ .../native_libs/include/serial/impl/win.h | 207 +++ .../native_libs/include/serial/serial.h | 780 +++++++++++ .../native_libs/include/serial/v8stdint.h | 57 + .../Classes/native_libs/include/tinycthread.h | 479 +++++++ .../Classes/native_libs/src/LICENSE_glob | 34 + .../native_libs/src/LICENSE_ringbuffer | 21 + .../Classes/native_libs/src/LICENSE_serial | 7 + .../native_libs/src/LICENSE_tinycthread | 25 + .../macos/Classes/native_libs/src/cglob.c | 908 +++++++++++++ .../src/impl/list_ports/list_ports_linux.cpp | 342 +++++ .../src/impl/list_ports/list_ports_osx.cpp | 286 +++++ .../src/impl/list_ports/list_ports_win.cpp | 152 +++ .../Classes/native_libs/src/impl/unix.cpp | 1087 ++++++++++++++++ .../Classes/native_libs/src/impl/win.cpp | 651 ++++++++++ .../Classes/native_libs/src/ringbuffer.c | 78 ++ .../macos/Classes/native_libs/src/serial.cpp | 432 +++++++ .../Classes/native_libs/src/tinycthread.c | 931 ++++++++++++++ third_party/flserial/macos/flserial.podspec | 27 + third_party/flserial/pubspec.yaml | 80 ++ third_party/flserial/src/CMakeLists.txt | 58 + third_party/flserial/src/flserial.cpp | 391 ++++++ third_party/flserial/src/flserial.def | 11 + third_party/flserial/src/flserial.h | 79 ++ .../flserial/src/native_libs/include/cglob.h | 104 ++ .../src/native_libs/include/ringbuffer.h | 144 +++ .../native_libs/include/serial/impl/unix.h | 221 ++++ .../src/native_libs/include/serial/impl/win.h | 207 +++ .../src/native_libs/include/serial/serial.h | 780 +++++++++++ .../src/native_libs/include/serial/v8stdint.h | 57 + .../src/native_libs/include/tinycthread.h | 485 +++++++ .../flserial/src/native_libs/src/LICENSE_glob | 34 + .../src/native_libs/src/LICENSE_ringbuffer | 21 + .../src/native_libs/src/LICENSE_serial | 7 + .../src/native_libs/src/LICENSE_tinycthread | 25 + .../flserial/src/native_libs/src/cglob.c | 908 +++++++++++++ .../src/impl/list_ports/list_ports_linux.cpp | 342 +++++ .../src/impl/list_ports/list_ports_osx.cpp | 286 +++++ .../src/impl/list_ports/list_ports_win.cpp | 152 +++ .../src/native_libs/src/impl/unix.cpp | 1138 +++++++++++++++++ .../flserial/src/native_libs/src/impl/win.cpp | 651 ++++++++++ .../flserial/src/native_libs/src/ringbuffer.c | 78 ++ .../flserial/src/native_libs/src/serial.cpp | 432 +++++++ .../src/native_libs/src/tinycthread.c | 931 ++++++++++++++ .../flserial/test/lib/flserial_test.dart | 35 + third_party/flserial/windows/.gitignore | 17 + third_party/flserial/windows/CMakeLists.txt | 23 + 74 files changed, 16313 insertions(+), 4 deletions(-) create mode 100644 third_party/flserial/.clang-format create mode 100644 third_party/flserial/.github/workflows/flutter.yml create mode 100644 third_party/flserial/.gitignore create mode 100644 third_party/flserial/.metadata create mode 100644 third_party/flserial/.vscode/launch.json create mode 100644 third_party/flserial/CHANGELOG.md create mode 100644 third_party/flserial/LICENSE create mode 100644 third_party/flserial/README.md create mode 100644 third_party/flserial/analysis_options.yaml create mode 100644 third_party/flserial/android/.gitignore create mode 100644 third_party/flserial/android/build.gradle create mode 100644 third_party/flserial/android/settings.gradle create mode 100644 third_party/flserial/android/src/main/AndroidManifest.xml create mode 100644 third_party/flserial/ffigen.yaml create mode 100644 third_party/flserial/ios/Classes/flserial.c create mode 100644 third_party/flserial/ios/flserial.podspec create mode 100644 third_party/flserial/lib/flserial.dart create mode 100644 third_party/flserial/lib/flserial_bindings_generated.dart create mode 100644 third_party/flserial/lib/flserial_exception.dart create mode 100644 third_party/flserial/lib/main.dart create mode 100644 third_party/flserial/linux/CMakeLists.txt create mode 100644 third_party/flserial/macos/Classes/flserial.cpp create mode 100644 third_party/flserial/macos/Classes/flserial.h create mode 100644 third_party/flserial/macos/Classes/native_libs/include/cglob.h create mode 100644 third_party/flserial/macos/Classes/native_libs/include/ringbuffer.h create mode 100644 third_party/flserial/macos/Classes/native_libs/include/serial/impl/unix.h create mode 100644 third_party/flserial/macos/Classes/native_libs/include/serial/impl/win.h create mode 100644 third_party/flserial/macos/Classes/native_libs/include/serial/serial.h create mode 100644 third_party/flserial/macos/Classes/native_libs/include/serial/v8stdint.h create mode 100644 third_party/flserial/macos/Classes/native_libs/include/tinycthread.h create mode 100644 third_party/flserial/macos/Classes/native_libs/src/LICENSE_glob create mode 100644 third_party/flserial/macos/Classes/native_libs/src/LICENSE_ringbuffer create mode 100644 third_party/flserial/macos/Classes/native_libs/src/LICENSE_serial create mode 100644 third_party/flserial/macos/Classes/native_libs/src/LICENSE_tinycthread create mode 100644 third_party/flserial/macos/Classes/native_libs/src/cglob.c create mode 100644 third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_linux.cpp create mode 100644 third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_osx.cpp create mode 100644 third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_win.cpp create mode 100644 third_party/flserial/macos/Classes/native_libs/src/impl/unix.cpp create mode 100644 third_party/flserial/macos/Classes/native_libs/src/impl/win.cpp create mode 100644 third_party/flserial/macos/Classes/native_libs/src/ringbuffer.c create mode 100644 third_party/flserial/macos/Classes/native_libs/src/serial.cpp create mode 100644 third_party/flserial/macos/Classes/native_libs/src/tinycthread.c create mode 100644 third_party/flserial/macos/flserial.podspec create mode 100644 third_party/flserial/pubspec.yaml create mode 100644 third_party/flserial/src/CMakeLists.txt create mode 100644 third_party/flserial/src/flserial.cpp create mode 100644 third_party/flserial/src/flserial.def create mode 100644 third_party/flserial/src/flserial.h create mode 100644 third_party/flserial/src/native_libs/include/cglob.h create mode 100644 third_party/flserial/src/native_libs/include/ringbuffer.h create mode 100644 third_party/flserial/src/native_libs/include/serial/impl/unix.h create mode 100644 third_party/flserial/src/native_libs/include/serial/impl/win.h create mode 100644 third_party/flserial/src/native_libs/include/serial/serial.h create mode 100644 third_party/flserial/src/native_libs/include/serial/v8stdint.h create mode 100644 third_party/flserial/src/native_libs/include/tinycthread.h create mode 100644 third_party/flserial/src/native_libs/src/LICENSE_glob create mode 100644 third_party/flserial/src/native_libs/src/LICENSE_ringbuffer create mode 100644 third_party/flserial/src/native_libs/src/LICENSE_serial create mode 100644 third_party/flserial/src/native_libs/src/LICENSE_tinycthread create mode 100644 third_party/flserial/src/native_libs/src/cglob.c create mode 100644 third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_linux.cpp create mode 100644 third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_osx.cpp create mode 100644 third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_win.cpp create mode 100644 third_party/flserial/src/native_libs/src/impl/unix.cpp create mode 100644 third_party/flserial/src/native_libs/src/impl/win.cpp create mode 100644 third_party/flserial/src/native_libs/src/ringbuffer.c create mode 100644 third_party/flserial/src/native_libs/src/serial.cpp create mode 100644 third_party/flserial/src/native_libs/src/tinycthread.c create mode 100644 third_party/flserial/test/lib/flserial_test.dart create mode 100644 third_party/flserial/windows/.gitignore create mode 100644 third_party/flserial/windows/CMakeLists.txt diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt index f05acf60..f697e5dc 100644 --- a/linux/CMakeLists.txt +++ b/linux/CMakeLists.txt @@ -82,6 +82,32 @@ if(TARGET flserial) target_compile_definitions(flserial PRIVATE __STDC_NO_THREADS__) endif() +# Issue zjs81/meshcore-open#600: the release zip must contain +# libonnxruntime.so.1 and must not depend on the build machine's absolute +# path. The plugin is linked against that library by absolute path, so CMake +# records the download directory as the plugin RUNPATH, and install(FILES) +# ships that build-tree file unchanged. The loader uses the plugin RUNPATH, +# not the executable RPATH, when resolving the plugin's libonnxruntime.so.1 +# dependency. Keep the download directory so ld can resolve the SONAME while +# linking meshcore_open, and add $ORIGIN so the copy installed next to the +# plugin is found on a machine that does not have this build tree. Do not set +# SKIP_BUILD_RPATH: without the download directory the link fails with +# "libonnxruntime.so.1, needed by libflutter_onnxruntime_plugin.so, not found". +if(TARGET flutter_onnxruntime_plugin) + file(GLOB _onnx_link_libs + "${CMAKE_BINARY_DIR}/plugins/flutter_onnxruntime/onnxruntime/onnxruntime-linux-*/lib/libonnxruntime.so" + "${PROJECT_BINARY_DIR}/plugins/flutter_onnxruntime/onnxruntime/onnxruntime-linux-*/lib/libonnxruntime.so") + if(_onnx_link_libs) + list(GET _onnx_link_libs 0 _onnx_link_lib) + get_filename_component(_onnx_lib_dir "${_onnx_link_lib}" DIRECTORY) + set_target_properties(flutter_onnxruntime_plugin PROPERTIES + BUILD_RPATH "\$ORIGIN;${_onnx_lib_dir}") + endif() +endif() +set_target_properties(${BINARY_NAME} PROPERTIES + INSTALL_RPATH "$ORIGIN/lib") +target_link_options(${BINARY_NAME} PRIVATE "-Wl,--disable-new-dtags") + # === Installation === # By default, "installing" just makes a relocatable bundle in the build @@ -114,6 +140,27 @@ foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) COMPONENT Runtime) endforeach(bundled_library) +# Copy ONNX Runtime under the names the dynamic linker asks for. The plugin +# bundles libonnxruntime.so, which is a symlink; the NEEDED entry is +# libonnxruntime.so.1. +install(CODE " + set(_onnx_roots + \"${CMAKE_BINARY_DIR}/plugins/flutter_onnxruntime/onnxruntime\" + \"${PROJECT_BINARY_DIR}/plugins/flutter_onnxruntime/onnxruntime\") + foreach(_root \${_onnx_roots}) + file(GLOB _onnx_libs + \"\${_root}/onnxruntime-linux-*/lib/libonnxruntime.so*\" + \"\${_root}/onnxruntime-linux-*/lib/libonnxruntime_providers_shared.so\") + foreach(_lib \${_onnx_libs}) + get_filename_component(_name \"\${_lib}\" NAME) + execute_process(COMMAND readlink -f \"\${_lib}\" + OUTPUT_VARIABLE _real OUTPUT_STRIP_TRAILING_WHITESPACE) + execute_process(COMMAND \"${CMAKE_COMMAND}\" -E copy + \"\${_real}\" \"${INSTALL_BUNDLE_LIB_DIR}/\${_name}\") + endforeach() + endforeach() + " COMPONENT Runtime) + # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" diff --git a/pubspec.yaml b/pubspec.yaml index 39df156b..a4d83a73 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -38,11 +38,11 @@ dependencies: # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.8 flutter_blue_plus: ^2.3.14 - # TODO: Switch to official flserial repo once changes are upstreamed + # Vendored from MeshEnvy/flserial e1864de. Linux SerialThread waits + # until fl_set_callback is installed so a port that transmits on open + # does not call a null callback. Switch back upstream once that lands. flserial: - git: - url: https://github.com/MeshEnvy/flserial.git - ref: e1864de9b65cda9656dba804329bdd2890dd5a92 + path: third_party/flserial ffi: ^2.1.3 # calloc.free for flserial's native I/O buffers provider: ^6.1.5+1 shared_preferences: ^2.2.2 diff --git a/third_party/flserial/.clang-format b/third_party/flserial/.clang-format new file mode 100644 index 00000000..64ee9a17 --- /dev/null +++ b/third_party/flserial/.clang-format @@ -0,0 +1,3 @@ +# Disable clang-format for this vendored submodule so that local patches +# are not stomped by editor auto-formatting. +DisableFormat: true diff --git a/third_party/flserial/.github/workflows/flutter.yml b/third_party/flserial/.github/workflows/flutter.yml new file mode 100644 index 00000000..db07f109 --- /dev/null +++ b/third_party/flserial/.github/workflows/flutter.yml @@ -0,0 +1,53 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Flutter + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + - uses: seanmiddleditch/gha-setup-ninja@master + + + - name: Sudo apt update + run: sudo apt update + + - name: Install gtk3 + run: sudo apt-get install libgtk-3-dev + + - name: Install dependencies + run: flutter pub get + + - name: Analyze project source + run: flutter analyze + + - name: Build release + working-directory: ./example + run: flutter build linux --release + + - name: Print Folder Tree + uses: jaywcjlove/github-action-folder-tree@main + id: tree + with: + exclude: "node_modules|dist|.git|.husky" + path: ./ + depth: 10 + + #- name: List files in the repository + # run: ls -lR ${{ github.workspace }}/build/linux + # - name: Run tests + # run: cp ./example/build/linux/x64/release/bundle/lib/libflserial.so ./test/lib/libflserial.so + #- name: Run tests + # run: flutter test diff --git a/third_party/flserial/.gitignore b/third_party/flserial/.gitignore new file mode 100644 index 00000000..ac5aa989 --- /dev/null +++ b/third_party/flserial/.gitignore @@ -0,0 +1,29 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +build/ diff --git a/third_party/flserial/.metadata b/third_party/flserial/.metadata new file mode 100644 index 00000000..3c2a016b --- /dev/null +++ b/third_party/flserial/.metadata @@ -0,0 +1,42 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668" + channel: "stable" + +project_type: plugin_ffi + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: android + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: ios + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: linux + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: macos + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + - platform: windows + create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/third_party/flserial/.vscode/launch.json b/third_party/flserial/.vscode/launch.json new file mode 100644 index 00000000..6461961b --- /dev/null +++ b/third_party/flserial/.vscode/launch.json @@ -0,0 +1,45 @@ +{ + // Użyj funkcji IntelliSense, aby uzyskać informacje o możliwych atrybutach. + // Najedź kursorem, aby wyświetlić opisy istniejących atrybutów. + // Aby uzyskać więcej informacji, odwiedź stronę: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "flserial", + "request": "launch", + "type": "dart" + }, + { + "name": "flserial (profile mode)", + "request": "launch", + "type": "dart", + "flutterMode": "profile" + }, + { + "name": "flserial (release mode)", + "request": "launch", + "type": "dart", + "flutterMode": "release" + }, + { + "name": "example", + "cwd": "example", + "request": "launch", + "type": "dart" + }, + { + "name": "example (profile mode)", + "cwd": "example", + "request": "launch", + "type": "dart", + "flutterMode": "profile" + }, + { + "name": "example (release mode)", + "cwd": "example", + "request": "launch", + "type": "dart", + "flutterMode": "release" + } + ] +} \ No newline at end of file diff --git a/third_party/flserial/CHANGELOG.md b/third_party/flserial/CHANGELOG.md new file mode 100644 index 00000000..e31a4adb --- /dev/null +++ b/third_party/flserial/CHANGELOG.md @@ -0,0 +1,49 @@ +## 0.3.5 +* Add support 16KB Page Size + +## 0.3.4 +* Changelog fix + +## 0.3.3 +* Replace fifo library + +## 0.3.2 +* MacOS support +* Memory allocation fix + +## 0.3.1 +* Update libs + +## 0.3.0 +* Import project to new plugin ffi template +* Few Api changes + +## 0.2.0 +* New event model +* Cleaning up unnecessary libs +* Performance improvements +* Api changes, main functions: + +Stream based events, before: +``` +serial.onSerialData.subscribe( +``` +to: +``` +serial.onSerialData.stream.listen( +``` + +Write serial port, before: +``` +serial.write(data.length, data); +``` +to: +``` +serial.write(data); +``` + +## 0.1.2 +* Android compilation + +## 0.1.1 +* Initial beta version diff --git a/third_party/flserial/LICENSE b/third_party/flserial/LICENSE new file mode 100644 index 00000000..aad987ed --- /dev/null +++ b/third_party/flserial/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Grzegorz Leśniak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/flserial/README.md b/third_party/flserial/README.md new file mode 100644 index 00000000..cae9c4f3 --- /dev/null +++ b/third_party/flserial/README.md @@ -0,0 +1,63 @@ +# flserial +Flutter Serial Port Plugin FFI based on great C library. Useful to communicate with RS232 devices. + +Based on great serial library: https://github.com/wjwwood/serial + +Supported platforms: +- Linux +- Windows +- Android +- MacOS + +Example of usage: + +``` + FlSerial serial = FlSerial(); + serial.init(); + serial.openPort("COM3", 9600); + serial.onSerialData.stream.listen( + (args) { + if (args.len > 0) { + print(args.serial.readList()); + } + }, + ); + + serial.setByteSize8(); + serial.setBitParityNone(); + serial.setStopBits1(); + serial.setFlowControlNone(); + + String msg = "Hello World!"; + var list = msg.codeUnits; + serial.write(Uint8List.fromList(list)); + + serial.closePort(); + serial.free(); + + +``` + + + +MIT License + +Copyright (c) 2024 Grzegorz Leśniak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/flserial/analysis_options.yaml b/third_party/flserial/analysis_options.yaml new file mode 100644 index 00000000..a5744c1c --- /dev/null +++ b/third_party/flserial/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/third_party/flserial/android/.gitignore b/third_party/flserial/android/.gitignore new file mode 100644 index 00000000..161bdcda --- /dev/null +++ b/third_party/flserial/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/third_party/flserial/android/build.gradle b/third_party/flserial/android/build.gradle new file mode 100644 index 00000000..c2859ef5 --- /dev/null +++ b/third_party/flserial/android/build.gradle @@ -0,0 +1,66 @@ +// The Android Gradle Plugin builds the native code with the Android NDK. + +group = "pl.glpro.flserial" +version = "1.0" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + // The Android Gradle Plugin knows how to build native code with the NDK. + classpath("com.android.tools.build:gradle:8.13.0") + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: "com.android.library" + +android { + if (project.android.hasProperty("namespace")) { + namespace = "pl.glpro.flserial" + } + + // Bumping the plugin compileSdk version requires all clients of this plugin + // to bump the version in their app. + compileSdk = 36 + + // Use the NDK version + // declared in /android/app/build.gradle file of the Flutter project. + // Replace it with a version number if this plugin requires a specific NDK version. + // (e.g. ndkVersion "23.1.7779620") + // ndkVersion = android.ndkVersion + ndkVersion = "29.0.14206865" + + // Invoke the shared CMake build with the Android Gradle Plugin. + externalNativeBuild { + cmake { + path = "../src/CMakeLists.txt" + + // The default CMake version for the Android Gradle Plugin is 3.10.2. + // https://developer.android.com/studio/projects/install-ndk#vanilla_cmake + // + // The Flutter tooling requires that developers have CMake 3.10 or later + // installed. You should not increase this version, as doing so will cause + // the plugin to fail to compile for some customers of the plugin. + // version "3.10.2" + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + + defaultConfig { + minSdk = 21 + } +} diff --git a/third_party/flserial/android/settings.gradle b/third_party/flserial/android/settings.gradle new file mode 100644 index 00000000..ea223529 --- /dev/null +++ b/third_party/flserial/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'flserial' diff --git a/third_party/flserial/android/src/main/AndroidManifest.xml b/third_party/flserial/android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..a51915ba --- /dev/null +++ b/third_party/flserial/android/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/third_party/flserial/ffigen.yaml b/third_party/flserial/ffigen.yaml new file mode 100644 index 00000000..31e28c07 --- /dev/null +++ b/third_party/flserial/ffigen.yaml @@ -0,0 +1,19 @@ +# Run with `dart run ffigen --config ffigen.yaml`. +name: FlserialBindings +description: | + Bindings for `src/flserial.h`. + + Regenerate bindings with `dart run ffigen --config ffigen.yaml`. +output: 'lib/flserial_bindings_generated.dart' +headers: + entry-points: + - 'src/flserial.h' + include-directives: + - 'src/flserial.h' +preamble: | + // ignore_for_file: always_specify_types + // ignore_for_file: camel_case_types + // ignore_for_file: non_constant_identifier_names +comments: + style: any + length: full diff --git a/third_party/flserial/ios/Classes/flserial.c b/third_party/flserial/ios/Classes/flserial.c new file mode 100644 index 00000000..56c5e102 --- /dev/null +++ b/third_party/flserial/ios/Classes/flserial.c @@ -0,0 +1,3 @@ +// Relative import to be able to reuse the C sources. +// See the comment in ../flserial.podspec for more information. +#include "../../src/flserial.cp" diff --git a/third_party/flserial/ios/flserial.podspec b/third_party/flserial/ios/flserial.podspec new file mode 100644 index 00000000..006f0d04 --- /dev/null +++ b/third_party/flserial/ios/flserial.podspec @@ -0,0 +1,28 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint flserial.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'flserial' + s.version = '0.0.1' + s.summary = 'A new Flutter FFI plugin project.' + s.description = <<-DESC +A new Flutter FFI plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + + # This will ensure the source files in Classes/ are included in the native + # builds of apps using this FFI plugin. Podspec does not support relative + # paths, so Classes contains a forwarder C file that relatively imports + # `../src/*` so that the C sources can be shared among all target platforms. + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'Flutter' + s.platform = :ios, '12.0' + + # Flutter.framework does not contain a i386 slice. + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } + s.swift_version = '5.0' +end diff --git a/third_party/flserial/lib/flserial.dart b/third_party/flserial/lib/flserial.dart new file mode 100644 index 00000000..2b77d091 --- /dev/null +++ b/third_party/flserial/lib/flserial.dart @@ -0,0 +1,452 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:ffi/ffi.dart'; +import 'package:flserial/flserial_exception.dart'; + +import 'flserial_bindings_generated.dart'; + +const String _libName = 'flserial'; +const int _serialIOBuffLen = 1024 * 8; + +/// The dynamic library in which the symbols for [FlserialBindings] can be found. +final DynamicLibrary dylib = () { + if (Platform.isMacOS || Platform.isIOS) { + return DynamicLibrary.open('$_libName.framework/$_libName'); + } + if (Platform.isAndroid || Platform.isLinux) { + return DynamicLibrary.open('lib$_libName.so'); + } + if (Platform.isWindows) { + return DynamicLibrary.open('$_libName.dll'); + } + throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}'); +}(); + +/// The bindings to the native functions in [_dylib]. +final FlserialBindings bindings = FlserialBindings(dylib); + +/// Native pointer to string conversion +String nativeInt8ToString(Pointer pointer, {bool allowMalformed = true}) { + var ptrName = pointer.cast(); + final ptrNameCodeUnits = pointer.cast(); + var list = ptrNameCodeUnits.asTypedList(ptrName.length); + return utf8.decode(list, allowMalformed: allowMalformed); +} + +/// String conversion to native pointer, memory should be free outside function +Pointer stringToNativeInt8(String str, {Allocator allocator = calloc}) { + final units = utf8.encode(str); + final result = allocator(units.length + 1); + final nativeString = result.asTypedList(units.length + 1); + nativeString.setAll(0, units); + nativeString[units.length] = 0; + + return result.cast(); +} + +/// List conversion to native pointer, memory should be free outside function +Pointer int8ListToPointerInt8( + Uint8List units, + Pointer pointer, { + Allocator allocator = calloc, +}) { + final nativeString = pointer.asTypedList(units.length + 1); //blobBytes + nativeString.setAll(0, units); + nativeString[units.length] = 0; + return pointer.cast(); +} + +Pointer listToPointerDouble(List sample) { + final Pointer pointer = calloc.allocate( + sample.length, + alignment: 8, + ); + final nativeSamples = pointer.asTypedList(sample.length); + nativeSamples.setAll(0, sample); + return pointer.cast(); +} + +/// Native pointer conversion to list +Int8List nativeInt8ToInt8List(Pointer pointer) { + var ptrName = pointer.cast(); + final ptrNameCodeUnits = pointer.cast(); + var list = ptrNameCodeUnits.asTypedList(ptrName.length); + return list; +} + +/// Open serial port status +enum FlOpenStatus { open, closed, error } + +/// Class for incoming data handling +class FlSerialEventArgs { + FlSerialEventArgs(this.serial, this.len, this.cts, this.dsr); + final FlSerial serial; + final int len; + final bool cts, dsr; +} + +/// Main serial wrapper class over ffi +class FlSerial { + int flh = -1; + bool prevCTS = false; + bool prevDSR = false; + var onSerialData = StreamController(); + Pointer serialReadBuff = Pointer.fromAddress(0); + Pointer serialWriteBuff = Pointer.fromAddress(0); + + /// Init should be called at program start, after FlSerial creation + /// Function is used to make array of internal port structs for 16 parallel processing ports + int init() { + return bindings.fl_init(16); + } + + /// Setting callback to native code. Used for incoming data signal + void setCallback(int flh, {required DartflcallbackFunction callback}) { + final nativeCallable = NativeCallable.listener( + callback, + ); + bindings.fl_set_callback(flh, nativeCallable.nativeFunction); + } + + /// Listing serial ports. Platform depend + static List listPorts() { + List list = List.empty(growable: true); + + Allocator allocator = calloc; + var result = allocator(1024); + + for (int i = 0; i < 255; i++) { + int len = bindings.fl_ports(i, 1024, result); + if (len > 0) { + String resultStr = result.cast().toDartString(length: len); + list.add(resultStr); + } else { + break; + } + } + + allocator.free(result); + return list; + } + + /// Internal function for serial port handler checking + int _checkFLH(int handler) { + if (handler >= 0 && handler < MAX_PORT_COUNT) { + return FlError.FL_ERROR_OK; + } + throw FlSerialException(FlError.FL_ERROR_HANDLER, msg: "$handler"); + } + + /// Function for openning serial port + FlOpenStatus openPort(String portname, int baudrate) { + prevCTS = false; + prevDSR = false; + Pointer ptr = stringToNativeInt8(portname); + flh = bindings.fl_open(flh, ptr, baudrate); + calloc.free(ptr); + int error = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1); + int flerror = FlError.FL_ERROR_UNKNOW; + if (error > 0) { + /// error mapping + String msg = "Port open error: $portname"; + switch (error) { + case 1: + case 3: + flerror = FlError.FL_ERROR_PORT_NOT_EXIST; + msg += " port not exist"; + break; + case 2: + flerror = FlError.FL_ERROR_PORT_ALLREADY_OPEN; + msg += " port allready open"; + break; + } + + bindings.fl_close(flh); + flh = -1; + throw FlSerialException(flerror, msg: msg); + } + + onSerialData = StreamController(); + + Allocator allocator = calloc; + serialReadBuff = allocator(_serialIOBuffLen); + serialWriteBuff = allocator(_serialIOBuffLen); + + setCallback( + flh, + callback: (cflh, len) async { + if (len > 0) { + onSerialData.add(FlSerialEventArgs(this, len, prevCTS, prevDSR)); + } + }, + ); + + return isOpen(); + } + + /// Function check is serial port opened + FlOpenStatus isOpen() { + if (flh < 0) { + return FlOpenStatus.closed; + } + + int error = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1); + if (error > 0) { + return FlOpenStatus.error; + } + int nres = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_IS_PORT_OPEN, -1); + if (nres == 0) { + return FlOpenStatus.closed; + } + return FlOpenStatus.open; + } + + /// Get last error message. Return empty string if no error + String getLastError() { + _checkFLH(flh); + + int res = bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_LAST_ERROR, -1); + String strres = ""; + + switch (res) { + case FlError.FL_ERROR_OK: + strres = "0: None"; + break; + case FlError.FL_ERROR_PORT_ALLREADY_OPEN: + strres = "$res: Port allready open"; + break; + case FlError.FL_ERROR_PORT_NOT_EXIST: + strres = "$res: Port not exist"; + break; + default: + strres = "-1: Unknow error"; + break; + } + return strres; + } + + /* + Future _readLineStatus() async { + + _checkFLH(flh); + + bool currCTS = getCTS(); + bool currDSR = getDSR(); + if(currCTS != prevCTS || prevDSR != currDSR) + { + prevCTS = currCTS; + prevDSR = currDSR; + + onSerialData.broadcast(FlSerialEventArgs( + readBuff.length, Uint8List(0), currCTS, currDSR)); + } + return 0; + }*/ + + /// Internal function to read serial data from lower layer with desired len. If no data is present, empty list is returned + Uint8List _readList(int len) { + _checkFLH(flh); + + if (len > _serialIOBuffLen) { + len = _serialIOBuffLen; + } + + int intres = bindings.fl_read(flh, len, serialReadBuff); + + if (intres <= 0) { + return Uint8List(0); + } + + final ptrNameCodeUnits = serialReadBuff.cast(); + var list = ptrNameCodeUnits.asTypedList(intres); + + return list; + } + + /// Read full read bufer from serial port + Uint8List readList() { + _checkFLH(flh); + + return readListLen(1024 * 8); + } + + /// Read desired len from serial port buffer + Uint8List readListLen(int len) { + _checkFLH(flh); + + return _readList(len); + } + + /// Read single byte + int read() { + _checkFLH(flh); + + Uint8List data = _readList(1); + + if (data.isNotEmpty) { + return data.first; + } + return -1; + } + + /// Write list data to serial port + int write(Uint8List data) { + _checkFLH(flh); + + Pointer ptr = int8ListToPointerInt8(data, serialWriteBuff); + int res = bindings.fl_write(flh, data.length, ptr); + + return res; + } + + /// Close serial port and free resources + int closePort() { + _checkFLH(flh); + bindings.fl_close(flh); + onSerialData.close(); + Allocator allocator = calloc; + if (serialReadBuff.value != 0) { + allocator.free(serialReadBuff); + } + if (serialWriteBuff.value != 0) { + allocator.free(serialWriteBuff); + } + flh = -1; + return flh; + } + + /// Uniwersal function to control serial port + int ctrl(int cmd, int value) { + _checkFLH(flh); + return bindings.fl_ctrl(flh, cmd, value); + } + + /// Function set RTS line in serial port + int setRTS(bool value) { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_RTS, value ? 1 : 0); + } + + /// Function set CTS line in serial port + bool getCTS() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_CTS, 0) > 0 ? true : false; + } + + /// Get status of DTR line + int setDTR(bool value) { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_DTR, value ? 1 : 0); + } + + /// Get status of DSR line + bool getDSR() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_DSR, 0) > 0 ? true : false; + } + + /// Set byte size to 5 bits + int setByteSize5() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_5, 0); + } + + /// Set byte size to 6 bits + int setByteSize6() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_6, 0); + } + + /// Set byte size to 7 bits + int setByteSize7() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_7, 0); + } + + /// Set byte size to 8 bits + int setByteSize8() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_BYTESIZE_8, 0); + } + + /// Set bit parity to none + int setBitParityNone() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_NONE, 0); + } + + /// Set bit parity to odd + int setBitParityOdd() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_ODD, 0); + } + + // Set bit parity to even + int setBitParityEven() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_EVEN, 0); + } + + // Set bit parity to mark + int setBitParityMark() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_MARK, 0); + } + + // Set bit parity to space + int setBitParitySpace() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_PARITY_SPACE, 0); + } + + /// Set stop bits to one + int setStopBits1() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_ONE, 0); + } + + /// Set stop bits to one and half + int setStopBits1_5() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE, 0); + } + + /// Set stop bits to two + int setStopBits2() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_STOPBITS_TWO, 0); + } + + /// Disable flow control + int setFlowControlNone() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_NONE, 0); + } + + /// Set hardware flow control + int setFlowControlHardware() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_HARDWARE, 0); + } + + /// Set xon/xoff flow control (software) + int setFlowControlSoftware() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_SET_FLOWCONTROL_SOFTWARE, 0); + } + + /// Waiting for status line change + int setWaitStatusChange() { + _checkFLH(flh); + return bindings.fl_ctrl(flh, FlCtrl.FL_CTRL_GET_STATUS_CHANGE, 0); + } + + /// Free resources. Serial port should not be used after calling this function + int free() { + return bindings.fl_free(); + } +} diff --git a/third_party/flserial/lib/flserial_bindings_generated.dart b/third_party/flserial/lib/flserial_bindings_generated.dart new file mode 100644 index 00000000..a8c22a9d --- /dev/null +++ b/third_party/flserial/lib/flserial_bindings_generated.dart @@ -0,0 +1,216 @@ +// ignore_for_file: always_specify_types +// ignore_for_file: camel_case_types +// ignore_for_file: non_constant_identifier_names + +// AUTO GENERATED FILE, DO NOT EDIT. +// +// Generated by `package:ffigen`. +// ignore_for_file: type=lint +import 'dart:ffi' as ffi; + +/// Bindings for `src/flserial.h`. +/// +/// Regenerate bindings with `dart run ffigen --config ffigen.yaml`. +/// +class FlserialBindings { + /// Holds the symbol lookup function. + final ffi.Pointer Function(String symbolName) + _lookup; + + /// The symbols are looked up in [dynamicLibrary]. + FlserialBindings(ffi.DynamicLibrary dynamicLibrary) + : _lookup = dynamicLibrary.lookup; + + /// The symbols are looked up with [lookup]. + FlserialBindings.fromLookup( + ffi.Pointer Function(String symbolName) + lookup) + : _lookup = lookup; + + int fl_init( + int portCount, + ) { + return _fl_init( + portCount, + ); + } + + late final _fl_initPtr = + _lookup>('fl_init'); + late final _fl_init = _fl_initPtr.asFunction(); + + int fl_set_callback( + int flh, + flcallback cb, + ) { + return _fl_set_callback( + flh, + cb, + ); + } + + late final _fl_set_callbackPtr = + _lookup>( + 'fl_set_callback'); + late final _fl_set_callback = + _fl_set_callbackPtr.asFunction(); + + int fl_ports( + int index, + int buffsize, + ffi.Pointer buff, + ) { + return _fl_ports( + index, + buffsize, + buff, + ); + } + + late final _fl_portsPtr = _lookup< + ffi.NativeFunction< + ffi.Int Function( + ffi.Int, ffi.Int, ffi.Pointer)>>('fl_ports'); + late final _fl_ports = + _fl_portsPtr.asFunction)>(); + + int fl_open( + int flh, + ffi.Pointer portname, + int baudrate, + ) { + return _fl_open( + flh, + portname, + baudrate, + ); + } + + late final _fl_openPtr = _lookup< + ffi.NativeFunction< + ffi.Int Function( + ffi.Int, ffi.Pointer, ffi.Int)>>('fl_open'); + late final _fl_open = + _fl_openPtr.asFunction, int)>(); + + int fl_read( + int flh, + int len, + ffi.Pointer buff, + ) { + return _fl_read( + flh, + len, + buff, + ); + } + + late final _fl_readPtr = _lookup< + ffi.NativeFunction< + ffi.Int Function( + ffi.Int, ffi.Int, ffi.Pointer)>>('fl_read'); + late final _fl_read = + _fl_readPtr.asFunction)>(); + + int fl_write( + int flh, + int len, + ffi.Pointer data, + ) { + return _fl_write( + flh, + len, + data, + ); + } + + late final _fl_writePtr = _lookup< + ffi.NativeFunction< + ffi.Int Function( + ffi.Int, ffi.Int, ffi.Pointer)>>('fl_write'); + late final _fl_write = + _fl_writePtr.asFunction)>(); + + int fl_close( + int flh, + ) { + return _fl_close( + flh, + ); + } + + late final _fl_closePtr = + _lookup>('fl_close'); + late final _fl_close = _fl_closePtr.asFunction(); + + int fl_ctrl( + int flh, + int param, + int value, + ) { + return _fl_ctrl( + flh, + param, + value, + ); + } + + late final _fl_ctrlPtr = _lookup< + ffi.NativeFunction>( + 'fl_ctrl'); + late final _fl_ctrl = _fl_ctrlPtr.asFunction(); + + int fl_free() { + return _fl_free(); + } + + late final _fl_freePtr = + _lookup>('fl_free'); + late final _fl_free = _fl_freePtr.asFunction(); +} + +abstract class FlCtrl { + static const int FL_CTRL_LAST_ERROR = 0; + static const int FL_CTRL_IS_PORT_OPEN = 1; + static const int FL_CTRL_BREAK = 2; + static const int FL_CTRL_SET_RTS = 3; + static const int FL_CTRL_GET_CTS = 4; + static const int FL_CTRL_SET_DTR = 5; + static const int FL_CTRL_GET_DSR = 6; + static const int FL_CTRL_SET_BYTESIZE_5 = 7; + static const int FL_CTRL_SET_BYTESIZE_6 = 8; + static const int FL_CTRL_SET_BYTESIZE_7 = 9; + static const int FL_CTRL_SET_BYTESIZE_8 = 10; + static const int FL_CTRL_SET_PARITY_NONE = 11; + static const int FL_CTRL_SET_PARITY_ODD = 12; + static const int FL_CTRL_SET_PARITY_EVEN = 13; + static const int FL_CTRL_SET_PARITY_MARK = 14; + static const int FL_CTRL_SET_PARITY_SPACE = 15; + static const int FL_CTRL_SET_STOPBITS_ONE = 16; + static const int FL_CTRL_SET_STOPBITS_TWO = 17; + static const int FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE = 18; + static const int FL_CTRL_SET_FLOWCONTROL_NONE = 19; + static const int FL_CTRL_SET_FLOWCONTROL_HARDWARE = 20; + static const int FL_CTRL_SET_FLOWCONTROL_SOFTWARE = 21; + static const int FL_CTRL_GET_STATUS_CHANGE = 22; + static const int FL_CTRL_LAST = 23; +} + +abstract class FlError { + static const int FL_ERROR_OK = 0; + static const int FL_ERROR_UNKNOW = 1; + static const int FL_ERROR_PORT_ALLREADY_OPEN = 2; + static const int FL_ERROR_PORT_NOT_EXIST = 3; + static const int FL_ERROR_IO = 4; + static const int FL_ERROR_HANDLER = 5; + static const int FL_ERROR_LAST = 6; +} + +typedef flcallback = ffi.Pointer>; +typedef flcallbackFunction = ffi.Void Function( + ffi.UnsignedInt, ffi.UnsignedInt); +typedef DartflcallbackFunction = void Function(int, int); + +const int MAX_PORT_NAME_LEN = 512; + +const int MAX_PORT_COUNT = 128; diff --git a/third_party/flserial/lib/flserial_exception.dart b/third_party/flserial/lib/flserial_exception.dart new file mode 100644 index 00000000..a05cbcce --- /dev/null +++ b/third_party/flserial/lib/flserial_exception.dart @@ -0,0 +1,6 @@ +/// Exception class for serial port +class FlSerialException implements Exception { + FlSerialException(this.error, {required this.msg}); + final int error; + final String msg; +} diff --git a/third_party/flserial/lib/main.dart b/third_party/flserial/lib/main.dart new file mode 100644 index 00000000..23f84bc5 --- /dev/null +++ b/third_party/flserial/lib/main.dart @@ -0,0 +1,2 @@ +export 'flserial_exception.dart'; +export 'flserial.dart'; diff --git a/third_party/flserial/linux/CMakeLists.txt b/third_party/flserial/linux/CMakeLists.txt new file mode 100644 index 00000000..1120a7f9 --- /dev/null +++ b/third_party/flserial/linux/CMakeLists.txt @@ -0,0 +1,22 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +# Project-level configuration. +set(PROJECT_NAME "flserial") +project(${PROJECT_NAME} LANGUAGES CXX) + +# Invoke the build for native code shared with the other target platforms. +# This can be changed to accommodate different builds. +add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared") + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(flserial_bundled_libraries + # Defined in ../src/CMakeLists.txt. + # This can be changed to accommodate different builds. + $ + PARENT_SCOPE +) diff --git a/third_party/flserial/macos/Classes/flserial.cpp b/third_party/flserial/macos/Classes/flserial.cpp new file mode 100644 index 00000000..ec30afc7 --- /dev/null +++ b/third_party/flserial/macos/Classes/flserial.cpp @@ -0,0 +1,377 @@ +#include "flserial.h" +#include "native_libs/include/serial/serial.h" +#include "native_libs/include/tinycthread.h" +#include "native_libs/include/ringbuffer.h" +#include + +#define FL_SERIAL_BUFF_LEN (8 * 1024) + +typedef struct _flserial_ +{ + char portname[MAX_PORT_NAME_LEN + 1]; + int baudrate; + serial::Serial *serialport; + enum FlError lasterror; + char lasterrormsg[512]; + thrd_t cthread; + int breakThread; + ring_buffer_t cinfifo; + ring_buffer_t coutfifo; + char inbuff[FL_SERIAL_BUFF_LEN]; + char outbuff[FL_SERIAL_BUFF_LEN]; + mtx_t inFifo_mutex; + mtx_t outFifo_mutex; + flcallback callback; +} FlSerial; + +int SerialThread(void *aArg) +{ + FlSerial *serial = (FlSerial *)aArg; + ring_buffer_size_t res = 0; + uint8_t buff[FL_SERIAL_BUFF_LEN]; + ring_buffer_size_t len = sizeof(buff); + ring_buffer_size_t total = 0; + int isEmpty = 0; + + while (!serial->breakThread) + { + try + { + res = (int)serial->serialport->read((uint8_t *)buff, (size_t)len); + if (res > 0) + { + mtx_lock(&serial->inFifo_mutex); + ring_buffer_queue_arr(&serial->cinfifo, (const char *)buff, res); + mtx_unlock(&serial->inFifo_mutex); + total += res; + if(!serial->serialport->available()){ + serial->callback(0, total); + total = 0; + } else { + continue; + } + } + + mtx_lock(&serial->outFifo_mutex); + res = (ring_buffer_size_t)ring_buffer_dequeue_arr(&serial->coutfifo, (char *)buff, (int)len); + mtx_unlock(&serial->outFifo_mutex); + if (res > 0) { + res = (int)serial->serialport->write((uint8_t*)buff, (size_t)res); + } + + + } + catch (const serial::IOException &ioe) + { + serial->lasterror = FL_ERROR_IO; + strncpy(serial->lasterrormsg , ioe.what(), sizeof(serial->lasterrormsg) - 1); + } + } + + return 0; +} + +FlSerial *flserial_tab[MAX_PORT_COUNT]; +int flserial_count; +int current_port; + +/// Internal helper: close a single slot and null it out. +/// Safe to call with a NULL entry — returns immediately. +/// Sets breakThread=1 then calls thrd_join() so the SerialThread is +/// guaranteed to have exited before this function returns. This is the +/// critical ordering that prevents the Dart NativeCallable from being +/// invoked after the isolate has freed it ("Callback invoked after it has +/// been deleted"). +static void _fl_close_slot(int slot) +{ + FlSerial *port = flserial_tab[slot]; + if (port == NULL) + return; + + port->breakThread = 1; + + try + { + if (port->cthread != 0) + thrd_join(port->cthread, NULL); + + port->serialport->close(); + + mtx_destroy(&port->inFifo_mutex); + mtx_destroy(&port->outFifo_mutex); + } + catch (const std::exception &) + { + } + + delete port->serialport; + port->serialport = NULL; + delete port; + flserial_tab[slot] = NULL; +} + +FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb) +{ + FlSerial *port = flserial_tab[flh]; + port->callback = cb; + return 0; +} + +FFI_PLUGIN_EXPORT int fl_init(int portCount) +{ + if (portCount > MAX_PORT_COUNT) + return 1; + + flserial_count = portCount; + current_port = -1; + + return 0; +} + +FFI_PLUGIN_EXPORT int fl_open(int flh, char *portname, int baudrate) +{ + int porth = flh; + + if (porth < 0) + porth = ++current_port; + + // If a previous FlSerial (and its SerialThread) is alive in this slot, + // join and free it before overwriting. On Dart hot restart the isolate + // dies without calling fl_close(), leaving the old thread running with a + // dangling NativeCallable pointer. Joining here prevents the crash. + _fl_close_slot(porth); + + FlSerial *port = new FlSerial(); + port->breakThread = 0; + + flserial_tab[porth] = port; + + strncpy(port->portname, portname, MAX_PORT_NAME_LEN); + + port->baudrate = baudrate; + port->lasterror = FL_ERROR_OK; + + port->serialport = new serial::Serial(); +#if !defined(__linux__) && !defined(__APPLE__) + port->serialport->setTimeout(serial::Timeout(0, 2, 0, 0, 0)); +#endif // #if defined(__linux__) + port->serialport->setPort(portname); + port->serialport->setBaudrate(baudrate); + + try + { + port->serialport->open(); + + ring_buffer_init(&port->cinfifo, port->inbuff, FL_SERIAL_BUFF_LEN ); + ring_buffer_init(&port->coutfifo, port->outbuff, FL_SERIAL_BUFF_LEN ); + + port->serialport->setBytesize(serial::bytesize_t::eightbits); + port->serialport->setParity(serial::parity_t::parity_none); + port->serialport->setStopbits(serial::stopbits_one); + thrd_create(&port->cthread, SerialThread, (void *)port); + mtx_init(&port->inFifo_mutex, mtx_plain); + mtx_init(&port->outFifo_mutex, mtx_plain); + } + catch (const serial::IOException &ioe) + { + strncpy(port->lasterrormsg, ioe.what(), sizeof(port->lasterrormsg) - 1); + + switch (ioe.getErrorNumber()) + { + case 1: + port->lasterror = FlError::FL_ERROR_PORT_NOT_EXIST; + break; + case 2: + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + break; + default: + port->lasterror = FlError::FL_ERROR_UNKNOW; + break; + } + } + catch (const std::exception) + { + port->lasterror = FlError::FL_ERROR_UNKNOW; + } + + return porth; +} + +FFI_PLUGIN_EXPORT int fl_ports(int index, int buffsize, char *buff) +{ + auto list = serial::list_ports(); + if (serial::list_ports().size() <= index) + { + return 0; + } + else + { + serial::PortInfo info = list[index]; + return snprintf(buff, buffsize, "%s - %s - %s", info.port.c_str(), info.description.c_str(), info.hardware_id.c_str()); + } +} + +FFI_PLUGIN_EXPORT int fl_read(int flh, int len, char *buff) +{ + FlSerial *port = flserial_tab[flh]; + ring_buffer_size_t res = 0; + + char *buf = NULL; + ring_buffer_size_t size = 0; + ring_buffer_size_t read = 0; + + mtx_lock(&port->inFifo_mutex); + read = ring_buffer_dequeue_arr(&port->cinfifo, buff, (ring_buffer_size_t) len); + mtx_unlock(&port->inFifo_mutex); + + return (int)read; +} + +FFI_PLUGIN_EXPORT int fl_write(int flh, int len, char *data) +{ + FlSerial *port = flserial_tab[flh]; + int res = 0; + try + { + mtx_lock(&port->outFifo_mutex); + ring_buffer_queue_arr(&port->coutfifo, data, len); + mtx_unlock(&port->outFifo_mutex); + } + catch (const std::exception &) + { + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + } + + return res; +} + +FFI_PLUGIN_EXPORT int fl_close(int flh) +{ + _fl_close_slot(flh); + return 0; +} + +FFI_PLUGIN_EXPORT int fl_ctrl(int flh, FlCtrl param, int value) +{ + + int result = -1; + FlSerial *port = flserial_tab[flh]; + + try + { + switch (param) + { + case FL_CTRL_IS_PORT_OPEN: + result = port->serialport->isOpen() ? 1 : 0; + break; + case FL_CTRL_LAST_ERROR: + result = port->lasterror; + break; + case FL_CTRL_BREAK: + port->serialport->setBreak(); + result = FL_ERROR_OK; + break; + case FL_CTRL_SET_RTS: + port->serialport->setRTS(value > 0 ? true : false); + result = FL_ERROR_OK; + break; + case FL_CTRL_GET_CTS: + result = port->serialport->getCTS() ? 1 : 0; + break; + case FL_CTRL_SET_DTR: + port->serialport->setDTR(value > 0 ? true : false); + result = FL_ERROR_OK; + break; + case FL_CTRL_GET_DSR: + result = port->serialport->getDSR() ? 1 : 0; + break; + + case FL_CTRL_SET_BYTESIZE_5: + port->serialport->setBytesize(serial::bytesize_t::fivebits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_6: + port->serialport->setBytesize(serial::bytesize_t::sixbits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_7: + port->serialport->setBytesize(serial::bytesize_t::sevenbits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_8: + port->serialport->setBytesize(serial::bytesize_t::eightbits); + result = 1; + break; + case FL_CTRL_SET_PARITY_NONE: + port->serialport->setParity(serial::parity_t::parity_none); + result = 1; + break; + case FL_CTRL_SET_PARITY_ODD: + port->serialport->setParity(serial::parity_t::parity_odd); + result = 1; + break; + case FL_CTRL_SET_PARITY_EVEN: + port->serialport->setParity(serial::parity_t::parity_even); + result = 1; + break; + case FL_CTRL_SET_PARITY_MARK: + port->serialport->setParity(serial::parity_t::parity_mark); + result = 1; + break; + case FL_CTRL_SET_PARITY_SPACE: + port->serialport->setParity(serial::parity_t::parity_space); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_ONE: + port->serialport->setStopbits(serial::stopbits_t::stopbits_one); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_TWO: + port->serialport->setStopbits(serial::stopbits_t::stopbits_two); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE: + port->serialport->setStopbits(serial::stopbits_t::stopbits_one_point_five); + result = 1; + break; + case FL_CTRL_SET_FLOWCONTROL_NONE: + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_none); + result = 1; + break; + case FL_CTRL_SET_FLOWCONTROL_HARDWARE: + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_hardware); + result = 1; + break; + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_software); + result = 1; + case FL_CTRL_SET_FLOWCONTROL_SOFTWARE: + break; + case FL_CTRL_GET_STATUS_CHANGE: + port->serialport->waitForChange(); + result = 1; + break; + + default: + result = -1; + break; + } + } + catch (const std::exception &) + { + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + } + return result; +} + +FFI_PLUGIN_EXPORT int fl_free(void) +{ + // Join every live SerialThread before the Dart isolate tears down on hot + // restart. Without this, threads holding freed NativeCallable pointers + // crash with "Callback invoked after it has been deleted". + for (int i = 0; i < MAX_PORT_COUNT; i++) + _fl_close_slot(i); + + flserial_count = 0; + current_port = -1; + return 0; +} diff --git a/third_party/flserial/macos/Classes/flserial.h b/third_party/flserial/macos/Classes/flserial.h new file mode 100644 index 00000000..edd8b7ef --- /dev/null +++ b/third_party/flserial/macos/Classes/flserial.h @@ -0,0 +1,79 @@ +#include +#include +#include + +#if _WIN32 +#include +#else +#include +#include +#endif + +#if _WIN32 +#define FFI_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FFI_PLUGIN_EXPORT +#endif + + +#define MAX_PORT_FIFO_LEN 128*1024 +#define MAX_PORT_NAME_LEN 512 +#define MAX_PORT_COUNT 16 + +typedef enum FlCtrl { + FL_CTRL_LAST_ERROR, + FL_CTRL_IS_PORT_OPEN, + FL_CTRL_BREAK, + FL_CTRL_SET_RTS, + FL_CTRL_GET_CTS, + FL_CTRL_SET_DTR, + FL_CTRL_GET_DSR, + FL_CTRL_SET_BYTESIZE_5, + FL_CTRL_SET_BYTESIZE_6, + FL_CTRL_SET_BYTESIZE_7, + FL_CTRL_SET_BYTESIZE_8, + FL_CTRL_SET_PARITY_NONE, + FL_CTRL_SET_PARITY_ODD, + FL_CTRL_SET_PARITY_EVEN, + FL_CTRL_SET_PARITY_MARK, + FL_CTRL_SET_PARITY_SPACE, + FL_CTRL_SET_STOPBITS_ONE, + FL_CTRL_SET_STOPBITS_TWO, + FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE, + FL_CTRL_SET_FLOWCONTROL_NONE, + FL_CTRL_SET_FLOWCONTROL_HARDWARE, + FL_CTRL_SET_FLOWCONTROL_SOFTWARE, + FL_CTRL_GET_STATUS_CHANGE, + FL_CTRL_LAST, +} FlCtrl; + +typedef enum FlError { + FL_ERROR_OK, + FL_ERROR_UNKNOW, + FL_ERROR_PORT_ALLREADY_OPEN, + FL_ERROR_PORT_NOT_EXIST, + FL_ERROR_IO, + FL_ERROR_HANDLER, + FL_ERROR_LAST, +} FlError; + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*flcallback)(unsigned int, unsigned int); + +FFI_PLUGIN_EXPORT int fl_init (int portCount); +FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb); +FFI_PLUGIN_EXPORT int fl_ports (int index, int buffsize, char *buff); +FFI_PLUGIN_EXPORT int fl_open (int flh, char *portname, int baudrate); +FFI_PLUGIN_EXPORT int fl_read (int flh, int len, char *buff); +FFI_PLUGIN_EXPORT int fl_write (int flh, int len, char *data); +FFI_PLUGIN_EXPORT int fl_close (int flh); +FFI_PLUGIN_EXPORT int fl_ctrl (int flh, FlCtrl param, int value); +FFI_PLUGIN_EXPORT int fl_free (void); + + +#ifdef __cplusplus +} +#endif diff --git a/third_party/flserial/macos/Classes/native_libs/include/cglob.h b/third_party/flserial/macos/Classes/native_libs/include/cglob.h new file mode 100644 index 00000000..8da8abd9 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/include/cglob.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)glob.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD$ + */ + +#ifndef _GLOB_H_ +#define _GLOB_H_ + +#include +#include + +#ifndef _SIZE_T_DECLARED +typedef size_t __size_t; +#define _SIZE_T_DECLARED +#endif + +struct stat; +typedef struct { + size_t gl_pathc; /* Count of total paths so far. */ + size_t gl_matchc; /* Count of paths matching pattern. */ + size_t gl_offs; /* Reserved at beginning of gl_pathv. */ + int gl_flags; /* Copy of flags parameter to glob. */ + char **gl_pathv; /* List of paths matching pattern. */ + /* Copy of errfunc parameter to glob. */ + int (*gl_errfunc)(const char *, int); + + /* + * Alternate filesystem access methods for glob; replacement + * versions of closedir(3), readdir(3), opendir(3), stat(2) + * and lstat(2). + */ + void (*gl_closedir)(void *); + struct dirent *(*gl_readdir)(void *); + void *(*gl_opendir)(const char *); + int (*gl_lstat)(const char *, struct stat *); + int (*gl_stat)(const char *, struct stat *); +} cglob_t; + + +/* Believed to have been introduced in 1003.2-1992 */ +#define GLOB_APPEND 0x0001 /* Append to output from previous call. */ +#define GLOB_DOOFFS 0x0002 /* Use gl_offs. */ +#define GLOB_ERR 0x0004 /* Return on error. */ +#define GLOB_MARK 0x0008 /* Append / to matching directories. */ +#define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */ +#define GLOB_NOSORT 0x0020 /* Don't sort. */ +#define GLOB_NOESCAPE 0x2000 /* Disable backslash escaping. */ + +/* Error values returned by glob(3) */ +#define GLOB_NOSPACE (-1) /* Malloc call failed. */ +#define GLOB_ABORTED (-2) /* Unignored error. */ +#define GLOB_NOMATCH (-3) /* No match and GLOB_NOCHECK was not set. */ +#define GLOB_NOSYS (-4) /* Obsolete: source comptability only. */ + + + +#define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */ +#define GLOB_BRACE 0x0080 /* Expand braces ala csh. */ +#define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */ +#define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */ +#define GLOB_QUOTE 0x0400 /* Quote special chars with \. */ +#define GLOB_TILDE 0x0800 /* Expand tilde names from the passwd file. */ +#define GLOB_LIMIT 0x1000 /* limit number of returned paths */ + +/* source compatibility, these are the old names */ +#define GLOB_MAXPATH GLOB_LIMIT +#define GLOB_ABEND GLOB_ABORTED + +__BEGIN_DECLS +int cglob(const char *, int, int (*)(const char *, int), cglob_t *); +void cglobfree(cglob_t *); +__END_DECLS + +#endif /* !_GLOB_H_ */ diff --git a/third_party/flserial/macos/Classes/native_libs/include/ringbuffer.h b/third_party/flserial/macos/Classes/native_libs/include/ringbuffer.h new file mode 100644 index 00000000..36da6eb1 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/include/ringbuffer.h @@ -0,0 +1,144 @@ +#include +#include +#include +/** + * @file + * Prototypes and structures for the ring buffer module. + */ + +#ifndef RINGBUFFER_H +#define RINGBUFFER_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define RING_BUFFER_ASSERT(x) assert(x) + +/** + * Checks if the buffer_size is a power of two. + * Due to the design only RING_BUFFER_SIZE-1 items + * can be contained in the buffer. + * buffer_size must be a power of two. +*/ +#define RING_BUFFER_IS_POWER_OF_TWO(buffer_size) ((buffer_size & (buffer_size - 1)) == 0) + +/** + * The type which is used to hold the size + * and the indicies of the buffer. + */ +typedef size_t ring_buffer_size_t; + +/** + * Used as a modulo operator + * as a % b = (a & (b − 1)) + * where \c a is a positive index in the buffer and + * \c b is the (power of two) size of the buffer. + */ +#define RING_BUFFER_MASK(rb) (rb->buffer_mask) + +/** + * Simplifies the use of struct ring_buffer_t. + */ +typedef struct ring_buffer_t ring_buffer_t; + +/** + * Structure which holds a ring buffer. + * The buffer contains a buffer array + * as well as metadata for the ring buffer. + */ +struct ring_buffer_t { + /** Buffer memory. */ + char *buffer; + /** Buffer mask. */ + ring_buffer_size_t buffer_mask; + /** Index of tail. */ + ring_buffer_size_t tail_index; + /** Index of head. */ + ring_buffer_size_t head_index; +}; + +/** + * Initializes the ring buffer pointed to by buffer. + * This function can also be used to empty/reset the buffer. + * The resulting buffer can contain buf_size-1 bytes. + * @param buffer The ring buffer to initialize. + * @param buf The buffer allocated for the ringbuffer. + * @param buf_size The size of the allocated ringbuffer. + */ +void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size); + +/** + * Adds a byte to a ring buffer. + * @param buffer The buffer in which the data should be placed. + * @param data The byte to place. + */ +void ring_buffer_queue(ring_buffer_t *buffer, char data); + +/** + * Adds an array of bytes to a ring buffer. + * @param buffer The buffer in which the data should be placed. + * @param data A pointer to the array of bytes to place in the queue. + * @param size The size of the array. + */ +void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size); + +/** + * Returns the oldest byte in a ring buffer. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the location at which the data should be placed. + * @return 1 if data was returned; 0 otherwise. + */ +uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data); + +/** + * Returns the len oldest bytes in a ring buffer. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the array at which the data should be placed. + * @param len The maximum number of bytes to return. + * @return The number of bytes returned. + */ +ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len); +/** + * Peeks a ring buffer, i.e. returns an element without removing it. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the location at which the data should be placed. + * @param index The index to peek. + * @return 1 if data was returned; 0 otherwise. + */ +uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index); + + +/** + * Returns whether a ring buffer is empty. + * @param buffer The buffer for which it should be returned whether it is empty. + * @return 1 if empty; 0 otherwise. + */ +inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer) { + return (buffer->head_index == buffer->tail_index); +} + +/** + * Returns whether a ring buffer is full. + * @param buffer The buffer for which it should be returned whether it is full. + * @return 1 if full; 0 otherwise. + */ +inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer) { + return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)) == RING_BUFFER_MASK(buffer); +} + +/** + * Returns the number of items in a ring buffer. + * @param buffer The buffer for which the number of items should be returned. + * @return The number of items in the ring buffer. + */ +inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer) { + return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)); +} + +#ifdef __cplusplus +} +#endif + +#endif /* RINGBUFFER_H */ diff --git a/third_party/flserial/macos/Classes/native_libs/include/serial/impl/unix.h b/third_party/flserial/macos/Classes/native_libs/include/serial/impl/unix.h new file mode 100644 index 00000000..02d85e9d --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/include/serial/impl/unix.h @@ -0,0 +1,221 @@ +/*! + * \file serial/impl/unix.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall, John Harrison + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a unix based pimpl for the Serial class. This implementation is + * based off termios.h and uses select for multiplexing the IO ports. + * + */ + +#if !defined(_WIN32) + +#ifndef SERIAL_IMPL_UNIX_H +#define SERIAL_IMPL_UNIX_H + +#include "../../../include/serial/serial.h" + +#include + +namespace serial { + +using std::size_t; +using std::string; +using std::invalid_argument; + +using serial::SerialException; +using serial::IOException; + +class MillisecondTimer { +public: + MillisecondTimer(const uint32_t millis); + int64_t remaining(); + +private: + static timespec timespec_now(); + timespec expiry; +}; + +class serial::Serial::SerialImpl { +public: + SerialImpl (const string &port, + unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, + stopbits_t stopbits, + flowcontrol_t flowcontrol); + + virtual ~SerialImpl (); + + void + open (); + + void + close (); + + bool + isOpen () const; + + size_t + available (); + + bool + waitReadable (uint32_t timeout); + + void + waitByteTimes (size_t count); + + size_t + read (uint8_t *buf, size_t size = 1); + + size_t + write (const uint8_t *data, size_t length); + + void + flush (); + + void + flushInput (); + + void + flushOutput (); + + void + sendBreak (int duration); + + void + setBreak (bool level); + + void + setRTS (bool level); + + void + setDTR (bool level); + + bool + waitForChange (); + + bool + getCTS (); + + bool + getDSR (); + + bool + getRI (); + + bool + getCD (); + + void + setPort (const string &port); + + string + getPort () const; + + void + setTimeout (Timeout &timeout); + + Timeout + getTimeout () const; + + void + setBaudrate (unsigned long baudrate); + + unsigned long + getBaudrate () const; + + void + setBytesize (bytesize_t bytesize); + + bytesize_t + getBytesize () const; + + void + setParity (parity_t parity); + + parity_t + getParity () const; + + void + setStopbits (stopbits_t stopbits); + + stopbits_t + getStopbits () const; + + void + setFlowcontrol (flowcontrol_t flowcontrol); + + flowcontrol_t + getFlowcontrol () const; + + void + readLock (); + + void + readUnlock (); + + void + writeLock (); + + void + writeUnlock (); + +protected: + void reconfigurePort (); + +private: + string port_; // Path to the file descriptor + int fd_; // The current file descriptor + + bool is_open_; + bool xonxoff_; + bool rtscts_; + + Timeout timeout_; // Timeout for read operations + unsigned long baudrate_; // Baudrate + uint32_t byte_time_ns_; // Nanoseconds to transmit/receive a single byte + + parity_t parity_; // Parity + bytesize_t bytesize_; // Size of the bytes + stopbits_t stopbits_; // Stop Bits + flowcontrol_t flowcontrol_; // Flow Control + + // Mutex used to lock the read functions + pthread_mutex_t read_mutex; + // Mutex used to lock the write functions + pthread_mutex_t write_mutex; +}; + +} + +#endif // SERIAL_IMPL_UNIX_H + +#endif // !defined(_WIN32) diff --git a/third_party/flserial/macos/Classes/native_libs/include/serial/impl/win.h b/third_party/flserial/macos/Classes/native_libs/include/serial/impl/win.h new file mode 100644 index 00000000..2c0c6cde --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/include/serial/impl/win.h @@ -0,0 +1,207 @@ +/*! + * \file serial/impl/windows.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall, John Harrison + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a windows implementation of the Serial class interface. + * + */ + +#if defined(_WIN32) + +#ifndef SERIAL_IMPL_WINDOWS_H +#define SERIAL_IMPL_WINDOWS_H + +#include "serial/serial.h" + +#include "windows.h" + +namespace serial { + +using std::string; +using std::wstring; +using std::invalid_argument; + +using serial::SerialException; +using serial::IOException; + +class serial::Serial::SerialImpl { +public: + SerialImpl (const string &port, + unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, + stopbits_t stopbits, + flowcontrol_t flowcontrol); + + virtual ~SerialImpl (); + + void + open (); + + void + close (); + + bool + isOpen () const; + + size_t + available (); + + bool + waitReadable (uint32_t timeout); + + void + waitByteTimes (size_t count); + + size_t + read (uint8_t *buf, size_t size = 1); + + size_t + write (const uint8_t *data, size_t length); + + void + flush (); + + void + flushInput (); + + void + flushOutput (); + + void + sendBreak (int duration); + + void + setBreak (bool level); + + void + setRTS (bool level); + + void + setDTR (bool level); + + bool + waitForChange (); + + bool + getCTS (); + + bool + getDSR (); + + bool + getRI (); + + bool + getCD (); + + void + setPort (const string &port); + + string + getPort () const; + + void + setTimeout (Timeout &timeout); + + Timeout + getTimeout () const; + + void + setBaudrate (unsigned long baudrate); + + unsigned long + getBaudrate () const; + + void + setBytesize (bytesize_t bytesize); + + bytesize_t + getBytesize () const; + + void + setParity (parity_t parity); + + parity_t + getParity () const; + + void + setStopbits (stopbits_t stopbits); + + stopbits_t + getStopbits () const; + + void + setFlowcontrol (flowcontrol_t flowcontrol); + + flowcontrol_t + getFlowcontrol () const; + + void + readLock (); + + void + readUnlock (); + + void + writeLock (); + + void + writeUnlock (); + +protected: + void reconfigurePort (); + +private: + wstring port_; // Path to the file descriptor + HANDLE fd_; + + bool is_open_; + + Timeout timeout_; // Timeout for read operations + unsigned long baudrate_; // Baudrate + + parity_t parity_; // Parity + bytesize_t bytesize_; // Size of the bytes + stopbits_t stopbits_; // Stop Bits + flowcontrol_t flowcontrol_; // Flow Control + + // Mutex used to lock the read functions + HANDLE read_mutex; + // Mutex used to lock the write functions + HANDLE write_mutex; +}; + +} + +#endif // SERIAL_IMPL_WINDOWS_H + +#endif // if defined(_WIN32) diff --git a/third_party/flserial/macos/Classes/native_libs/include/serial/serial.h b/third_party/flserial/macos/Classes/native_libs/include/serial/serial.h new file mode 100644 index 00000000..642febf3 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/include/serial/serial.h @@ -0,0 +1,780 @@ +/*! + * \file serial/serial.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a cross platform interface for interacting with Serial Ports. + */ + +#ifndef SERIAL_H +#define SERIAL_H + +#include +#include +#include +#include +#include +#include +#include +#include "v8stdint.h" + + + +#define THROWEX(exceptionClass, message, errorno) throw exceptionClass(__FILE__, \ +__LINE__, (message), (errorno) ) + +#define THROW(exceptionClass, message) throw exceptionClass(__FILE__, \ +__LINE__, (message) ) + +namespace serial { + +/*! + * Enumeration defines the possible bytesizes for the serial port. + */ +typedef enum { + fivebits = 5, + sixbits = 6, + sevenbits = 7, + eightbits = 8 +} bytesize_t; + +/*! + * Enumeration defines the possible parity types for the serial port. + */ +typedef enum { + parity_none = 0, + parity_odd = 1, + parity_even = 2, + parity_mark = 3, + parity_space = 4 +} parity_t; + +/*! + * Enumeration defines the possible stopbit types for the serial port. + */ +typedef enum { + stopbits_one = 1, + stopbits_two = 2, + stopbits_one_point_five +} stopbits_t; + +/*! + * Enumeration defines the possible flowcontrol types for the serial port. + */ +typedef enum { + flowcontrol_none = 0, + flowcontrol_software, + flowcontrol_hardware +} flowcontrol_t; + +/*! + * Structure for setting the timeout of the serial port, times are + * in milliseconds. + * + * In order to disable the interbyte timeout, set it to Timeout::max(). + */ +struct Timeout { +#ifdef max +# undef max +#endif + static uint32_t max() {return std::numeric_limits::max();} + /*! + * Convenience function to generate Timeout structs using a + * single absolute timeout. + * + * \param timeout A long that defines the time in milliseconds until a + * timeout occurs after a call to read or write is made. + * + * \return Timeout struct that represents this simple timeout provided. + */ + static Timeout simpleTimeout(uint32_t timeout) { + return Timeout(10, timeout, 0, timeout, 0); + } + + /*! Number of milliseconds between bytes received to timeout on. */ + uint32_t inter_byte_timeout; + /*! A constant number of milliseconds to wait after calling read. */ + uint32_t read_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling read. + */ + uint32_t read_timeout_multiplier; + /*! A constant number of milliseconds to wait after calling write. */ + uint32_t write_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling write. + */ + uint32_t write_timeout_multiplier; + + explicit Timeout (uint32_t inter_byte_timeout_=0, + uint32_t read_timeout_constant_=0, + uint32_t read_timeout_multiplier_=0, + uint32_t write_timeout_constant_=0, + uint32_t write_timeout_multiplier_=0) + : inter_byte_timeout(inter_byte_timeout_), + read_timeout_constant(read_timeout_constant_), + read_timeout_multiplier(read_timeout_multiplier_), + write_timeout_constant(write_timeout_constant_), + write_timeout_multiplier(write_timeout_multiplier_) + {} +}; + +/*! + * Class that provides a portable serial port interface. + */ +class Serial { +public: + /*! + * Creates a Serial object and opens the port if a port is specified, + * otherwise it remains closed until serial::Serial::open is called. + * + * \param port A std::string containing the address of the serial port, + * which would be something like 'COM1' on Windows and '/dev/ttyS0' + * on Linux. + * + * \param baudrate An unsigned 32-bit integer that represents the baudrate + * + * \param timeout A serial::Timeout struct that defines the timeout + * conditions for the serial port. \see serial::Timeout + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \param flowcontrol Type of flowcontrol used, default is + * flowcontrol_none, possible values are: flowcontrol_none, + * flowcontrol_software, flowcontrol_hardware + * + * \throw serial::PortNotOpenedException + * \throw serial::IOException + * \throw std::invalid_argument + */ + Serial (const std::string &port = "", + uint32_t baudrate = 9600, + Timeout timeout = Timeout(), + bytesize_t bytesize = eightbits, + parity_t parity = parity_none, + stopbits_t stopbits = stopbits_one, + flowcontrol_t flowcontrol = flowcontrol_none); + + /*! Destructor */ + virtual ~Serial (); + + /*! + * Opens the serial port as long as the port is set and the port isn't + * already open. + * + * If the port is provided to the constructor then an explicit call to open + * is not needed. + * + * \see Serial::Serial + * + * \throw std::invalid_argument + * \throw serial::SerialException + * \throw serial::IOException + */ + void + open (); + + /*! Gets the open status of the serial port. + * + * \return Returns true if the port is open, false otherwise. + */ + bool + isOpen () const; + + /*! Closes the serial port. */ + void + close (); + + /*! Return the number of characters in the buffer. */ + size_t + available (); + + /*! Block until there is serial data to read or read_timeout_constant + * number of milliseconds have elapsed. The return value is true when + * the function exits with the port in a readable state, false otherwise + * (due to timeout or select interruption). */ + bool + waitReadable (); + + /*! Block for a period of time corresponding to the transmission time of + * count characters at present serial settings. This may be used in con- + * junction with waitReadable to read larger blocks of data from the + * port. */ + void + waitByteTimes (size_t count); + + /*! Read a given amount of bytes from the serial port into a given buffer. + * + * The read function will return in one of three cases: + * * The number of requested bytes was read. + * * In this case the number of bytes requested will match the size_t + * returned by read. + * * A timeout occurred, in this case the number of bytes read will not + * match the amount requested, but no exception will be thrown. One of + * two possible timeouts occurred: + * * The inter byte timeout expired, this means that number of + * milliseconds elapsed between receiving bytes from the serial port + * exceeded the inter byte timeout. + * * The total timeout expired, which is calculated by multiplying the + * read timeout multiplier by the number of requested bytes and then + * added to the read timeout constant. If that total number of + * milliseconds elapses after the initial call to read a timeout will + * occur. + * * An exception occurred, in this case an actual exception will be thrown. + * + * \param buffer An uint8_t array of at least the requested size. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (uint8_t *buffer, size_t size); + + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::vector of uint8_t. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::vector &buffer, size_t size = 1); + + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::string. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::string &buffer, size_t size = 1); + + /*! Read a given amount of bytes from the serial port and return a string + * containing the data. + * + * \param size A size_t defining how many bytes to be read. + * + * \return A std::string containing the data read from the port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + read (size_t size = 1); + + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param buffer A std::string reference used to store the data. + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A size_t representing the number of bytes read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + readline (std::string &buffer, size_t size = 65536, std::string eol = "\n"); + + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A std::string containing the line. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + readline (size_t size = 65536, std::string eol = "\n"); + + /*! Reads in multiple lines until the serial port times out. + * + * This requires a timeout > 0 before it can be run. It will read until a + * timeout occurs and return a list of strings. + * + * \param size A maximum length of combined lines, defaults to 65536 (2^16) + * + * \param eol A string to match against for the EOL. + * + * \return A vector containing the lines. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::vector + readlines (size_t size = 65536, std::string eol = "\n"); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \param size A size_t that indicates how many bytes should be written from + * the given data buffer. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const uint8_t *data, size_t size); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::vector &data); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::string &data); + + /*! Sets the serial port identifier. + * + * \param port A const std::string reference containing the address of the + * serial port, which would be something like 'COM1' on Windows and + * '/dev/ttyS0' on Linux. + * + * \throw std::invalid_argument + */ + void + setPort (const std::string &port); + + /*! Gets the serial port identifier. + * + * \see Serial::setPort + * + * \throw std::invalid_argument + */ + std::string + getPort () const; + + /*! Sets the timeout for reads and writes using the Timeout struct. + * + * There are two timeout conditions described here: + * * The inter byte timeout: + * * The inter_byte_timeout component of serial::Timeout defines the + * maximum amount of time, in milliseconds, between receiving bytes on + * the serial port that can pass before a timeout occurs. Setting this + * to zero will prevent inter byte timeouts from occurring. + * * Total time timeout: + * * The constant and multiplier component of this timeout condition, + * for both read and write, are defined in serial::Timeout. This + * timeout occurs if the total time since the read or write call was + * made exceeds the specified time in milliseconds. + * * The limit is defined by multiplying the multiplier component by the + * number of requested bytes and adding that product to the constant + * component. In this way if you want a read call, for example, to + * timeout after exactly one second regardless of the number of bytes + * you asked for then set the read_timeout_constant component of + * serial::Timeout to 1000 and the read_timeout_multiplier to zero. + * This timeout condition can be used in conjunction with the inter + * byte timeout condition with out any problems, timeout will simply + * occur when one of the two timeout conditions is met. This allows + * users to have maximum control over the trade-off between + * responsiveness and efficiency. + * + * Read and write functions will return in one of three cases. When the + * reading or writing is complete, when a timeout occurs, or when an + * exception occurs. + * + * A timeout of 0 enables non-blocking mode. + * + * \param timeout A serial::Timeout struct containing the inter byte + * timeout, and the read and write timeout constants and multipliers. + * + * \see serial::Timeout + */ + void + setTimeout (Timeout &timeout); + + /*! Sets the timeout for reads and writes. */ + void + setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant, + uint32_t read_timeout_multiplier, uint32_t write_timeout_constant, + uint32_t write_timeout_multiplier) + { + Timeout timeout(inter_byte_timeout, read_timeout_constant, + read_timeout_multiplier, write_timeout_constant, + write_timeout_multiplier); + return setTimeout(timeout); + } + + /*! Gets the timeout for reads in seconds. + * + * \return A Timeout struct containing the inter_byte_timeout, and read + * and write timeout constants and multipliers. + * + * \see Serial::setTimeout + */ + Timeout + getTimeout () const; + + /*! Sets the baudrate for the serial port. + * + * Possible baudrates depends on the system but some safe baudrates include: + * 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000, + * 57600, 115200 + * Some other baudrates that are supported by some comports: + * 128000, 153600, 230400, 256000, 460800, 500000, 921600 + * + * \param baudrate An integer that sets the baud rate for the serial port. + * + * \throw std::invalid_argument + */ + void + setBaudrate (uint32_t baudrate); + + /*! Gets the baudrate for the serial port. + * + * \return An integer that sets the baud rate for the serial port. + * + * \see Serial::setBaudrate + * + * \throw std::invalid_argument + */ + uint32_t + getBaudrate () const; + + /*! Sets the bytesize for the serial port. + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \throw std::invalid_argument + */ + void + setBytesize (bytesize_t bytesize); + + /*! Gets the bytesize for the serial port. + * + * \see Serial::setBytesize + * + * \throw std::invalid_argument + */ + bytesize_t + getBytesize () const; + + /*! Sets the parity for the serial port. + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \throw std::invalid_argument + */ + void + setParity (parity_t parity); + + /*! Gets the parity for the serial port. + * + * \see Serial::setParity + * + * \throw std::invalid_argument + */ + parity_t + getParity () const; + + /*! Sets the stopbits for the serial port. + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \throw std::invalid_argument + */ + void + setStopbits (stopbits_t stopbits); + + /*! Gets the stopbits for the serial port. + * + * \see Serial::setStopbits + * + * \throw std::invalid_argument + */ + stopbits_t + getStopbits () const; + + /*! Sets the flow control for the serial port. + * + * \param flowcontrol Type of flowcontrol used, default is flowcontrol_none, + * possible values are: flowcontrol_none, flowcontrol_software, + * flowcontrol_hardware + * + * \throw std::invalid_argument + */ + void + setFlowcontrol (flowcontrol_t flowcontrol); + + /*! Gets the flow control for the serial port. + * + * \see Serial::setFlowcontrol + * + * \throw std::invalid_argument + */ + flowcontrol_t + getFlowcontrol () const; + + /*! Flush the input and output buffers */ + void + flush (); + + /*! Flush only the input buffer */ + void + flushInput (); + + /*! Flush only the output buffer */ + void + flushOutput (); + + /*! Sends the RS-232 break signal. See tcsendbreak(3). */ + void + sendBreak (int duration); + + /*! Set the break condition to a given level. Defaults to true. */ + void + setBreak (bool level = true); + + /*! Set the RTS handshaking line to the given level. Defaults to true. */ + void + setRTS (bool level = true); + + /*! Set the DTR handshaking line to the given level. Defaults to true. */ + void + setDTR (bool level = true); + + /*! + * Blocks until CTS, DSR, RI, CD changes or something interrupts it. + * + * Can throw an exception if an error occurs while waiting. + * You can check the status of CTS, DSR, RI, and CD once this returns. + * Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a + * resolution of less than +-1ms and as good as +-0.2ms. Otherwise a + * polling method is used which can give +-2ms. + * + * \return Returns true if one of the lines changed, false if something else + * occurred. + * + * \throw SerialException + */ + bool + waitForChange (); + + /*! Returns the current status of the CTS line. */ + bool + getCTS (); + + /*! Returns the current status of the DSR line. */ + bool + getDSR (); + + /*! Returns the current status of the RI line. */ + bool + getRI (); + + /*! Returns the current status of the CD line. */ + bool + getCD (); + +private: + // Disable copy constructors + Serial(const Serial&); + Serial& operator=(const Serial&); + + // Pimpl idiom, d_pointer + class SerialImpl; + SerialImpl *pimpl_; + + // Scoped Lock Classes + class ScopedReadLock; + class ScopedWriteLock; + + // Read common function + size_t + read_ (uint8_t *buffer, size_t size); + // Write common function + size_t + write_ (const uint8_t *data, size_t length); + +}; + +class SerialException : public std::exception +{ + // Disable copy constructors + SerialException& operator=(const SerialException&); + std::string e_what_; +public: + SerialException (const char *description) { + std::stringstream ss; + ss << "SerialException " << description << " failed."; + e_what_ = ss.str(); + } + SerialException (const SerialException& other) : e_what_(other.e_what_) {} + virtual ~SerialException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +class IOException : public std::exception +{ + // Disable copy constructors + IOException& operator=(const IOException&); + std::string file_; + int line_; + std::string e_what_; + int errno_; +public: + explicit IOException (std::string file, int line, int errnum = 0) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; +#if defined(_WIN32) && !defined(__MINGW32__) + char error_str [1024]; + strerror_s(error_str, 1024, errnum); +#else + char * error_str = strerror(errnum); +#endif + ss << "IO Exception (" << errno_ << "): " << error_str; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + explicit IOException (std::string file, int line, const char * description, int errnum = 0) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; + ss << "IO Exception: " << description; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + virtual ~IOException() throw() {} + IOException (const IOException& other) : line_(other.line_), e_what_(other.e_what_), errno_(other.errno_) {} + + int getErrorNumber () const { return errno_; } + + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +class PortNotOpenedException : public std::exception +{ + // Disable copy constructors + const PortNotOpenedException& operator=(PortNotOpenedException); + std::string e_what_; +public: + PortNotOpenedException (const char * description) { + std::stringstream ss; + ss << "PortNotOpenedException " << description << " failed."; + e_what_ = ss.str(); + } + PortNotOpenedException (const PortNotOpenedException& other) : e_what_(other.e_what_) {} + virtual ~PortNotOpenedException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +/*! + * Structure that describes a serial device. + */ +struct PortInfo { + + /*! Address of the serial port (this can be passed to the constructor of Serial). */ + std::string port; + + /*! Human readable description of serial device if available. */ + std::string description; + + /*! Hardware ID (e.g. VID:PID of USB serial devices) or "n/a" if not available. */ + std::string hardware_id; + +}; + +/* Lists the serial ports available on the system + * + * Returns a vector of available serial ports, each represented + * by a serial::PortInfo data structure: + * + * \return vector of serial::PortInfo. + */ +std::vector +list_ports(); + +} // namespace serial + +#endif diff --git a/third_party/flserial/macos/Classes/native_libs/include/serial/v8stdint.h b/third_party/flserial/macos/Classes/native_libs/include/serial/v8stdint.h new file mode 100644 index 00000000..f3be96b1 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/include/serial/v8stdint.h @@ -0,0 +1,57 @@ +// This header is from the v8 google project: +// http://code.google.com/p/v8/source/browse/trunk/include/v8stdint.h + +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Load definitions of standard types. + +#ifndef V8STDINT_H_ +#define V8STDINT_H_ + +#include +#include + +#if defined(_WIN32) && !defined(__MINGW32__) + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; // NOLINT +typedef unsigned short uint16_t; // NOLINT +typedef int int32_t; +typedef unsigned int uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +// intptr_t and friends are defined in crtdefs.h through stdio.h. + +#else + +#include + +#endif + +#endif // V8STDINT_H_ diff --git a/third_party/flserial/macos/Classes/native_libs/include/tinycthread.h b/third_party/flserial/macos/Classes/native_libs/include/tinycthread.h new file mode 100644 index 00000000..2fc7f628 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/include/tinycthread.h @@ -0,0 +1,479 @@ +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#ifndef _TINYCTHREAD_H_ +#define _TINYCTHREAD_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @file +* @mainpage TinyCThread API Reference +* +* @section intro_sec Introduction +* TinyCThread is a minimal, portable implementation of basic threading +* classes for C. +* +* They closely mimic the functionality and naming of the C11 standard, and +* should be easily replaceable with the corresponding standard variants. +* +* @section port_sec Portability +* The Win32 variant uses the native Win32 API for implementing the thread +* classes, while for other systems, the POSIX threads API (pthread) is used. +* +* @section misc_sec Miscellaneous +* The following special keywords are available: #_Thread_local. +* +* For more detailed information, browse the different sections of this +* documentation. A good place to start is: +* tinycthread.h. +*/ + +/* Which platform are we on? */ +#if !defined(_TTHREAD_PLATFORM_DEFINED_) + #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) + #define _TTHREAD_WIN32_ + #else + #define _TTHREAD_POSIX_ + #endif + #define _TTHREAD_PLATFORM_DEFINED_ +#endif + +/* Activate some POSIX functionality (e.g. clock_gettime and recursive mutexes) */ +#if defined(_TTHREAD_POSIX_) + #undef _FEATURES_H + #if !defined(_GNU_SOURCE) + #define _GNU_SOURCE + #endif + #if !defined(_POSIX_C_SOURCE) || ((_POSIX_C_SOURCE - 0) < 199309L) + #undef _POSIX_C_SOURCE + #define _POSIX_C_SOURCE 199309L + #endif + #if !defined(_XOPEN_SOURCE) || ((_XOPEN_SOURCE - 0) < 500) + #undef _XOPEN_SOURCE + #define _XOPEN_SOURCE 500 + #endif + #define _XPG6 +#endif + +/* Generic includes */ +#include + +/* Platform specific includes */ +#if defined(_TTHREAD_POSIX_) + #include +#elif defined(_TTHREAD_WIN32_) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #define __UNDEF_LEAN_AND_MEAN + #endif + #include + #ifdef __UNDEF_LEAN_AND_MEAN + #undef WIN32_LEAN_AND_MEAN + #undef __UNDEF_LEAN_AND_MEAN + #endif +#endif + +/* Compiler-specific information */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define TTHREAD_NORETURN _Noreturn +#elif defined(__GNUC__) + #define TTHREAD_NORETURN __attribute__((__noreturn__)) +#else + #define TTHREAD_NORETURN +#endif + +/* If TIME_UTC is missing, provide it and provide a wrapper for + timespec_get. */ +#ifndef TIME_UTC +#define TIME_UTC 1 +#define _TTHREAD_EMULATE_TIMESPEC_GET_ + +#if defined(_TTHREAD_WIN32_) +struct _tthread_timespec { + time_t tv_sec; + long tv_nsec; +}; +#define timespec _tthread_timespec +#endif + +int _tthread_timespec_get(struct timespec *ts, int base); +#define timespec_get _tthread_timespec_get +#endif + +/** TinyCThread version (major number). */ +#define TINYCTHREAD_VERSION_MAJOR 1 +/** TinyCThread version (minor number). */ +#define TINYCTHREAD_VERSION_MINOR 2 +/** TinyCThread version (full version). */ +#define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR) + +/** +* @def _Thread_local +* Thread local storage keyword. +* A variable that is declared with the @c _Thread_local keyword makes the +* value of the variable local to each thread (known as thread-local storage, +* or TLS). Example usage: +* @code +* // This variable is local to each thread. +* _Thread_local int variable; +* @endcode +* @note The @c _Thread_local keyword is a macro that maps to the corresponding +* compiler directive (e.g. @c __declspec(thread)). +* @note This directive is currently not supported on Mac OS X (it will give +* a compiler error), since compile-time TLS is not supported in the Mac OS X +* executable format. Also, some older versions of MinGW (before GCC 4.x) do +* not support this directive, nor does the Tiny C Compiler. +* @hideinitializer +*/ + +#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local) + #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) + #define _Thread_local __thread + #else + #define _Thread_local __declspec(thread) + #endif +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && (((__GNUC__ << 8) | __GNUC_MINOR__) < ((4 << 8) | 9)) + #define _Thread_local __thread +#endif + +/* Macros */ +#if defined(_TTHREAD_WIN32_) +#define TSS_DTOR_ITERATIONS (4) +#else +#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS +#endif + +/* Function return values */ +#define thrd_error 0 /**< The requested operation failed */ +#define thrd_success 1 /**< The requested operation succeeded */ +#define thrd_timedout 2 /**< The time specified in the call was reached without acquiring the requested resource */ +#define thrd_busy 3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */ +#define thrd_nomem 4 /**< The requested operation failed because it was unable to allocate memory */ + +/* Mutex types */ +#define mtx_plain 0 +#define mtx_timed 1 +#define mtx_recursive 2 + +/* Mutex */ +#if defined(_TTHREAD_WIN32_) +typedef struct { + union { + CRITICAL_SECTION cs; /* Critical section handle (used for non-timed mutexes) */ + HANDLE mut; /* Mutex handle (used for timed mutex) */ + } mHandle; /* Mutex handle */ + int mAlreadyLocked; /* TRUE if the mutex is already locked */ + int mRecursive; /* TRUE if the mutex is recursive */ + int mTimed; /* TRUE if the mutex is timed */ +} mtx_t; +#else +typedef pthread_mutex_t mtx_t; +#endif + +/** Create a mutex object. +* @param mtx A mutex object. +* @param type Bit-mask that must have one of the following six values: +* @li @c mtx_plain for a simple non-recursive mutex +* @li @c mtx_timed for a non-recursive mutex that supports timeout +* @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive) +* @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive) +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_init(mtx_t *mtx, int type); + +/** Release any resources used by the given mutex. +* @param mtx A mutex object. +*/ +void mtx_destroy(mtx_t *mtx); + +/** Lock the given mutex. +* Blocks until the given mutex can be locked. If the mutex is non-recursive, and +* the calling thread already has a lock on the mutex, this call will block +* forever. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_lock(mtx_t *mtx); + +/** Lock the given mutex, or block until a specific point in time. +* Blocks until either the given mutex can be locked, or the specified TIME_UTC +* based time. +* @param mtx A mutex object. +* @param ts A UTC based calendar time +* @return @ref The mtx_timedlock function returns thrd_success on success, or +* thrd_timedout if the time specified was reached without acquiring the +* requested resource, or thrd_error if the request could not be honored. +*/ +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts); + +/** Try to lock the given mutex. +* The specified mutex shall support either test and return or timeout. If the +* mutex is already locked, the function returns without blocking. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_busy if the resource +* requested is already in use, or @ref thrd_error if the request could not be +* honored. +*/ +int mtx_trylock(mtx_t *mtx); + +/** Unlock the given mutex. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_unlock(mtx_t *mtx); + +/* Condition variable */ +#if defined(_TTHREAD_WIN32_) +typedef struct { + HANDLE mEvents[2]; /* Signal and broadcast event HANDLEs. */ + unsigned int mWaitersCount; /* Count of the number of waiters. */ + CRITICAL_SECTION mWaitersCountLock; /* Serialize access to mWaitersCount. */ +} cnd_t; +#else +typedef pthread_cond_t cnd_t; +#endif + +/** Create a condition variable object. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_init(cnd_t *cond); + +/** Release any resources used by the given condition variable. +* @param cond A condition variable object. +*/ +void cnd_destroy(cnd_t *cond); + +/** Signal a condition variable. +* Unblocks one of the threads that are blocked on the given condition variable +* at the time of the call. If no threads are blocked on the condition variable +* at the time of the call, the function does nothing and return success. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_signal(cnd_t *cond); + +/** Broadcast a condition variable. +* Unblocks all of the threads that are blocked on the given condition variable +* at the time of the call. If no threads are blocked on the condition variable +* at the time of the call, the function does nothing and return success. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_broadcast(cnd_t *cond); + +/** Wait for a condition variable to become signaled. +* The function atomically unlocks the given mutex and endeavors to block until +* the given condition variable is signaled by a call to cnd_signal or to +* cnd_broadcast. When the calling thread becomes unblocked it locks the mutex +* before it returns. +* @param cond A condition variable object. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_wait(cnd_t *cond, mtx_t *mtx); + +/** Wait for a condition variable to become signaled. +* The function atomically unlocks the given mutex and endeavors to block until +* the given condition variable is signaled by a call to cnd_signal or to +* cnd_broadcast, or until after the specified time. When the calling thread +* becomes unblocked it locks the mutex before it returns. +* @param cond A condition variable object. +* @param mtx A mutex object. +* @param xt A point in time at which the request will time out (absolute time). +* @return @ref thrd_success upon success, or @ref thrd_timeout if the time +* specified in the call was reached without acquiring the requested resource, or +* @ref thrd_error if the request could not be honored. +*/ +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts); + +/* Thread */ +#if defined(_TTHREAD_WIN32_) +typedef HANDLE thrd_t; +#else +typedef pthread_t thrd_t; +#endif + +/** Thread start function. +* Any thread that is started with the @ref thrd_create() function must be +* started through a function of this type. +* @param arg The thread argument (the @c arg argument of the corresponding +* @ref thrd_create() call). +* @return The thread return value, which can be obtained by another thread +* by using the @ref thrd_join() function. +*/ +typedef int (*thrd_start_t)(void *arg); + +/** Create a new thread. +* @param thr Identifier of the newly created thread. +* @param func A function pointer to the function that will be executed in +* the new thread. +* @param arg An argument to the thread function. +* @return @ref thrd_success on success, or @ref thrd_nomem if no memory could +* be allocated for the thread requested, or @ref thrd_error if the request +* could not be honored. +* @note A thread’s identifier may be reused for a different thread once the +* original thread has exited and either been detached or joined to another +* thread. +*/ +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg); + +/** Identify the calling thread. +* @return The identifier of the calling thread. +*/ +thrd_t thrd_current(void); + +/** Dispose of any resources allocated to the thread when that thread exits. + * @return thrd_success, or thrd_error on error +*/ +int thrd_detach(thrd_t thr); + +/** Compare two thread identifiers. +* The function determines if two thread identifiers refer to the same thread. +* @return Zero if the two thread identifiers refer to different threads. +* Otherwise a nonzero value is returned. +*/ +int thrd_equal(thrd_t thr0, thrd_t thr1); + +/** Terminate execution of the calling thread. +* @param res Result code of the calling thread. +*/ +TTHREAD_NORETURN void thrd_exit(int res); + +/** Wait for a thread to terminate. +* The function joins the given thread with the current thread by blocking +* until the other thread has terminated. +* @param thr The thread to join with. +* @param res If this pointer is not NULL, the function will store the result +* code of the given thread in the integer pointed to by @c res. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int thrd_join(thrd_t thr, int *res); + +/** Put the calling thread to sleep. +* Suspend execution of the calling thread. +* @param duration Interval to sleep for +* @param remaining If non-NULL, this parameter will hold the remaining +* time until time_point upon return. This will +* typically be zero, but if the thread was woken up +* by a signal that is not ignored before duration was +* reached @c remaining will hold a positive time. +* @return 0 (zero) on successful sleep, -1 if an interrupt occurred, +* or a negative value if the operation fails. +*/ +int thrd_sleep(const struct timespec *duration, struct timespec *remaining); + +/** Yield execution to another thread. +* Permit other threads to run, even if the current thread would ordinarily +* continue to run. +*/ +void thrd_yield(void); + +/* Thread local storage */ +#if defined(_TTHREAD_WIN32_) +typedef DWORD tss_t; +#else +typedef pthread_key_t tss_t; +#endif + +/** Destructor function for a thread-specific storage. +* @param val The value of the destructed thread-specific storage. +*/ +typedef void (*tss_dtor_t)(void *val); + +/** Create a thread-specific storage. +* @param key The unique key identifier that will be set if the function is +* successful. +* @param dtor Destructor function. This can be NULL. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +* @note On Windows, the @c dtor will definitely be called when +* appropriate for threads created with @ref thrd_create. It will be +* called for other threads in most cases, the possible exception being +* for DLLs loaded with LoadLibraryEx. In order to be certain, you +* should use @ref thrd_create whenever possible. +*/ +int tss_create(tss_t *key, tss_dtor_t dtor); + +/** Delete a thread-specific storage. +* The function releases any resources used by the given thread-specific +* storage. +* @param key The key that shall be deleted. +*/ +void tss_delete(tss_t key); + +/** Get the value for a thread-specific storage. +* @param key The thread-specific storage identifier. +* @return The value for the current thread held in the given thread-specific +* storage. +*/ +void *tss_get(tss_t key); + +/** Set the value for a thread-specific storage. +* @param key The thread-specific storage identifier. +* @param val The value of the thread-specific storage to set for the current +* thread. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int tss_set(tss_t key, void *val); + +#if defined(_TTHREAD_WIN32_) + typedef struct { + LONG volatile status; + CRITICAL_SECTION lock; + } once_flag; + #define ONCE_FLAG_INIT {0,} +#else + #define once_flag pthread_once_t + #define ONCE_FLAG_INIT PTHREAD_ONCE_INIT +#endif + +/** Invoke a callback exactly once + * @param flag Flag used to ensure the callback is invoked exactly + * once. + * @param func Callback to invoke. + */ +#if defined(_TTHREAD_WIN32_) + void call_once(once_flag *flag, void (*func)(void)); +#else + #define call_once(flag,func) pthread_once(flag,func) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _TINYTHREAD_H_ */ diff --git a/third_party/flserial/macos/Classes/native_libs/src/LICENSE_glob b/third_party/flserial/macos/Classes/native_libs/src/LICENSE_glob new file mode 100644 index 00000000..32eeff77 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/LICENSE_glob @@ -0,0 +1,34 @@ +/* + * Natanael Arndt, 2011: removed collate.h dependencies + * (my changes are trivial) + * + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ diff --git a/third_party/flserial/macos/Classes/native_libs/src/LICENSE_ringbuffer b/third_party/flserial/macos/Classes/native_libs/src/LICENSE_ringbuffer new file mode 100644 index 00000000..4e5491e4 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/LICENSE_ringbuffer @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Anders Kalør + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/third_party/flserial/macos/Classes/native_libs/src/LICENSE_serial b/third_party/flserial/macos/Classes/native_libs/src/LICENSE_serial new file mode 100644 index 00000000..bd087f8d --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/LICENSE_serial @@ -0,0 +1,7 @@ +Copyright (c) 2012 William Woodall, John Harrison + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/third_party/flserial/macos/Classes/native_libs/src/LICENSE_tinycthread b/third_party/flserial/macos/Classes/native_libs/src/LICENSE_tinycthread new file mode 100644 index 00000000..d24cfe88 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/LICENSE_tinycthread @@ -0,0 +1,25 @@ + +License +------- + +Copyright (c) 2012 Marcus Geelnard + 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. diff --git a/third_party/flserial/macos/Classes/native_libs/src/cglob.c b/third_party/flserial/macos/Classes/native_libs/src/cglob.c new file mode 100644 index 00000000..7903dbc4 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/cglob.c @@ -0,0 +1,908 @@ +/* + * Natanael Arndt, 2011: removed collate.h dependencies + * (my changes are trivial) + * + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD$"); + +/* + * glob(3) -- a superset of the one defined in POSIX 1003.2. + * + * The [!...] convention to negate a range is supported (SysV, Posix, ksh). + * + * Optional extra services, controlled by flags not defined by POSIX: + * + * GLOB_QUOTE: + * Escaping convention: \ inhibits any special meaning the following + * character might have (except \ at end of string is retained). + * GLOB_MAGCHAR: + * Set in gl_flags if pattern contained a globbing character. + * GLOB_NOMAGIC: + * Same as GLOB_NOCHECK, but it will only append pattern if it did + * not contain any magic characters. [Used in csh style globbing] + * GLOB_ALTDIRFUNC: + * Use alternately specified directory access functions. + * GLOB_TILDE: + * expand ~user/foo to the /home/dir/of/user/foo + * GLOB_BRACE: + * expand {1,2}{a,b} to 1a 1b 2a 2b + * gl_matchc: + * Number of matches in the current invocation of glob. + */ + +/* + * Some notes on multibyte character support: + * 1. Patterns with illegal byte sequences match nothing - even if + * GLOB_NOCHECK is specified. + * 2. Illegal byte sequences in filenames are handled by treating them as + * single-byte characters with a value of the first byte of the sequence + * cast to wchar_t. + * 3. State-dependent encodings are not currently supported. + */ + +#include +#include + +#include +#include +#include +#include "cglob.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define DOLLAR '$' +#define DOT '.' +#define EOS '\0' +#define LBRACKET '[' +#define NOT '!' +#define QUESTION '?' +#define QUOTE '\\' +#define RANGE '-' +#define RBRACKET ']' +#define SEP '/' +#define STAR '*' +#define TILDE '~' +#define UNDERSCORE '_' +#define LBRACE '{' +#define RBRACE '}' +#define SLASH '/' +#define COMMA ',' + +#ifndef DEBUG + +#define M_QUOTE 0x8000000000ULL +#define M_PROTECT 0x4000000000ULL +#define M_MASK 0xffffffffffULL +#define M_CHAR 0x00ffffffffULL + +typedef uint_fast64_t Char; + +#else + +#define M_QUOTE 0x80 +#define M_PROTECT 0x40 +#define M_MASK 0xff +#define M_CHAR 0x7f + +typedef char Char; + +#endif + + +#define CHAR(c) ((Char)((c)&M_CHAR)) +#define META(c) ((Char)((c)|M_QUOTE)) +#define M_ALL META('*') +#define M_END META(']') +#define M_NOT META('!') +#define M_ONE META('?') +#define M_RNG META('-') +#define M_SET META('[') +#define ismeta(c) (((c)&M_QUOTE) != 0) + + +static int compare(const void *, const void *); +static int g_Ctoc(const Char *, char *, size_t); +static int g_lstat(Char *, struct stat *, cglob_t *); +static DIR *g_opendir(Char *, cglob_t *); +static const Char *g_strchr(const Char *, wchar_t); +#ifdef notdef +static Char *g_strcat(Char *, const Char *); +#endif +static int g_stat(Char *, struct stat *, cglob_t *); +static int glob0(const Char *, cglob_t *, size_t *); +static int glob1(Char *, cglob_t *, size_t *); +static int glob2(Char *, Char *, Char *, Char *, cglob_t *, size_t *); +static int glob3(Char *, Char *, Char *, Char *, Char *, cglob_t *, size_t *); +static int globextend(const Char *, cglob_t *, size_t *); +static const Char * + globtilde(const Char *, Char *, size_t, cglob_t *); +static int globexp1(const Char *, cglob_t *, size_t *); +static int globexp2(const Char *, const Char *, cglob_t *, int *, size_t *); +static int match(Char *, Char *, Char *); +#ifdef DEBUG +static void qprintf(const char *, Char *); +#endif + +int +cglob(const char *pattern, int flags, int (*errfunc)(const char *, int), cglob_t *pglob) +{ + const char *patnext; + size_t limit; + Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot; + mbstate_t mbs; + wchar_t wc; + size_t clen; + + patnext = pattern; + if (!(flags & GLOB_APPEND)) { + pglob->gl_pathc = 0; + pglob->gl_pathv = NULL; + if (!(flags & GLOB_DOOFFS)) + pglob->gl_offs = 0; + } + + if (flags & GLOB_LIMIT) { + limit = pglob->gl_matchc; + if (limit == 0) + limit = ARG_MAX; + } else + limit = 0; + + pglob->gl_flags = flags & ~GLOB_MAGCHAR; + pglob->gl_errfunc = errfunc; + pglob->gl_matchc = 0; + + bufnext = patbuf; + bufend = bufnext + MAXPATHLEN - 1; + if (flags & GLOB_NOESCAPE) { + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc; + patnext += clen; + } + } else { + /* Protect the quoted characters. */ + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + if (*patnext == QUOTE) { + if (*++patnext == EOS) { + *bufnext++ = QUOTE | M_PROTECT; + continue; + } + prot = M_PROTECT; + } else + prot = 0; + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc | prot; + patnext += clen; + } + } + *bufnext = EOS; + + if (flags & GLOB_BRACE) + return globexp1(patbuf, pglob, &limit); + else + return glob0(patbuf, pglob, &limit); +} + +/* + * Expand recursively a glob {} pattern. When there is no more expansion + * invoke the standard globbing routine to glob the rest of the magic + * characters + */ +static int +globexp1(const Char *pattern, cglob_t *pglob, size_t *limit) +{ + const Char* ptr = pattern; + int rv; + + /* Protect a single {}, for find(1), like csh */ + if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS) + return glob0(pattern, pglob, limit); + + while ((ptr = g_strchr(ptr, LBRACE)) != NULL) + if (!globexp2(ptr, pattern, pglob, &rv, limit)) + return rv; + + return glob0(pattern, pglob, limit); +} + + +/* + * Recursive brace globbing helper. Tries to expand a single brace. + * If it succeeds then it invokes globexp1 with the new pattern. + * If it fails then it tries to glob the rest of the pattern and returns. + */ +static int +globexp2(const Char *ptr, const Char *pattern, cglob_t *pglob, int *rv, size_t *limit) +{ + int i; + Char *lm, *ls; + const Char *pe, *pm, *pm1, *pl; + Char patbuf[MAXPATHLEN]; + + /* copy part up to the brace */ + for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++) + continue; + *lm = EOS; + ls = lm; + + /* Find the balanced brace */ + for (i = 0, pe = ++ptr; *pe; pe++) + if (*pe == LBRACKET) { + /* Ignore everything between [] */ + for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++) + continue; + if (*pe == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pe = pm; + } + } + else if (*pe == LBRACE) + i++; + else if (*pe == RBRACE) { + if (i == 0) + break; + i--; + } + + /* Non matching braces; just glob the pattern */ + if (i != 0 || *pe == EOS) { + *rv = glob0(patbuf, pglob, limit); + return 0; + } + + for (i = 0, pl = pm = ptr; pm <= pe; pm++) + switch (*pm) { + case LBRACKET: + /* Ignore everything between [] */ + for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++) + continue; + if (*pm == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pm = pm1; + } + break; + + case LBRACE: + i++; + break; + + case RBRACE: + if (i) { + i--; + break; + } + /* FALLTHROUGH */ + case COMMA: + if (i && *pm == COMMA) + break; + else { + /* Append the current string */ + for (lm = ls; (pl < pm); *lm++ = *pl++) + continue; + /* + * Append the rest of the pattern after the + * closing brace + */ + for (pl = pe + 1; (*lm++ = *pl++) != EOS;) + continue; + + /* Expand the current pattern */ +#ifdef DEBUG + qprintf("globexp2:", patbuf); +#endif + *rv = globexp1(patbuf, pglob, limit); + + /* move after the comma, to the next string */ + pl = pm + 1; + } + break; + + default: + break; + } + *rv = 0; + return 0; +} + + + +/* + * expand tilde from the passwd file. + */ +static const Char * +globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, cglob_t *pglob) +{ + struct passwd *pwd; + char *h; + const Char *p; + Char *b, *eb; + + if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE)) + return pattern; + + /* + * Copy up to the end of the string or / + */ + eb = &patbuf[patbuf_len - 1]; + for (p = pattern + 1, h = (char *) patbuf; + h < (char *)eb && *p && *p != SLASH; *h++ = *p++) + continue; + + *h = EOS; + + if (((char *) patbuf)[0] == EOS) { + /* + * handle a plain ~ or ~/ by expanding $HOME first (iff + * we're not running setuid or setgid) and then trying + * the password file + */ + /*if (issetugid() != 0 || + (h = getenv("HOME")) == NULL) { + if (((h = getlogin()) != NULL && + (pwd = getpwnam(h)) != NULL) || + (pwd = getpwuid(getuid())) != NULL) + h = pwd->pw_dir; + else + return pattern; + }*/ + } + else { + /* + * Expand a ~user + */ + if ((pwd = getpwnam((char*) patbuf)) == NULL) + return pattern; + else + h = pwd->pw_dir; + } + + /* Copy the home directory */ + for (b = patbuf; b < eb && *h; *b++ = *h++) + continue; + + /* Append the rest of the pattern */ + while (b < eb && (*b++ = *p++) != EOS) + continue; + *b = EOS; + + return patbuf; +} + + +/* + * The main glob() routine: compiles the pattern (optionally processing + * quotes), calls glob1() to do the real pattern matching, and finally + * sorts the list (unless unsorted operation is requested). Returns 0 + * if things went well, nonzero if errors occurred. + */ +static int +glob0(const Char *pattern, cglob_t *pglob, size_t *limit) +{ + const Char *qpatnext; + int err; + size_t oldpathc; + Char *bufnext, c, patbuf[MAXPATHLEN]; + + qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob); + oldpathc = pglob->gl_pathc; + bufnext = patbuf; + + /* We don't need to check for buffer overflow any more. */ + while ((c = *qpatnext++) != EOS) { + switch (c) { + case LBRACKET: + c = *qpatnext; + if (c == NOT) + ++qpatnext; + if (*qpatnext == EOS || + g_strchr(qpatnext+1, RBRACKET) == NULL) { + *bufnext++ = LBRACKET; + if (c == NOT) + --qpatnext; + break; + } + *bufnext++ = M_SET; + if (c == NOT) + *bufnext++ = M_NOT; + c = *qpatnext++; + do { + *bufnext++ = CHAR(c); + if (*qpatnext == RANGE && + (c = qpatnext[1]) != RBRACKET) { + *bufnext++ = M_RNG; + *bufnext++ = CHAR(c); + qpatnext += 2; + } + } while ((c = *qpatnext++) != RBRACKET); + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_END; + break; + case QUESTION: + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_ONE; + break; + case STAR: + pglob->gl_flags |= GLOB_MAGCHAR; + /* collapse adjacent stars to one, + * to avoid exponential behavior + */ + if (bufnext == patbuf || bufnext[-1] != M_ALL) + *bufnext++ = M_ALL; + break; + default: + *bufnext++ = CHAR(c); + break; + } + } + *bufnext = EOS; +#ifdef DEBUG + qprintf("glob0:", patbuf); +#endif + + if ((err = glob1(patbuf, pglob, limit)) != 0) + return(err); + + /* + * If there was no match we are going to append the pattern + * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified + * and the pattern did not contain any magic characters + * GLOB_NOMAGIC is there just for compatibility with csh. + */ + if (pglob->gl_pathc == oldpathc) { + if (((pglob->gl_flags & GLOB_NOCHECK) || + ((pglob->gl_flags & GLOB_NOMAGIC) && + !(pglob->gl_flags & GLOB_MAGCHAR)))) + return(globextend(pattern, pglob, limit)); + else + return(GLOB_NOMATCH); + } + if (!(pglob->gl_flags & GLOB_NOSORT)) + qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc, + pglob->gl_pathc - oldpathc, sizeof(char *), compare); + return(0); +} + +static int +compare(const void *p, const void *q) +{ + return(strcmp(*(char **)p, *(char **)q)); +} + +static int +glob1(Char *pattern, cglob_t *pglob, size_t *limit) +{ + Char pathbuf[MAXPATHLEN]; + + /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */ + if (*pattern == EOS) + return(0); + return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1, + pattern, pglob, limit)); +} + +/* + * The functions glob2 and glob3 are mutually recursive; there is one level + * of recursion for each segment in the pattern that contains one or more + * meta characters. + */ +static int +glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern, + cglob_t *pglob, size_t *limit) +{ + struct stat sb; + Char *p, *q; + int anymeta; + + /* + * Loop over pattern segments until end of pattern or until + * segment with meta character found. + */ + for (anymeta = 0;;) { + if (*pattern == EOS) { /* End of pattern? */ + *pathend = EOS; + if (g_lstat(pathbuf, &sb, pglob)) + return(0); + + if (((pglob->gl_flags & GLOB_MARK) && + pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) + || (S_ISLNK(sb.st_mode) && + (g_stat(pathbuf, &sb, pglob) == 0) && + S_ISDIR(sb.st_mode)))) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = SEP; + *pathend = EOS; + } + ++pglob->gl_matchc; + return(globextend(pathbuf, pglob, limit)); + } + + /* Find end of next segment, copy tentatively to pathend. */ + q = pathend; + p = pattern; + while (*p != EOS && *p != SEP) { + if (ismeta(*p)) + anymeta = 1; + if (q + 1 > pathend_last) + return (GLOB_ABORTED); + *q++ = *p++; + } + + if (!anymeta) { /* No expansion, do next segment. */ + pathend = q; + pattern = p; + while (*pattern == SEP) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = *pattern++; + } + } else /* Need expansion, recurse. */ + return(glob3(pathbuf, pathend, pathend_last, pattern, p, + pglob, limit)); + } + /* NOTREACHED */ +} + +static int +glob3(Char *pathbuf, Char *pathend, Char *pathend_last, + Char *pattern, Char *restpattern, + cglob_t *pglob, size_t *limit) +{ + struct dirent *dp; + DIR *dirp; + int err; + char buf[MAXPATHLEN]; + + /* + * The readdirfunc declaration can't be prototyped, because it is + * assigned, below, to two functions which are prototyped in glob.h + * and dirent.h as taking pointers to differently typed opaque + * structures. + */ + struct dirent *(*readdirfunc)(); + + if (pathend > pathend_last) + return (GLOB_ABORTED); + *pathend = EOS; + errno = 0; + + if ((dirp = g_opendir(pathbuf, pglob)) == NULL) { + /* TODO: don't call for ENOENT or ENOTDIR? */ + if (pglob->gl_errfunc) { + if (g_Ctoc(pathbuf, buf, sizeof(buf))) + return (GLOB_ABORTED); + if (pglob->gl_errfunc(buf, errno) || + pglob->gl_flags & GLOB_ERR) + return (GLOB_ABORTED); + } + return(0); + } + + err = 0; + + /* Search directory for matching names. */ + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + readdirfunc = pglob->gl_readdir; + else + readdirfunc = readdir; + while ((dp = (*readdirfunc)(dirp))) { + char *sc; + Char *dc; + wchar_t wc; + size_t clen; + mbstate_t mbs; + + /* Initial DOT must be matched literally. */ + if (dp->d_name[0] == DOT && *pattern != DOT) + continue; + memset(&mbs, 0, sizeof(mbs)); + dc = pathend; + sc = dp->d_name; + while (dc < pathend_last) { + clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) { + wc = *sc; + clen = 1; + memset(&mbs, 0, sizeof(mbs)); + } + if ((*dc++ = wc) == EOS) + break; + sc += clen; + } + if (!match(pathend, pattern, restpattern)) { + *pathend = EOS; + continue; + } + err = glob2(pathbuf, --dc, pathend_last, restpattern, + pglob, limit); + if (err) + break; + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + (*pglob->gl_closedir)(dirp); + else + closedir(dirp); + return(err); +} + + +/* + * Extend the gl_pathv member of a glob_t structure to accomodate a new item, + * add the new item, and update gl_pathc. + * + * This assumes the BSD realloc, which only copies the block when its size + * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic + * behavior. + * + * Return 0 if new item added, error code if memory couldn't be allocated. + * + * Invariant of the glob_t structure: + * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and + * gl_pathv points to (gl_offs + gl_pathc + 1) items. + */ +static int +globextend(const Char *path, cglob_t *pglob, size_t *limit) +{ + char **pathv; + size_t i, newsize, len; + char *copy; + const Char *p; + + if (*limit && pglob->gl_pathc > *limit) { + errno = 0; + return (GLOB_NOSPACE); + } + + newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs); + pathv = pglob->gl_pathv ? + realloc((char *)pglob->gl_pathv, newsize) : + malloc(newsize); + if (pathv == NULL) { + if (pglob->gl_pathv) { + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } + return(GLOB_NOSPACE); + } + + if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) { + /* first time around -- clear initial gl_offs items */ + pathv += pglob->gl_offs; + for (i = pglob->gl_offs + 1; --i > 0; ) + *--pathv = NULL; + } + pglob->gl_pathv = pathv; + + for (p = path; *p++;) + continue; + len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */ + if ((copy = malloc(len)) != NULL) { + if (g_Ctoc(path, copy, len)) { + free(copy); + return (GLOB_NOSPACE); + } + pathv[pglob->gl_offs + pglob->gl_pathc++] = copy; + } + pathv[pglob->gl_offs + pglob->gl_pathc] = NULL; + return(copy == NULL ? GLOB_NOSPACE : 0); +} + +/* + * pattern matching function for filenames. Each occurrence of the * + * pattern causes a recursion level. + */ +static int +match(Char *name, Char *pat, Char *patend) +{ + int ok, negate_range; + Char c, k; + + while (pat < patend) { + c = *pat++; + switch (c & M_MASK) { + case M_ALL: + if (pat == patend) + return(1); + do + if (match(name, pat, patend)) + return(1); + while (*name++ != EOS); + return(0); + case M_ONE: + if (*name++ == EOS) + return(0); + break; + case M_SET: + ok = 0; + if ((k = *name++) == EOS) + return(0); + if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS) + ++pat; + while (((c = *pat++) & M_MASK) != M_END) + if ((*pat & M_MASK) == M_RNG) { + if (CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1])) ok = 1; + pat += 2; + } else if (c == k) + ok = 1; + if (ok == negate_range) + return(0); + break; + default: + if (*name++ != c) + return(0); + break; + } + } + return(*name == EOS); +} + +/* Free allocated data belonging to a glob_t structure. */ +void +cglobfree(cglob_t *pglob) +{ + size_t i; + char **pp; + + if (pglob->gl_pathv != NULL) { + pp = pglob->gl_pathv + pglob->gl_offs; + for (i = pglob->gl_pathc; i--; ++pp) + if (*pp) + free(*pp); + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } +} + +static DIR * +g_opendir(Char *str, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (!*str) + strcpy(buf, "."); + else { + if (g_Ctoc(str, buf, sizeof(buf))) + return (NULL); + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_opendir)(buf)); + + return(opendir(buf)); +} + +static int +g_lstat(Char *fn, struct stat *sb, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_lstat)(buf, sb)); + return(lstat(buf, sb)); +} + +static int +g_stat(Char *fn, struct stat *sb, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_stat)(buf, sb)); + return(stat(buf, sb)); +} + +static const Char * +g_strchr(const Char *str, wchar_t ch) +{ + + do { + if (*str == ch) + return (str); + } while (*str++); + return (NULL); +} + +static int +g_Ctoc(const Char *str, char *buf, size_t len) +{ + mbstate_t mbs; + size_t clen; + + memset(&mbs, 0, sizeof(mbs)); + while (len >= MB_CUR_MAX) { + clen = wcrtomb(buf, *str, &mbs); + if (clen == (size_t)-1) + return (1); + if (*str == L'\0') + return (0); + str++; + buf += clen; + len -= clen; + } + return (1); +} + +#ifdef DEBUG +static void +qprintf(const char *str, Char *s) +{ + Char *p; + + (void)printf("%s:\n", str); + for (p = s; *p; p++) + (void)printf("%c", CHAR(*p)); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", *p & M_PROTECT ? '"' : ' '); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", ismeta(*p) ? '_' : ' '); + (void)printf("\n"); +} +#endif diff --git a/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_linux.cpp b/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_linux.cpp new file mode 100644 index 00000000..5799d6ac --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_linux.cpp @@ -0,0 +1,342 @@ +#if defined(__linux__) + +/* + * Copyright (c) 2014 Craig Lilley + * This software is made available under the terms of the MIT licence. + * A copy of the licence can be obtained from: + * http://opensource.org/licenses/MIT + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef ANDROID +#include "cglob.h" +#else +#include +#define cglob glob +#define cglobfree globfree +#define cglob_t glob_t +#endif +#include +#include +#include + +#include "serial/serial.h" + +using serial::PortInfo; +using std::istringstream; +using std::ifstream; +using std::getline; +using std::vector; +using std::string; +using std::cout; +using std::endl; + +static vector glob(const vector& patterns); +static string basename(const string& path); +static string dirname(const string& path); +static bool path_exists(const string& path); +static string realpath(const string& path); +static string usb_sysfs_friendly_name(const string& sys_usb_path); +static vector get_sysfs_info(const string& device_path); +static string read_line(const string& file); +static string usb_sysfs_hw_string(const string& sysfs_path); +static string format(const char* format, ...); + +vector +glob(const vector& patterns) +{ + vector paths_found; + + if(patterns.size() == 0) + return paths_found; + + cglob_t glob_results; + + int glob_retval = cglob(patterns[0].c_str(), 0, NULL, &glob_results); + + vector::const_iterator iter = patterns.begin(); + + while(++iter != patterns.end()) + { + glob_retval = cglob(iter->c_str(), GLOB_APPEND, NULL, &glob_results); + } + + for(int path_index = 0; path_index < glob_results.gl_pathc; path_index++) + { + paths_found.push_back(glob_results.gl_pathv[path_index]); + } + + cglobfree(&glob_results); + + return paths_found; +} + +string +basename(const string& path) +{ + size_t pos = path.rfind("/"); + + if(pos == std::string::npos) + return path; + + return string(path, pos+1, string::npos); +} + +string +dirname(const string& path) +{ + size_t pos = path.rfind("/"); + + if(pos == std::string::npos) + return path; + else if(pos == 0) + return "/"; + + return string(path, 0, pos); +} + +bool +path_exists(const string& path) +{ + struct stat sb; + + if( stat(path.c_str(), &sb ) == 0 ) + return true; + + return false; +} + +string +realpath(const string& path) +{ + char* real_path = realpath(path.c_str(), NULL); + + string result; + + if(real_path != NULL) + { + result = real_path; + + free(real_path); + } + + return result; +} + +string +usb_sysfs_friendly_name(const string& sys_usb_path) +{ + unsigned int device_number = 0; + + istringstream( read_line(sys_usb_path + "/devnum") ) >> device_number; + + string manufacturer = read_line( sys_usb_path + "/manufacturer" ); + + string product = read_line( sys_usb_path + "/product" ); + + string serial = read_line( sys_usb_path + "/serial" ); + + if( manufacturer.empty() && product.empty() && serial.empty() ) + return ""; + + return format("%s %s %s", manufacturer.c_str(), product.c_str(), serial.c_str() ); +} + +vector +get_sysfs_info(const string& device_path) +{ + string device_name = basename( device_path ); + + string friendly_name; + + string hardware_id; + + string sys_device_path = format( "/sys/class/tty/%s/device", device_name.c_str() ); + + if( device_name.compare(0,6,"ttyUSB") == 0 ) + { + sys_device_path = dirname( dirname( realpath( sys_device_path ) ) ); + + if( path_exists( sys_device_path ) ) + { + friendly_name = usb_sysfs_friendly_name( sys_device_path ); + + hardware_id = usb_sysfs_hw_string( sys_device_path ); + } + } + else if( device_name.compare(0,6,"ttyACM") == 0 ) + { + sys_device_path = dirname( realpath( sys_device_path ) ); + + if( path_exists( sys_device_path ) ) + { + friendly_name = usb_sysfs_friendly_name( sys_device_path ); + + hardware_id = usb_sysfs_hw_string( sys_device_path ); + } + } + else + { + // Try to read ID string of PCI device + + string sys_id_path = sys_device_path + "/id"; + + if( path_exists( sys_id_path ) ) + hardware_id = read_line( sys_id_path ); + } + + if( friendly_name.empty() ) + friendly_name = device_name; + + if( hardware_id.empty() ) + hardware_id = "n/a"; + + vector result; + result.push_back(friendly_name); + result.push_back(hardware_id); + + return result; +} + +string +read_line(const string& file) +{ + ifstream ifs(file.c_str(), ifstream::in); + + string line; + + if(ifs) + { + getline(ifs, line); + } + + return line; +} + +string +format(const char* format, ...) +{ + va_list ap; + + size_t buffer_size_bytes = 256; + + string result; + + char* buffer = (char*)malloc(buffer_size_bytes); + + if( buffer == NULL ) + return result; + + bool done = false; + + unsigned int loop_count = 0; + + while(!done) + { + va_start(ap, format); + + int return_value = vsnprintf(buffer, buffer_size_bytes, format, ap); + + if( return_value < 0 ) + { + done = true; + } + else if( return_value >= buffer_size_bytes ) + { + // Realloc and try again. + + buffer_size_bytes = return_value + 1; + + char* new_buffer_ptr = (char*)realloc(buffer, buffer_size_bytes); + + if( new_buffer_ptr == NULL ) + { + done = true; + } + else + { + buffer = new_buffer_ptr; + } + } + else + { + result = buffer; + done = true; + } + + va_end(ap); + + if( ++loop_count > 5 ) + done = true; + } + + free(buffer); + + return result; +} + +string +usb_sysfs_hw_string(const string& sysfs_path) +{ + string serial_number = read_line( sysfs_path + "/serial" ); + + if( serial_number.length() > 0 ) + { + serial_number = format( "SNR=%s", serial_number.c_str() ); + } + + string vid = read_line( sysfs_path + "/idVendor" ); + + string pid = read_line( sysfs_path + "/idProduct" ); + + return format("USB VID:PID=%s:%s %s", vid.c_str(), pid.c_str(), serial_number.c_str() ); +} + +vector +serial::list_ports() +{ + vector results; + + vector search_globs; + search_globs.push_back("/dev/ttyACM*"); + search_globs.push_back("/dev/ttyS*"); + search_globs.push_back("/dev/ttyUSB*"); + search_globs.push_back("/dev/tty.*"); + search_globs.push_back("/dev/cu.*"); + search_globs.push_back("/dev/rfcomm*"); + + vector devices_found = glob( search_globs ); + + vector::iterator iter = devices_found.begin(); + + while( iter != devices_found.end() ) + { + string device = *iter++; + + vector sysfs_info = get_sysfs_info( device ); + + string friendly_name = sysfs_info[0]; + + string hardware_id = sysfs_info[1]; + + PortInfo device_entry; + device_entry.port = device; + device_entry.description = friendly_name; + device_entry.hardware_id = hardware_id; + + results.push_back( device_entry ); + + } + + return results; +} + +#endif // defined(__linux__) diff --git a/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_osx.cpp b/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_osx.cpp new file mode 100644 index 00000000..8005c62b --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_osx.cpp @@ -0,0 +1,286 @@ +#if defined(__APPLE__) + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "../../../include/serial/serial.h" + +using serial::PortInfo; +using std::string; +using std::vector; + +#define HARDWARE_ID_STRING_LENGTH 128 + +string cfstring_to_string( CFStringRef cfstring ); +string get_device_path( io_object_t& serial_port ); +string get_class_name( io_object_t& obj ); +io_registry_entry_t get_parent_iousb_device( io_object_t& serial_port ); +string get_string_property( io_object_t& device, const char* property ); +uint16_t get_int_property( io_object_t& device, const char* property ); +string rtrim(const string& str); + +string +cfstring_to_string( CFStringRef cfstring ) +{ + char cstring[MAXPATHLEN]; + string result; + + if( cfstring ) + { + Boolean success = CFStringGetCString( cfstring, + cstring, + sizeof(cstring), + kCFStringEncodingASCII ); + + if( success ) + result = cstring; + } + + return result; +} + +string +get_device_path( io_object_t& serial_port ) +{ + CFTypeRef callout_path; + string device_path; + + callout_path = IORegistryEntryCreateCFProperty( serial_port, + CFSTR(kIOCalloutDeviceKey), + kCFAllocatorDefault, + 0 ); + + if (callout_path) + { + if( CFGetTypeID(callout_path) == CFStringGetTypeID() ) + device_path = cfstring_to_string( static_cast(callout_path) ); + + CFRelease(callout_path); + } + + return device_path; +} + +string +get_class_name( io_object_t& obj ) +{ + string result; + io_name_t class_name; + kern_return_t kern_result; + + kern_result = IOObjectGetClass( obj, class_name ); + + if( kern_result == KERN_SUCCESS ) + result = class_name; + + return result; +} + +io_registry_entry_t +get_parent_iousb_device( io_object_t& serial_port ) +{ + io_object_t device = serial_port; + io_registry_entry_t parent = 0; + io_registry_entry_t result = 0; + kern_return_t kern_result = KERN_FAILURE; + string name = get_class_name(device); + + // Walk the IO Registry tree looking for this devices parent IOUSBDevice. + while( name != "IOUSBDevice" ) + { + kern_result = IORegistryEntryGetParentEntry( device, + kIOServicePlane, + &parent ); + + if(kern_result != KERN_SUCCESS) + { + result = 0; + break; + } + + device = parent; + + name = get_class_name(device); + } + + if(kern_result == KERN_SUCCESS) + result = device; + + return result; +} + +string +get_string_property( io_object_t& device, const char* property ) +{ + string property_name; + + if( device ) + { + CFStringRef property_as_cfstring = CFStringCreateWithCString ( + kCFAllocatorDefault, + property, + kCFStringEncodingASCII ); + + CFTypeRef name_as_cfstring = IORegistryEntryCreateCFProperty( + device, + property_as_cfstring, + kCFAllocatorDefault, + 0 ); + + if( name_as_cfstring ) + { + if( CFGetTypeID(name_as_cfstring) == CFStringGetTypeID() ) + property_name = cfstring_to_string( static_cast(name_as_cfstring) ); + + CFRelease(name_as_cfstring); + } + + if(property_as_cfstring) + CFRelease(property_as_cfstring); + } + + return property_name; +} + +uint16_t +get_int_property( io_object_t& device, const char* property ) +{ + uint16_t result = 0; + + if( device ) + { + CFStringRef property_as_cfstring = CFStringCreateWithCString ( + kCFAllocatorDefault, + property, + kCFStringEncodingASCII ); + + CFTypeRef number = IORegistryEntryCreateCFProperty( device, + property_as_cfstring, + kCFAllocatorDefault, + 0 ); + + if(property_as_cfstring) + CFRelease(property_as_cfstring); + + if( number ) + { + if( CFGetTypeID(number) == CFNumberGetTypeID() ) + { + bool success = CFNumberGetValue( static_cast(number), + kCFNumberSInt16Type, + &result ); + + if( !success ) + result = 0; + } + + CFRelease(number); + } + + } + + return result; +} + +string rtrim(const string& str) +{ + string result = str; + + string whitespace = " \t\f\v\n\r"; + + std::size_t found = result.find_last_not_of(whitespace); + + if (found != std::string::npos) + result.erase(found+1); + else + result.clear(); + + return result; +} + +vector +serial::list_ports(void) +{ + vector devices_found; + CFMutableDictionaryRef classes_to_match; + io_iterator_t serial_port_iterator; + io_object_t serial_port; + mach_port_t master_port; + kern_return_t kern_result; + + kern_result = IOMasterPort(MACH_PORT_NULL, &master_port); + + if(kern_result != KERN_SUCCESS) + return devices_found; + + classes_to_match = IOServiceMatching(kIOSerialBSDServiceValue); + + if (classes_to_match == NULL) + return devices_found; + + CFDictionarySetValue( classes_to_match, + CFSTR(kIOSerialBSDTypeKey), + CFSTR(kIOSerialBSDAllTypes) ); + + kern_result = IOServiceGetMatchingServices(master_port, classes_to_match, &serial_port_iterator); + + if (KERN_SUCCESS != kern_result) + return devices_found; + + while ( (serial_port = IOIteratorNext(serial_port_iterator)) ) + { + string device_path = get_device_path( serial_port ); + io_registry_entry_t parent = get_parent_iousb_device( serial_port ); + IOObjectRelease(serial_port); + + if( device_path.empty() ) + continue; + + PortInfo port_info; + port_info.port = device_path; + port_info.description = "n/a"; + port_info.hardware_id = "n/a"; + + string device_name = rtrim( get_string_property( parent, "USB Product Name" ) ); + string vendor_name = rtrim( get_string_property( parent, "USB Vendor Name") ); + string description = rtrim( vendor_name + " " + device_name ); + if( !description.empty() ) + port_info.description = description; + + string serial_number = rtrim(get_string_property( parent, "USB Serial Number" ) ); + uint16_t vendor_id = get_int_property( parent, "idVendor" ); + uint16_t product_id = get_int_property( parent, "idProduct" ); + + if( vendor_id && product_id ) + { + char cstring[HARDWARE_ID_STRING_LENGTH]; + + if(serial_number.empty()) + serial_number = "None"; + + int ret = snprintf( cstring, HARDWARE_ID_STRING_LENGTH, "USB VID:PID=%04x:%04x SNR=%s", + vendor_id, + product_id, + serial_number.c_str() ); + + if( (ret >= 0) && (ret < HARDWARE_ID_STRING_LENGTH) ) + port_info.hardware_id = cstring; + } + + devices_found.push_back(port_info); + } + + IOObjectRelease(serial_port_iterator); + return devices_found; +} + +#endif // defined(__APPLE__) diff --git a/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_win.cpp b/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_win.cpp new file mode 100644 index 00000000..7da40c44 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/impl/list_ports/list_ports_win.cpp @@ -0,0 +1,152 @@ +#if defined(_WIN32) + +/* + * Copyright (c) 2014 Craig Lilley + * This software is made available under the terms of the MIT licence. + * A copy of the licence can be obtained from: + * http://opensource.org/licenses/MIT + */ + +#include "serial/serial.h" +#include +#include +#include +#include +#include +#include + +using serial::PortInfo; +using std::vector; +using std::string; + +static const DWORD port_name_max_length = 256; +static const DWORD friendly_name_max_length = 256; +static const DWORD hardware_id_max_length = 256; + +// Convert a wide Unicode string to an UTF8 string +std::string utf8_encode(const std::wstring &wstr) +{ + int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); + std::string strTo( size_needed, 0 ); + WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); + return strTo; +} + +vector +serial::list_ports() +{ + vector devices_found; + + HDEVINFO device_info_set = SetupDiGetClassDevs( + (const GUID *) &GUID_DEVCLASS_PORTS, + NULL, + NULL, + DIGCF_PRESENT); + + unsigned int device_info_set_index = 0; + SP_DEVINFO_DATA device_info_data; + + device_info_data.cbSize = sizeof(SP_DEVINFO_DATA); + + while(SetupDiEnumDeviceInfo(device_info_set, device_info_set_index, &device_info_data)) + { + device_info_set_index++; + + // Get port name + + HKEY hkey = SetupDiOpenDevRegKey( + device_info_set, + &device_info_data, + DICS_FLAG_GLOBAL, + 0, + DIREG_DEV, + KEY_READ); + + TCHAR port_name[port_name_max_length]; + DWORD port_name_length = port_name_max_length; + + LONG return_code = RegQueryValueEx( + hkey, + _T("PortName"), + NULL, + NULL, + (LPBYTE)port_name, + &port_name_length); + + RegCloseKey(hkey); + + if(return_code != EXIT_SUCCESS) + continue; + + if(port_name_length > 0 && port_name_length <= port_name_max_length) + port_name[port_name_length-1] = '\0'; + else + port_name[0] = '\0'; + + // Ignore parallel ports + + if(_tcsstr(port_name, _T("LPT")) != NULL) + continue; + + // Get port friendly name + + TCHAR friendly_name[friendly_name_max_length]; + DWORD friendly_name_actual_length = 0; + + BOOL got_friendly_name = SetupDiGetDeviceRegistryProperty( + device_info_set, + &device_info_data, + SPDRP_FRIENDLYNAME, + NULL, + (PBYTE)friendly_name, + friendly_name_max_length, + &friendly_name_actual_length); + + if(got_friendly_name == TRUE && friendly_name_actual_length > 0) + friendly_name[friendly_name_actual_length-1] = '\0'; + else + friendly_name[0] = '\0'; + + // Get hardware ID + + TCHAR hardware_id[hardware_id_max_length]; + DWORD hardware_id_actual_length = 0; + + BOOL got_hardware_id = SetupDiGetDeviceRegistryProperty( + device_info_set, + &device_info_data, + SPDRP_HARDWAREID, + NULL, + (PBYTE)hardware_id, + hardware_id_max_length, + &hardware_id_actual_length); + + if(got_hardware_id == TRUE && hardware_id_actual_length > 0) + hardware_id[hardware_id_actual_length-1] = '\0'; + else + hardware_id[0] = '\0'; + + #ifdef UNICODE + std::string portName = utf8_encode(port_name); + std::string friendlyName = utf8_encode(friendly_name); + std::string hardwareId = utf8_encode(hardware_id); + #else + std::string portName = port_name; + std::string friendlyName = friendly_name; + std::string hardwareId = hardware_id; + #endif + + PortInfo port_entry; + port_entry.port = portName; + port_entry.description = friendlyName; + port_entry.hardware_id = hardwareId; + + devices_found.push_back(port_entry); + } + + SetupDiDestroyDeviceInfoList(device_info_set); + + return devices_found; +} + +#endif // #if defined(_WIN32) diff --git a/third_party/flserial/macos/Classes/native_libs/src/impl/unix.cpp b/third_party/flserial/macos/Classes/native_libs/src/impl/unix.cpp new file mode 100644 index 00000000..689c08cf --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/impl/unix.cpp @@ -0,0 +1,1087 @@ +/* Copyright 2012 William Woodall and John Harrison + * + * Additional Contributors: Christopher Baker @bakercp + */ + +#if !defined(_WIN32) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +# include +#endif + +#include +#include +#include +#ifdef __MACH__ +#include +#include +#include +#endif + +#include "../../include/serial/impl/unix.h" + +#ifndef TIOCINQ +#ifdef FIONREAD +#define TIOCINQ FIONREAD +#else +#define TIOCINQ 0x541B +#endif +#endif + +#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3) +#include +#endif + +using std::string; +using std::stringstream; +using std::invalid_argument; +using serial::MillisecondTimer; +using serial::Serial; +using serial::SerialException; +using serial::PortNotOpenedException; +using serial::IOException; + + +MillisecondTimer::MillisecondTimer (const uint32_t millis) + : expiry(timespec_now()) +{ + int64_t tv_nsec = expiry.tv_nsec + (millis * 1e6); + if (tv_nsec >= 1e9) { + int64_t sec_diff = tv_nsec / static_cast (1e9); + expiry.tv_nsec = tv_nsec % static_cast(1e9); + expiry.tv_sec += sec_diff; + } else { + expiry.tv_nsec = tv_nsec; + } +} + +int64_t +MillisecondTimer::remaining () +{ + timespec now(timespec_now()); + int64_t millis = (expiry.tv_sec - now.tv_sec) * 1e3; + millis += (expiry.tv_nsec - now.tv_nsec) / 1e6; + return millis; +} + +timespec +MillisecondTimer::timespec_now () +{ + timespec time; +# ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + time.tv_sec = mts.tv_sec; + time.tv_nsec = mts.tv_nsec; +# else + clock_gettime(CLOCK_MONOTONIC, &time); +# endif + return time; +} + +timespec +timespec_from_ms (const uint32_t millis) +{ + timespec time; + time.tv_sec = millis / 1e3; + time.tv_nsec = (millis - (time.tv_sec * 1e3)) * 1e6; + return time; +} + +Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : port_ (port), fd_ (-1), is_open_ (false), xonxoff_ (false), rtscts_ (false), + baudrate_ (baudrate), parity_ (parity), + bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol) +{ + pthread_mutex_init(&this->read_mutex, NULL); + pthread_mutex_init(&this->write_mutex, NULL); + if (port_.empty () == false) + open (); +} + +Serial::SerialImpl::~SerialImpl () +{ + close(); + pthread_mutex_destroy(&this->read_mutex); + pthread_mutex_destroy(&this->write_mutex); +} + +void +Serial::SerialImpl::open () +{ + if (port_.empty ()) { + throw invalid_argument ("Empty port is invalid."); + } + if (is_open_ == true) { + throw SerialException ("Serial port already open."); + } + + fd_ = ::open (port_.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); + + int err = errno; + if (fd_ == -1) { + switch (err) { + case EINTR: + // Recurse because this is a recoverable error. + open (); + return; + case ENFILE: + case EMFILE: + THROW (IOException, "Too many file handles open."); + default: + char buff[32]; + sprintf(buff, "%08X", err); + THROW (IOException, buff); + } + } + + reconfigurePort(); + is_open_ = true; +} + +void +Serial::SerialImpl::reconfigurePort () +{ + if (fd_ == -1) { + // Can only operate on a valid file descriptor + THROW (IOException, "Invalid file descriptor, is the serial port open?"); + } + + struct termios options; // The options for the file descriptor + + if (tcgetattr(fd_, &options) == -1) { + THROW (IOException, "::tcgetattr"); + } + + // set up raw mode / no echo / binary + options.c_cflag |= (tcflag_t) (CLOCAL | CREAD); + options.c_lflag &= (tcflag_t) ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | + ISIG | IEXTEN); //|ECHOPRT + + options.c_oflag &= (tcflag_t) ~(OPOST); + options.c_iflag &= (tcflag_t) ~(INLCR | IGNCR | ICRNL | IGNBRK); +#ifdef IUCLC + options.c_iflag &= (tcflag_t) ~IUCLC; +#endif +#ifdef PARMRK + options.c_iflag &= (tcflag_t) ~PARMRK; +#endif + + // setup baud rate + bool custom_baud = false; + speed_t baud; + switch (baudrate_) { +#ifdef B0 + case 0: baud = B0; break; +#endif +#ifdef B50 + case 50: baud = B50; break; +#endif +#ifdef B75 + case 75: baud = B75; break; +#endif +#ifdef B110 + case 110: baud = B110; break; +#endif +#ifdef B134 + case 134: baud = B134; break; +#endif +#ifdef B150 + case 150: baud = B150; break; +#endif +#ifdef B200 + case 200: baud = B200; break; +#endif +#ifdef B300 + case 300: baud = B300; break; +#endif +#ifdef B600 + case 600: baud = B600; break; +#endif +#ifdef B1200 + case 1200: baud = B1200; break; +#endif +#ifdef B1800 + case 1800: baud = B1800; break; +#endif +#ifdef B2400 + case 2400: baud = B2400; break; +#endif +#ifdef B4800 + case 4800: baud = B4800; break; +#endif +#ifdef B7200 + case 7200: baud = B7200; break; +#endif +#ifdef B9600 + case 9600: baud = B9600; break; +#endif +#ifdef B14400 + case 14400: baud = B14400; break; +#endif +#ifdef B19200 + case 19200: baud = B19200; break; +#endif +#ifdef B28800 + case 28800: baud = B28800; break; +#endif +#ifdef B57600 + case 57600: baud = B57600; break; +#endif +#ifdef B76800 + case 76800: baud = B76800; break; +#endif +#ifdef B38400 + case 38400: baud = B38400; break; +#endif +#ifdef B115200 + case 115200: baud = B115200; break; +#endif +#ifdef B128000 + case 128000: baud = B128000; break; +#endif +#ifdef B153600 + case 153600: baud = B153600; break; +#endif +#ifdef B230400 + case 230400: baud = B230400; break; +#endif +#ifdef B256000 + case 256000: baud = B256000; break; +#endif +#ifdef B460800 + case 460800: baud = B460800; break; +#endif +#ifdef B500000 + case 500000: baud = B500000; break; +#endif +#ifdef B576000 + case 576000: baud = B576000; break; +#endif +#ifdef B921600 + case 921600: baud = B921600; break; +#endif +#ifdef B1000000 + case 1000000: baud = B1000000; break; +#endif +#ifdef B1152000 + case 1152000: baud = B1152000; break; +#endif +#ifdef B1500000 + case 1500000: baud = B1500000; break; +#endif +#ifdef B2000000 + case 2000000: baud = B2000000; break; +#endif +#ifdef B2500000 + case 2500000: baud = B2500000; break; +#endif +#ifdef B3000000 + case 3000000: baud = B3000000; break; +#endif +#ifdef B3500000 + case 3500000: baud = B3500000; break; +#endif +#ifdef B4000000 + case 4000000: baud = B4000000; break; +#endif + default: + custom_baud = true; + } + if (custom_baud == false) { +#ifdef _BSD_SOURCE + ::cfsetspeed(&options, baud); +#else + ::cfsetispeed(&options, baud); + ::cfsetospeed(&options, baud); +#endif + } + + // setup char len + options.c_cflag &= (tcflag_t) ~CSIZE; + if (bytesize_ == eightbits) + options.c_cflag |= CS8; + else if (bytesize_ == sevenbits) + options.c_cflag |= CS7; + else if (bytesize_ == sixbits) + options.c_cflag |= CS6; + else if (bytesize_ == fivebits) + options.c_cflag |= CS5; + else + throw invalid_argument ("invalid char len"); + // setup stopbits + if (stopbits_ == stopbits_one) + options.c_cflag &= (tcflag_t) ~(CSTOPB); + else if (stopbits_ == stopbits_one_point_five) + // ONE POINT FIVE same as TWO.. there is no POSIX support for 1.5 + options.c_cflag |= (CSTOPB); + else if (stopbits_ == stopbits_two) + options.c_cflag |= (CSTOPB); + else + throw invalid_argument ("invalid stop bit"); + // setup parity + options.c_iflag &= (tcflag_t) ~(INPCK | ISTRIP); + if (parity_ == parity_none) { + options.c_cflag &= (tcflag_t) ~(PARENB | PARODD); + } else if (parity_ == parity_even) { + options.c_cflag &= (tcflag_t) ~(PARODD); + options.c_cflag |= (PARENB); + } else if (parity_ == parity_odd) { + options.c_cflag |= (PARENB | PARODD); + } +#ifdef CMSPAR + else if (parity_ == parity_mark) { + options.c_cflag |= (PARENB | CMSPAR | PARODD); + } + else if (parity_ == parity_space) { + options.c_cflag |= (PARENB | CMSPAR); + options.c_cflag &= (tcflag_t) ~(PARODD); + } +#else + // CMSPAR is not defined on OSX. So do not support mark or space parity. + else if (parity_ == parity_mark || parity_ == parity_space) { + throw invalid_argument ("OS does not support mark or space parity"); + } +#endif // ifdef CMSPAR + else { + throw invalid_argument ("invalid parity"); + } + // setup flow control + if (flowcontrol_ == flowcontrol_none) { + xonxoff_ = false; + rtscts_ = false; + } + if (flowcontrol_ == flowcontrol_software) { + xonxoff_ = true; + rtscts_ = false; + } + if (flowcontrol_ == flowcontrol_hardware) { + xonxoff_ = false; + rtscts_ = true; + } + // xonxoff +#ifdef IXANY + if (xonxoff_) + options.c_iflag |= (IXON | IXOFF); //|IXANY) + else + options.c_iflag &= (tcflag_t) ~(IXON | IXOFF | IXANY); +#else + if (xonxoff_) + options.c_iflag |= (IXON | IXOFF); + else + options.c_iflag &= (tcflag_t) ~(IXON | IXOFF); +#endif + // rtscts +#ifdef CRTSCTS + if (rtscts_) + options.c_cflag |= (CRTSCTS); + else + options.c_cflag &= (unsigned long) ~(CRTSCTS); +#elif defined CNEW_RTSCTS + if (rtscts_) + options.c_cflag |= (CNEW_RTSCTS); + else + options.c_cflag &= (unsigned long) ~(CNEW_RTSCTS); +#else +#error "OS Support seems wrong." +#endif + + // http://www.unixwiz.net/techtips/termios-vmin-vtime.html + // this basically sets the read call up to be a polling read, + // but we are using select to ensure there is data available + // to read before each call, so we should never needlessly poll + options.c_cc[VMIN] = 0; + options.c_cc[VTIME] = 0; + + // activate settings + ::tcsetattr (fd_, TCSANOW, &options); + + // apply custom baud rate, if any + if (custom_baud == true) { + // OS X support +#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4) + // Starting with Tiger, the IOSSIOSPEED ioctl can be used to set arbitrary baud rates + // other than those specified by POSIX. The driver for the underlying serial hardware + // ultimately determines which baud rates can be used. This ioctl sets both the input + // and output speed. + speed_t new_baud = static_cast (baudrate_); + // PySerial uses IOSSIOSPEED=0x80045402 + if (-1 == ioctl (fd_, IOSSIOSPEED, &new_baud, 1)) { + THROW (IOException, errno); + } + // Linux Support +#elif defined(__linux__) && defined (TIOCSSERIAL) + struct serial_struct ser; + + if (-1 == ioctl (fd_, TIOCGSERIAL, &ser)) { + THROW (IOException, errno); + } + + // set custom divisor + ser.custom_divisor = ser.baud_base / static_cast (baudrate_); + // update flags + ser.flags &= ~ASYNC_SPD_MASK; + ser.flags |= ASYNC_SPD_CUST; + + if (-1 == ioctl (fd_, TIOCSSERIAL, &ser)) { + THROW (IOException, errno); + } +#else + throw invalid_argument ("OS does not currently support custom bauds"); +#endif + } + + // Update byte_time_ based on the new settings. + uint32_t bit_time_ns = 1e9 / baudrate_; + byte_time_ns_ = bit_time_ns * (1 + bytesize_ + parity_ + stopbits_); + + // Compensate for the stopbits_one_point_five enum being equal to int 3, + // and not 1.5. + if (stopbits_ == stopbits_one_point_five) { + byte_time_ns_ += ((1.5 - stopbits_one_point_five) * bit_time_ns); + } +} + +void +Serial::SerialImpl::close () +{ + if (is_open_ == true) { + if (fd_ != -1) { + int ret; + ret = ::close (fd_); + if (ret == 0) { + fd_ = -1; + } else { + THROW (IOException, errno); + } + } + is_open_ = false; + } +} + +bool +Serial::SerialImpl::isOpen () const +{ + return is_open_; +} + +size_t +Serial::SerialImpl::available () +{ + if (!is_open_) { + return 0; + } + int count = 0; + if (-1 == ioctl (fd_, TIOCINQ, &count)) { + THROW (IOException, errno); + } else { + return static_cast (count); + } +} + +bool +Serial::SerialImpl::waitReadable (uint32_t timeout) +{ + // Setup a select call to block for serial data or a timeout + fd_set readfds; + FD_ZERO (&readfds); + FD_SET (fd_, &readfds); + timespec timeout_ts (timespec_from_ms (timeout)); + int r = pselect (fd_ + 1, &readfds, NULL, NULL, &timeout_ts, NULL); + + if (r < 0) { + // Select was interrupted + if (errno == EINTR) { + return false; + } + // Otherwise there was some error + THROW (IOException, errno); + } + // Timeout occurred + if (r == 0) { + return false; + } + // This shouldn't happen, if r > 0 our fd has to be in the list! + if (!FD_ISSET (fd_, &readfds)) { + THROW (IOException, "select reports ready to read, but our fd isn't" + " in the list, this shouldn't happen!"); + } + // Data available to read. + return true; +} + +void +Serial::SerialImpl::waitByteTimes (size_t count) +{ + timespec wait_time = { 0, static_cast(byte_time_ns_ * count)}; + pselect (0, NULL, NULL, NULL, &wait_time, NULL); +} + +size_t +Serial::SerialImpl::read (uint8_t *buf, size_t size) +{ + // If the port is not open, throw + if (!is_open_) { + throw PortNotOpenedException ("Serial::read"); + } + size_t bytes_read = 0; + + // Calculate total timeout in milliseconds t_c + (t_m * N) + long total_timeout_ms = timeout_.read_timeout_constant; + total_timeout_ms += timeout_.read_timeout_multiplier * static_cast (size); + MillisecondTimer total_timeout(total_timeout_ms); + + // Pre-fill buffer with available bytes + { + ssize_t bytes_read_now = ::read (fd_, buf, size); + if (bytes_read_now > 0) { + bytes_read = bytes_read_now; + } + } + + while (bytes_read < size) { + int64_t timeout_remaining_ms = total_timeout.remaining(); + if (timeout_remaining_ms <= 0) { + // Timed out + break; + } + // Timeout for the next select is whichever is less of the remaining + // total read timeout and the inter-byte timeout. + uint32_t timeout = std::min(static_cast (timeout_remaining_ms), + timeout_.inter_byte_timeout); + // Wait for the device to be readable, and then attempt to read. + if (waitReadable(timeout)) { + // If it's a fixed-length multi-byte read, insert a wait here so that + // we can attempt to grab the whole thing in a single IO call. Skip + // this wait if a non-max inter_byte_timeout is specified. + if (size > 1 && timeout_.inter_byte_timeout == Timeout::max()) { + size_t bytes_available = available(); + if (bytes_available + bytes_read < size) { + waitByteTimes(size - (bytes_available + bytes_read)); + } + } + // This should be non-blocking returning only what is available now + // Then returning so that select can block again. + ssize_t bytes_read_now = + ::read (fd_, buf + bytes_read, size - bytes_read); + // read should always return some data as select reported it was + // ready to read when we get to this point. + if (bytes_read_now < 1) { + // Disconnected devices, at least on Linux, show the + // behavior that they are always ready to read immediately + // but reading returns nothing. + throw SerialException ("device reports readiness to read but " + "returned no data (device disconnected?)"); + } + // Update bytes_read + bytes_read += static_cast (bytes_read_now); + // If bytes_read == size then we have read everything we need + if (bytes_read == size) { + break; + } + // If bytes_read < size then we have more to read + if (bytes_read < size) { + continue; + } + // If bytes_read > size then we have over read, which shouldn't happen + if (bytes_read > size) { + throw SerialException ("read over read, too many bytes where " + "read, this shouldn't happen, might be " + "a logical error!"); + } + } + } + return bytes_read; +} + +size_t +Serial::SerialImpl::write (const uint8_t *data, size_t length) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::write"); + } + fd_set writefds; + size_t bytes_written = 0; + + // Calculate total timeout in milliseconds t_c + (t_m * N) + long total_timeout_ms = timeout_.write_timeout_constant; + total_timeout_ms += timeout_.write_timeout_multiplier * static_cast (length); + MillisecondTimer total_timeout(total_timeout_ms); + + bool first_iteration = true; + while (bytes_written < length) { + int64_t timeout_remaining_ms = total_timeout.remaining(); + // Only consider the timeout if it's not the first iteration of the loop + // otherwise a timeout of 0 won't be allowed through + if (!first_iteration && (timeout_remaining_ms <= 0)) { + // Timed out + break; + } + first_iteration = false; + + timespec timeout(timespec_from_ms(timeout_remaining_ms)); + + FD_ZERO (&writefds); + FD_SET (fd_, &writefds); + + // Do the select + int r = pselect (fd_ + 1, NULL, &writefds, NULL, &timeout, NULL); + + // Figure out what happened by looking at select's response 'r' + /** Error **/ + if (r < 0) { + // Select was interrupted, try again + if (errno == EINTR) { + continue; + } + // Otherwise there was some error + THROW (IOException, errno); + } + /** Timeout **/ + if (r == 0) { + break; + } + /** Port ready to write **/ + if (r > 0) { + // Make sure our file descriptor is in the ready to write list + if (FD_ISSET (fd_, &writefds)) { + // This will write some + ssize_t bytes_written_now = + ::write (fd_, data + bytes_written, length - bytes_written); + + // even though pselect returned readiness the call might still be + // interrupted. In that case simply retry. + if (bytes_written_now == -1 && errno == EINTR) { + continue; + } + + // write should always return some data as select reported it was + // ready to write when we get to this point. + if (bytes_written_now < 1) { + // Disconnected devices, at least on Linux, show the + // behavior that they are always ready to write immediately + // but writing returns nothing. + std::stringstream strs; + strs << "device reports readiness to write but " + "returned no data (device disconnected?)"; + strs << " errno=" << errno; + strs << " bytes_written_now= " << bytes_written_now; + strs << " bytes_written=" << bytes_written; + strs << " length=" << length; + throw SerialException(strs.str().c_str()); + } + // Update bytes_written + bytes_written += static_cast (bytes_written_now); + // If bytes_written == size then we have written everything we need to + if (bytes_written == length) { + break; + } + // If bytes_written < size then we have more to write + if (bytes_written < length) { + continue; + } + // If bytes_written > size then we have over written, which shouldn't happen + if (bytes_written > length) { + throw SerialException ("write over wrote, too many bytes where " + "written, this shouldn't happen, might be " + "a logical error!"); + } + } + // This shouldn't happen, if r > 0 our fd has to be in the list! + THROW (IOException, "select reports ready to write, but our fd isn't" + " in the list, this shouldn't happen!"); + } + } + return bytes_written; +} + +void +Serial::SerialImpl::setPort (const string &port) +{ + port_ = port; +} + +string +Serial::SerialImpl::getPort () const +{ + return port_; +} + +void +Serial::SerialImpl::setTimeout (serial::Timeout &timeout) +{ + timeout_ = timeout; +} + +serial::Timeout +Serial::SerialImpl::getTimeout () const +{ + return timeout_; +} + +void +Serial::SerialImpl::setBaudrate (unsigned long baudrate) +{ + baudrate_ = baudrate; + if (is_open_) + reconfigurePort (); +} + +unsigned long +Serial::SerialImpl::getBaudrate () const +{ + return baudrate_; +} + +void +Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize) +{ + bytesize_ = bytesize; + if (is_open_) + reconfigurePort (); +} + +serial::bytesize_t +Serial::SerialImpl::getBytesize () const +{ + return bytesize_; +} + +void +Serial::SerialImpl::setParity (serial::parity_t parity) +{ + parity_ = parity; + if (is_open_) + reconfigurePort (); +} + +serial::parity_t +Serial::SerialImpl::getParity () const +{ + return parity_; +} + +void +Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits) +{ + stopbits_ = stopbits; + if (is_open_) + reconfigurePort (); +} + +serial::stopbits_t +Serial::SerialImpl::getStopbits () const +{ + return stopbits_; +} + +void +Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol) +{ + flowcontrol_ = flowcontrol; + if (is_open_) + reconfigurePort (); +} + +serial::flowcontrol_t +Serial::SerialImpl::getFlowcontrol () const +{ + return flowcontrol_; +} + +void +Serial::SerialImpl::flush () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flush"); + } + tcdrain (fd_); +} + +void +Serial::SerialImpl::flushInput () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flushInput"); + } + tcflush (fd_, TCIFLUSH); +} + +void +Serial::SerialImpl::flushOutput () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flushOutput"); + } + tcflush (fd_, TCOFLUSH); +} + +void +Serial::SerialImpl::sendBreak (int duration) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::sendBreak"); + } + tcsendbreak (fd_, static_cast (duration / 4)); +} + +void +Serial::SerialImpl::setBreak (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setBreak"); + } + + if (level) { + if (-1 == ioctl (fd_, TIOCSBRK)) + { + stringstream ss; + ss << "setBreak failed on a call to ioctl(TIOCSBRK): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCCBRK)) + { + stringstream ss; + ss << "setBreak failed on a call to ioctl(TIOCCBRK): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +void +Serial::SerialImpl::setRTS (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setRTS"); + } + + int command = TIOCM_RTS; + + if (level) { + if (-1 == ioctl (fd_, TIOCMBIS, &command)) + { + stringstream ss; + ss << "setRTS failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCMBIC, &command)) + { + stringstream ss; + ss << "setRTS failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +void +Serial::SerialImpl::setDTR (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setDTR"); + } + + int command = TIOCM_DTR; + + if (level) { + if (-1 == ioctl (fd_, TIOCMBIS, &command)) + { + stringstream ss; + ss << "setDTR failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCMBIC, &command)) + { + stringstream ss; + ss << "setDTR failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +bool +Serial::SerialImpl::waitForChange () +{ +#ifndef TIOCMIWAIT + +while (is_open_ == true) { + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "waitForChange failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + if (0 != (status & TIOCM_CTS) + || 0 != (status & TIOCM_DSR) + || 0 != (status & TIOCM_RI) + || 0 != (status & TIOCM_CD)) + { + return true; + } + } + + usleep(1000); + } + + return false; +#else + int command = (TIOCM_CD|TIOCM_DSR|TIOCM_RI|TIOCM_CTS); + + if (-1 == ioctl (fd_, TIOCMIWAIT, &command)) { + stringstream ss; + ss << "waitForDSR failed on a call to ioctl(TIOCMIWAIT): " + << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + return true; +#endif +} + +bool +Serial::SerialImpl::getCTS () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCTS"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getCTS failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_CTS); + } +} + +bool +Serial::SerialImpl::getDSR () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getDSR"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getDSR failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_DSR); + } +} + +bool +Serial::SerialImpl::getRI () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getRI"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getRI failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_RI); + } +} + +bool +Serial::SerialImpl::getCD () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCD"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getCD failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_CD); + } +} + +void +Serial::SerialImpl::readLock () +{ + int result = pthread_mutex_lock(&this->read_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::readUnlock () +{ + int result = pthread_mutex_unlock(&this->read_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::writeLock () +{ + int result = pthread_mutex_lock(&this->write_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::writeUnlock () +{ + int result = pthread_mutex_unlock(&this->write_mutex); + if (result) { + THROW (IOException, result); + } +} + +#endif // !defined(_WIN32) diff --git a/third_party/flserial/macos/Classes/native_libs/src/impl/win.cpp b/third_party/flserial/macos/Classes/native_libs/src/impl/win.cpp new file mode 100644 index 00000000..cbccf048 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/impl/win.cpp @@ -0,0 +1,651 @@ +#if defined(_WIN32) + +/* Copyright 2012 William Woodall and John Harrison */ + +#include + +#include "serial/impl/win.h" + +using std::string; +using std::wstring; +using std::stringstream; +using std::invalid_argument; +using serial::Serial; +using serial::Timeout; +using serial::bytesize_t; +using serial::parity_t; +using serial::stopbits_t; +using serial::flowcontrol_t; +using serial::SerialException; +using serial::PortNotOpenedException; +using serial::IOException; + +inline wstring +_prefix_port_if_needed(const wstring &input) +{ + static wstring windows_com_port_prefix = L"\\\\.\\"; + if (input.compare(0, windows_com_port_prefix.size(), windows_com_port_prefix) != 0) + { + return windows_com_port_prefix + input; + } + return input; +} + +Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : port_ (port.begin(), port.end()), fd_ (INVALID_HANDLE_VALUE), is_open_ (false), + baudrate_ (baudrate), parity_ (parity), + bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol) +{ + if (port_.empty () == false) + open (); + read_mutex = CreateMutex(NULL, false, NULL); + write_mutex = CreateMutex(NULL, false, NULL); +} + +Serial::SerialImpl::~SerialImpl () +{ + this->close(); + CloseHandle(read_mutex); + CloseHandle(write_mutex); +} + +void +Serial::SerialImpl::open () +{ + if (port_.empty ()) { + throw invalid_argument ("Empty port is invalid."); + } + if (is_open_ == true) { + throw SerialException ("Serial port already open."); + } + + // See: https://github.com/wjwwood/serial/issues/84 + wstring port_with_prefix = _prefix_port_if_needed(port_); + LPCWSTR lp_port = port_with_prefix.c_str(); + fd_ = CreateFileW(lp_port, + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + 0); + + if (fd_ == INVALID_HANDLE_VALUE) { + DWORD create_file_err = GetLastError(); + stringstream ss; + switch (create_file_err) { + case ERROR_FILE_NOT_FOUND: + // Use this->getPort to convert to a std::string + ss << "Specified port, " << this->getPort() << ", does not exist."; + THROWEX (IOException, ss.str().c_str(), 1); + case ERROR_ACCESS_DENIED: + ss << "Specified port, " << this->getPort() << ", allready open."; + THROWEX (IOException, ss.str().c_str(), 2); + default: + ss << "Unknown error opening the serial port: " << create_file_err; + THROW (IOException, ss.str().c_str()); + } + } + + + + reconfigurePort(); + is_open_ = true; +} + +void +Serial::SerialImpl::reconfigurePort () +{ + if (fd_ == INVALID_HANDLE_VALUE) { + // Can only operate on a valid file descriptor + THROW (IOException, "Invalid file descriptor, is the serial port open?"); + } + + DCB dcbSerialParams = {0}; + + dcbSerialParams.DCBlength=sizeof(dcbSerialParams); + + if (!GetCommState(fd_, &dcbSerialParams)) { + //error getting state + THROW (IOException, "Error getting the serial port state."); + } + + // setup baud rate + switch (baudrate_) { +#ifdef CBR_0 + case 0: dcbSerialParams.BaudRate = CBR_0; break; +#endif +#ifdef CBR_50 + case 50: dcbSerialParams.BaudRate = CBR_50; break; +#endif +#ifdef CBR_75 + case 75: dcbSerialParams.BaudRate = CBR_75; break; +#endif +#ifdef CBR_110 + case 110: dcbSerialParams.BaudRate = CBR_110; break; +#endif +#ifdef CBR_134 + case 134: dcbSerialParams.BaudRate = CBR_134; break; +#endif +#ifdef CBR_150 + case 150: dcbSerialParams.BaudRate = CBR_150; break; +#endif +#ifdef CBR_200 + case 200: dcbSerialParams.BaudRate = CBR_200; break; +#endif +#ifdef CBR_300 + case 300: dcbSerialParams.BaudRate = CBR_300; break; +#endif +#ifdef CBR_600 + case 600: dcbSerialParams.BaudRate = CBR_600; break; +#endif +#ifdef CBR_1200 + case 1200: dcbSerialParams.BaudRate = CBR_1200; break; +#endif +#ifdef CBR_1800 + case 1800: dcbSerialParams.BaudRate = CBR_1800; break; +#endif +#ifdef CBR_2400 + case 2400: dcbSerialParams.BaudRate = CBR_2400; break; +#endif +#ifdef CBR_4800 + case 4800: dcbSerialParams.BaudRate = CBR_4800; break; +#endif +#ifdef CBR_7200 + case 7200: dcbSerialParams.BaudRate = CBR_7200; break; +#endif +#ifdef CBR_9600 + case 9600: dcbSerialParams.BaudRate = CBR_9600; break; +#endif +#ifdef CBR_14400 + case 14400: dcbSerialParams.BaudRate = CBR_14400; break; +#endif +#ifdef CBR_19200 + case 19200: dcbSerialParams.BaudRate = CBR_19200; break; +#endif +#ifdef CBR_28800 + case 28800: dcbSerialParams.BaudRate = CBR_28800; break; +#endif +#ifdef CBR_57600 + case 57600: dcbSerialParams.BaudRate = CBR_57600; break; +#endif +#ifdef CBR_76800 + case 76800: dcbSerialParams.BaudRate = CBR_76800; break; +#endif +#ifdef CBR_38400 + case 38400: dcbSerialParams.BaudRate = CBR_38400; break; +#endif +#ifdef CBR_115200 + case 115200: dcbSerialParams.BaudRate = CBR_115200; break; +#endif +#ifdef CBR_128000 + case 128000: dcbSerialParams.BaudRate = CBR_128000; break; +#endif +#ifdef CBR_153600 + case 153600: dcbSerialParams.BaudRate = CBR_153600; break; +#endif +#ifdef CBR_230400 + case 230400: dcbSerialParams.BaudRate = CBR_230400; break; +#endif +#ifdef CBR_256000 + case 256000: dcbSerialParams.BaudRate = CBR_256000; break; +#endif +#ifdef CBR_460800 + case 460800: dcbSerialParams.BaudRate = CBR_460800; break; +#endif +#ifdef CBR_921600 + case 921600: dcbSerialParams.BaudRate = CBR_921600; break; +#endif + default: + // Try to blindly assign it + dcbSerialParams.BaudRate = baudrate_; + } + + // setup char len + if (bytesize_ == eightbits) + dcbSerialParams.ByteSize = 8; + else if (bytesize_ == sevenbits) + dcbSerialParams.ByteSize = 7; + else if (bytesize_ == sixbits) + dcbSerialParams.ByteSize = 6; + else if (bytesize_ == fivebits) + dcbSerialParams.ByteSize = 5; + else + throw invalid_argument ("invalid char len"); + + // setup stopbits + if (stopbits_ == stopbits_one) + dcbSerialParams.StopBits = ONESTOPBIT; + else if (stopbits_ == stopbits_one_point_five) + dcbSerialParams.StopBits = ONE5STOPBITS; + else if (stopbits_ == stopbits_two) + dcbSerialParams.StopBits = TWOSTOPBITS; + else + throw invalid_argument ("invalid stop bit"); + + // setup parity + if (parity_ == parity_none) { + dcbSerialParams.Parity = NOPARITY; + } else if (parity_ == parity_even) { + dcbSerialParams.Parity = EVENPARITY; + } else if (parity_ == parity_odd) { + dcbSerialParams.Parity = ODDPARITY; + } else if (parity_ == parity_mark) { + dcbSerialParams.Parity = MARKPARITY; + } else if (parity_ == parity_space) { + dcbSerialParams.Parity = SPACEPARITY; + } else { + throw invalid_argument ("invalid parity"); + } + + // setup flowcontrol + if (flowcontrol_ == flowcontrol_none) { + dcbSerialParams.fOutxCtsFlow = false; + dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE; + dcbSerialParams.fOutX = false; + dcbSerialParams.fInX = false; + } + if (flowcontrol_ == flowcontrol_software) { + dcbSerialParams.fOutxCtsFlow = false; + dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE; + dcbSerialParams.fOutX = true; + dcbSerialParams.fInX = true; + } + if (flowcontrol_ == flowcontrol_hardware) { + dcbSerialParams.fOutxCtsFlow = true; + dcbSerialParams.fRtsControl = RTS_CONTROL_HANDSHAKE; + dcbSerialParams.fOutX = false; + dcbSerialParams.fInX = false; + } + + // activate settings + if (!SetCommState(fd_, &dcbSerialParams)){ + CloseHandle(fd_); + THROW (IOException, "Error setting serial port settings."); + } + + // Setup timeouts + COMMTIMEOUTS timeouts = {0}; + timeouts.ReadIntervalTimeout = timeout_.inter_byte_timeout; + timeouts.ReadTotalTimeoutConstant = timeout_.read_timeout_constant; + timeouts.ReadTotalTimeoutMultiplier = timeout_.read_timeout_multiplier; + timeouts.WriteTotalTimeoutConstant = timeout_.write_timeout_constant; + timeouts.WriteTotalTimeoutMultiplier = timeout_.write_timeout_multiplier; + if (!SetCommTimeouts(fd_, &timeouts)) { + THROW (IOException, "Error setting timeouts."); + } +} + +void +Serial::SerialImpl::close () +{ + if (is_open_ == true) { + if (fd_ != INVALID_HANDLE_VALUE) { + int ret; + ret = CloseHandle(fd_); + if (ret == 0) { + stringstream ss; + ss << "Error while closing serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } else { + fd_ = INVALID_HANDLE_VALUE; + } + } + is_open_ = false; + } +} + +bool +Serial::SerialImpl::isOpen () const +{ + return is_open_; +} + +size_t +Serial::SerialImpl::available () +{ + if (!is_open_) { + return 0; + } + COMSTAT cs; + if (!ClearCommError(fd_, NULL, &cs)) { + stringstream ss; + ss << "Error while checking status of the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return static_cast(cs.cbInQue); +} + +bool +Serial::SerialImpl::waitReadable (uint32_t /*timeout*/) +{ + THROW (IOException, "waitReadable is not implemented on Windows."); + return false; +} + +void +Serial::SerialImpl::waitByteTimes (size_t /*count*/) +{ + THROW (IOException, "waitByteTimes is not implemented on Windows."); +} + +size_t +Serial::SerialImpl::read (uint8_t *buf, size_t size) +{ + if (!is_open_) { + throw PortNotOpenedException ("Serial::read"); + } + DWORD bytes_read; + if (!ReadFile(fd_, buf, static_cast(size), &bytes_read, NULL)) { + stringstream ss; + ss << "Error while reading from the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return (size_t) (bytes_read); +} + +size_t +Serial::SerialImpl::write (const uint8_t *data, size_t length) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::write"); + } + DWORD bytes_written; + if (!WriteFile(fd_, data, static_cast(length), &bytes_written, NULL)) { + stringstream ss; + ss << "Error while writing to the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return (size_t) (bytes_written); +} + +void +Serial::SerialImpl::setPort (const string &port) +{ + port_ = wstring(port.begin(), port.end()); +} + +string +Serial::SerialImpl::getPort () const +{ + return string(port_.begin(), port_.end()); +} + +void +Serial::SerialImpl::setTimeout (serial::Timeout &timeout) +{ + timeout_ = timeout; + if (is_open_) { + reconfigurePort (); + } +} + +serial::Timeout +Serial::SerialImpl::getTimeout () const +{ + return timeout_; +} + +void +Serial::SerialImpl::setBaudrate (unsigned long baudrate) +{ + baudrate_ = baudrate; + if (is_open_) { + reconfigurePort (); + } +} + +unsigned long +Serial::SerialImpl::getBaudrate () const +{ + return baudrate_; +} + +void +Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize) +{ + bytesize_ = bytesize; + if (is_open_) { + reconfigurePort (); + } +} + +serial::bytesize_t +Serial::SerialImpl::getBytesize () const +{ + return bytesize_; +} + +void +Serial::SerialImpl::setParity (serial::parity_t parity) +{ + parity_ = parity; + if (is_open_) { + reconfigurePort (); + } +} + +serial::parity_t +Serial::SerialImpl::getParity () const +{ + return parity_; +} + +void +Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits) +{ + stopbits_ = stopbits; + if (is_open_) { + reconfigurePort (); + } +} + +serial::stopbits_t +Serial::SerialImpl::getStopbits () const +{ + return stopbits_; +} + +void +Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol) +{ + flowcontrol_ = flowcontrol; + if (is_open_) { + reconfigurePort (); + } +} + +serial::flowcontrol_t +Serial::SerialImpl::getFlowcontrol () const +{ + return flowcontrol_; +} + +void +Serial::SerialImpl::flush () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flush"); + } + FlushFileBuffers (fd_); +} + +void +Serial::SerialImpl::flushInput () +{ + if (is_open_ == false) { + throw PortNotOpenedException("Serial::flushInput"); + } + PurgeComm(fd_, PURGE_RXCLEAR); +} + +void +Serial::SerialImpl::flushOutput () +{ + if (is_open_ == false) { + throw PortNotOpenedException("Serial::flushOutput"); + } + PurgeComm(fd_, PURGE_TXCLEAR); +} + +void +Serial::SerialImpl::sendBreak (int /*duration*/) +{ + THROW (IOException, "sendBreak is not supported on Windows."); +} + +void +Serial::SerialImpl::setBreak (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setBreak"); + } + if (level) { + EscapeCommFunction (fd_, SETBREAK); + } else { + EscapeCommFunction (fd_, CLRBREAK); + } +} + +void +Serial::SerialImpl::setRTS (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setRTS"); + } + if (level) { + EscapeCommFunction (fd_, SETRTS); + } else { + EscapeCommFunction (fd_, CLRRTS); + } +} + +void +Serial::SerialImpl::setDTR (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setDTR"); + } + if (level) { + EscapeCommFunction (fd_, SETDTR); + } else { + EscapeCommFunction (fd_, CLRDTR); + } +} + +bool +Serial::SerialImpl::waitForChange () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::waitForChange"); + } + DWORD dwCommEvent; + + if (!SetCommMask(fd_, EV_CTS | EV_DSR | EV_RING | EV_RLSD)) { + // Error setting communications mask + return false; + } + + if (!WaitCommEvent(fd_, &dwCommEvent, NULL)) { + // An error occurred waiting for the event. + return false; + } else { + // Event has occurred. + return true; + } +} + +bool +Serial::SerialImpl::getCTS () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCTS"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the CTS line."); + } + + return (MS_CTS_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getDSR () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getDSR"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the DSR line."); + } + + return (MS_DSR_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getRI() +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getRI"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the RI line."); + } + + return (MS_RING_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getCD() +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCD"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + // Error in GetCommModemStatus; + THROW (IOException, "Error getting the status of the CD line."); + } + + return (MS_RLSD_ON & dwModemStatus) != 0; +} + +void +Serial::SerialImpl::readLock() +{ + if (WaitForSingleObject(read_mutex, INFINITE) != WAIT_OBJECT_0) { + THROW (IOException, "Error claiming read mutex."); + } +} + +void +Serial::SerialImpl::readUnlock() +{ + if (!ReleaseMutex(read_mutex)) { + THROW (IOException, "Error releasing read mutex."); + } +} + +void +Serial::SerialImpl::writeLock() +{ + if (WaitForSingleObject(write_mutex, INFINITE) != WAIT_OBJECT_0) { + THROW (IOException, "Error claiming write mutex."); + } +} + +void +Serial::SerialImpl::writeUnlock() +{ + if (!ReleaseMutex(write_mutex)) { + THROW (IOException, "Error releasing write mutex."); + } +} + +#endif // #if defined(_WIN32) + diff --git a/third_party/flserial/macos/Classes/native_libs/src/ringbuffer.c b/third_party/flserial/macos/Classes/native_libs/src/ringbuffer.c new file mode 100644 index 00000000..39fbea59 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/ringbuffer.c @@ -0,0 +1,78 @@ +#include "ringbuffer.h" + +/** + * @file + * Implementation of ring buffer functions. + */ + +void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size) { + RING_BUFFER_ASSERT(RING_BUFFER_IS_POWER_OF_TWO(buf_size) == 1); + buffer->buffer = buf; + buffer->buffer_mask = buf_size - 1; + buffer->tail_index = 0; + buffer->head_index = 0; +} + +void ring_buffer_queue(ring_buffer_t *buffer, char data) { + /* Is buffer full? */ + if(ring_buffer_is_full(buffer)) { + /* Is going to overwrite the oldest byte */ + /* Increase tail index */ + buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer)); + } + + /* Place data in buffer */ + buffer->buffer[buffer->head_index] = data; + buffer->head_index = ((buffer->head_index + 1) & RING_BUFFER_MASK(buffer)); +} + +void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size) { + /* Add bytes; one by one */ + ring_buffer_size_t i; + for(i = 0; i < size; i++) { + ring_buffer_queue(buffer, data[i]); + } +} + +uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data) { + if(ring_buffer_is_empty(buffer)) { + /* No items */ + return 0; + } + + *data = buffer->buffer[buffer->tail_index]; + buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer)); + return 1; +} + +ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len) { + if(ring_buffer_is_empty(buffer)) { + /* No items */ + return 0; + } + + char *data_ptr = data; + ring_buffer_size_t cnt = 0; + while((cnt < len) && ring_buffer_dequeue(buffer, data_ptr)) { + cnt++; + data_ptr++; + } + return cnt; +} + +uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index) { + if(index >= ring_buffer_num_items(buffer)) { + /* No items at index */ + return 0; + } + + /* Add index to pointer */ + ring_buffer_size_t data_index = ((buffer->tail_index + index) & RING_BUFFER_MASK(buffer)); + *data = buffer->buffer[data_index]; + return 1; +} + +extern inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer); +extern inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer); +extern inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer); + diff --git a/third_party/flserial/macos/Classes/native_libs/src/serial.cpp b/third_party/flserial/macos/Classes/native_libs/src/serial.cpp new file mode 100644 index 00000000..06a15a99 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/serial.cpp @@ -0,0 +1,432 @@ +/* Copyright 2012 William Woodall and John Harrison */ +#include + +#if !defined(_WIN32) && !defined(__OpenBSD__) && !defined(__FreeBSD__) +# include +#endif + +#if defined (__MINGW32__) +# define alloca __builtin_alloca +#endif + +#include "../include/serial/serial.h" + +#ifdef _WIN32 +#include "serial/impl/win.h" +#else +#include "../include/serial/impl/unix.h" +#endif + +using std::invalid_argument; +using std::min; +using std::numeric_limits; +using std::vector; +using std::size_t; +using std::string; + +using serial::Serial; +using serial::SerialException; +using serial::IOException; +using serial::bytesize_t; +using serial::parity_t; +using serial::stopbits_t; +using serial::flowcontrol_t; + +class Serial::ScopedReadLock { +public: + ScopedReadLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->readLock(); + } + ~ScopedReadLock() { + this->pimpl_->readUnlock(); + } +private: + // Disable copy constructors + ScopedReadLock(const ScopedReadLock&); + const ScopedReadLock& operator=(ScopedReadLock); + + SerialImpl *pimpl_; +}; + +class Serial::ScopedWriteLock { +public: + ScopedWriteLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->writeLock(); + } + ~ScopedWriteLock() { + this->pimpl_->writeUnlock(); + } +private: + // Disable copy constructors + ScopedWriteLock(const ScopedWriteLock&); + const ScopedWriteLock& operator=(ScopedWriteLock); + SerialImpl *pimpl_; +}; + +Serial::Serial (const string &port, uint32_t baudrate, serial::Timeout timeout, + bytesize_t bytesize, parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : pimpl_(new SerialImpl (port, baudrate, bytesize, parity, + stopbits, flowcontrol)) +{ + pimpl_->setTimeout(timeout); +} + +Serial::~Serial () +{ + delete pimpl_; +} + +void +Serial::open () +{ + pimpl_->open (); +} + +void +Serial::close () +{ + pimpl_->close (); +} + +bool +Serial::isOpen () const +{ + return pimpl_->isOpen (); +} + +size_t +Serial::available () +{ + return pimpl_->available (); +} + +bool +Serial::waitReadable () +{ + serial::Timeout timeout(pimpl_->getTimeout ()); + return pimpl_->waitReadable(timeout.read_timeout_constant); +} + +void +Serial::waitByteTimes (size_t count) +{ + pimpl_->waitByteTimes(count); +} + +size_t +Serial::read_ (uint8_t *buffer, size_t size) +{ + return this->pimpl_->read (buffer, size); +} + +size_t +Serial::read (uint8_t *buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + return this->pimpl_->read (buffer, size); +} + +size_t +Serial::read (std::vector &buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + uint8_t *buffer_ = new uint8_t[size]; + size_t bytes_read = 0; + + try { + bytes_read = this->pimpl_->read (buffer_, size); + } + catch (const std::exception) { + delete[] buffer_; + throw; + } + + buffer.insert (buffer.end (), buffer_, buffer_+bytes_read); + delete[] buffer_; + return bytes_read; +} + +size_t +Serial::read (std::string &buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + uint8_t *buffer_ = new uint8_t[size]; + size_t bytes_read = 0; + try { + bytes_read = this->pimpl_->read (buffer_, size); + } + catch (const std::exception) { + delete[] buffer_; + throw; + } + buffer.append (reinterpret_cast(buffer_), bytes_read); + delete[] buffer_; + return bytes_read; +} + +string +Serial::read (size_t size) +{ + std::string buffer; + this->read (buffer, size); + return buffer; +} + +size_t +Serial::readline (string &buffer, size_t size, string eol) +{ + ScopedReadLock lock(this->pimpl_); + size_t eol_len = eol.length (); + uint8_t *buffer_ = static_cast + (alloca (size * sizeof (uint8_t))); + size_t read_so_far = 0; + while (true) + { + size_t bytes_read = this->read_ (buffer_ + read_so_far, 1); + read_so_far += bytes_read; + if (bytes_read == 0) { + break; // Timeout occured on reading 1 byte + } + if(read_so_far < eol_len) continue; + if (string (reinterpret_cast + (buffer_ + read_so_far - eol_len), eol_len) == eol) { + break; // EOL found + } + if (read_so_far == size) { + break; // Reached the maximum read length + } + } + buffer.append(reinterpret_cast (buffer_), read_so_far); + return read_so_far; +} + +string +Serial::readline (size_t size, string eol) +{ + std::string buffer; + this->readline (buffer, size, eol); + return buffer; +} + +vector +Serial::readlines (size_t size, string eol) +{ + ScopedReadLock lock(this->pimpl_); + std::vector lines; + size_t eol_len = eol.length (); + uint8_t *buffer_ = static_cast + (alloca (size * sizeof (uint8_t))); + size_t read_so_far = 0; + size_t start_of_line = 0; + while (read_so_far < size) { + size_t bytes_read = this->read_ (buffer_+read_so_far, 1); + read_so_far += bytes_read; + if (bytes_read == 0) { + if (start_of_line != read_so_far) { + lines.push_back ( + string (reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + } + break; // Timeout occured on reading 1 byte + } + if(read_so_far < eol_len) continue; + if (string (reinterpret_cast + (buffer_ + read_so_far - eol_len), eol_len) == eol) { + // EOL found + lines.push_back( + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + start_of_line = read_so_far; + } + if (read_so_far == size) { + if (start_of_line != read_so_far) { + lines.push_back( + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + } + break; // Reached the maximum read length + } + } + return lines; +} + +size_t +Serial::write (const string &data) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_ (reinterpret_cast(data.c_str()), + data.length()); +} + +size_t +Serial::write (const std::vector &data) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_ (&data[0], data.size()); +} + +size_t +Serial::write (const uint8_t *data, size_t size) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_(data, size); +} + +size_t +Serial::write_ (const uint8_t *data, size_t length) +{ + return pimpl_->write (data, length); +} + +void +Serial::setPort (const string &port) +{ + ScopedReadLock rlock(this->pimpl_); + ScopedWriteLock wlock(this->pimpl_); + bool was_open = pimpl_->isOpen (); + if (was_open) close(); + pimpl_->setPort (port); + if (was_open) open (); +} + +string +Serial::getPort () const +{ + return pimpl_->getPort (); +} + +void +Serial::setTimeout (serial::Timeout &timeout) +{ + pimpl_->setTimeout (timeout); +} + +serial::Timeout +Serial::getTimeout () const { + return pimpl_->getTimeout (); +} + +void +Serial::setBaudrate (uint32_t baudrate) +{ + pimpl_->setBaudrate (baudrate); +} + +uint32_t +Serial::getBaudrate () const +{ + return uint32_t(pimpl_->getBaudrate ()); +} + +void +Serial::setBytesize (bytesize_t bytesize) +{ + pimpl_->setBytesize (bytesize); +} + +bytesize_t +Serial::getBytesize () const +{ + return pimpl_->getBytesize (); +} + +void +Serial::setParity (parity_t parity) +{ + pimpl_->setParity (parity); +} + +parity_t +Serial::getParity () const +{ + return pimpl_->getParity (); +} + +void +Serial::setStopbits (stopbits_t stopbits) +{ + pimpl_->setStopbits (stopbits); +} + +stopbits_t +Serial::getStopbits () const +{ + return pimpl_->getStopbits (); +} + +void +Serial::setFlowcontrol (flowcontrol_t flowcontrol) +{ + pimpl_->setFlowcontrol (flowcontrol); +} + +flowcontrol_t +Serial::getFlowcontrol () const +{ + return pimpl_->getFlowcontrol (); +} + +void Serial::flush () +{ + ScopedReadLock rlock(this->pimpl_); + ScopedWriteLock wlock(this->pimpl_); + pimpl_->flush (); +} + +void Serial::flushInput () +{ + ScopedReadLock lock(this->pimpl_); + pimpl_->flushInput (); +} + +void Serial::flushOutput () +{ + ScopedWriteLock lock(this->pimpl_); + pimpl_->flushOutput (); +} + +void Serial::sendBreak (int duration) +{ + pimpl_->sendBreak (duration); +} + +void Serial::setBreak (bool level) +{ + pimpl_->setBreak (level); +} + +void Serial::setRTS (bool level) +{ + pimpl_->setRTS (level); +} + +void Serial::setDTR (bool level) +{ + pimpl_->setDTR (level); +} + +bool Serial::waitForChange() +{ + return pimpl_->waitForChange(); +} + +bool Serial::getCTS () +{ + return pimpl_->getCTS (); +} + +bool Serial::getDSR () +{ + return pimpl_->getDSR (); +} + +bool Serial::getRI () +{ + return pimpl_->getRI (); +} + +bool Serial::getCD () +{ + return pimpl_->getCD (); +} diff --git a/third_party/flserial/macos/Classes/native_libs/src/tinycthread.c b/third_party/flserial/macos/Classes/native_libs/src/tinycthread.c new file mode 100644 index 00000000..182bbc38 --- /dev/null +++ b/third_party/flserial/macos/Classes/native_libs/src/tinycthread.c @@ -0,0 +1,931 @@ +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include "../include/tinycthread.h" +#include + +/* Platform specific includes */ +#if defined(_TTHREAD_POSIX_) + #include + #include + #include + #include + #include +#elif defined(_TTHREAD_WIN32_) + #include + #include +#endif + +/* Standard, good-to-have defines */ +#ifndef NULL + #define NULL (void*)0 +#endif +#ifndef TRUE + #define TRUE 1 +#endif +#ifndef FALSE + #define FALSE 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +int mtx_init(mtx_t *mtx, int type) +{ +#if defined(_TTHREAD_WIN32_) + mtx->mAlreadyLocked = FALSE; + mtx->mRecursive = type & mtx_recursive; + mtx->mTimed = type & mtx_timed; + if (!mtx->mTimed) + { + InitializeCriticalSection(&(mtx->mHandle.cs)); + } + else + { + mtx->mHandle.mut = CreateMutex(NULL, FALSE, NULL); + if (mtx->mHandle.mut == NULL) + { + return thrd_error; + } + } + return thrd_success; +#else + int ret; + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + if (type & mtx_recursive) + { + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + } + ret = pthread_mutex_init(mtx, &attr); + pthread_mutexattr_destroy(&attr); + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +void mtx_destroy(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + if (!mtx->mTimed) + { + DeleteCriticalSection(&(mtx->mHandle.cs)); + } + else + { + CloseHandle(mtx->mHandle.mut); + } +#else + pthread_mutex_destroy(mtx); +#endif +} + +int mtx_lock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + if (!mtx->mTimed) + { + EnterCriticalSection(&(mtx->mHandle.cs)); + } + else + { + switch (WaitForSingleObject(mtx->mHandle.mut, INFINITE)) + { + case WAIT_OBJECT_0: + break; + case WAIT_ABANDONED: + default: + return thrd_error; + } + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + return thrd_success; +#else + return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; +#endif +} + +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec current_ts; + DWORD timeoutMs; + + if (!mtx->mTimed) + { + return thrd_error; + } + + timespec_get(¤t_ts, TIME_UTC); + + if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec))) + { + timeoutMs = 0; + } + else + { + timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000; + timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000; + timeoutMs += 1; + } + + /* TODO: the timeout for WaitForSingleObject doesn't include time + while the computer is asleep. */ + switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs)) + { + case WAIT_OBJECT_0: + break; + case WAIT_TIMEOUT: + return thrd_timedout; + case WAIT_ABANDONED: + default: + return thrd_error; + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + + return thrd_success; +#elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L) + switch (pthread_mutex_timedlock(mtx, ts)) { + case 0: + return thrd_success; + case ETIMEDOUT: + return thrd_timedout; + default: + return thrd_error; + } +#else + int rc; + struct timespec cur, dur; + + /* Try to acquire the lock and, if we fail, sleep for 5ms. */ + while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) { + timespec_get(&cur, TIME_UTC); + + if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec))) + { + break; + } + + dur.tv_sec = ts->tv_sec - cur.tv_sec; + dur.tv_nsec = ts->tv_nsec - cur.tv_nsec; + if (dur.tv_nsec < 0) + { + dur.tv_sec--; + dur.tv_nsec += 1000000000; + } + + if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000)) + { + dur.tv_sec = 0; + dur.tv_nsec = 5000000; + } + + nanosleep(&dur, NULL); + } + + switch (rc) { + case 0: + return thrd_success; + case ETIMEDOUT: + case EBUSY: + return thrd_timedout; + default: + return thrd_error; + } +#endif +} + +int mtx_trylock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + int ret; + + if (!mtx->mTimed) + { + ret = TryEnterCriticalSection(&(mtx->mHandle.cs)) ? thrd_success : thrd_busy; + } + else + { + ret = (WaitForSingleObject(mtx->mHandle.mut, 0) == WAIT_OBJECT_0) ? thrd_success : thrd_busy; + } + + if ((!mtx->mRecursive) && (ret == thrd_success)) + { + if (mtx->mAlreadyLocked) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + ret = thrd_busy; + } + else + { + mtx->mAlreadyLocked = TRUE; + } + } + return ret; +#else + return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy; +#endif +} + +int mtx_unlock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + mtx->mAlreadyLocked = FALSE; + if (!mtx->mTimed) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + } + else + { + if (!ReleaseMutex(mtx->mHandle.mut)) + { + return thrd_error; + } + } + return thrd_success; +#else + return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;; +#endif +} + +#if defined(_TTHREAD_WIN32_) +#define _CONDITION_EVENT_ONE 0 +#define _CONDITION_EVENT_ALL 1 +#endif + +int cnd_init(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + cond->mWaitersCount = 0; + + /* Init critical section */ + InitializeCriticalSection(&cond->mWaitersCountLock); + + /* Init events */ + cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL) + { + cond->mEvents[_CONDITION_EVENT_ALL] = NULL; + return thrd_error; + } + cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + cond->mEvents[_CONDITION_EVENT_ONE] = NULL; + return thrd_error; + } + + return thrd_success; +#else + return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error; +#endif +} + +void cnd_destroy(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + } + if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]); + } + DeleteCriticalSection(&cond->mWaitersCountLock); +#else + pthread_cond_destroy(cond); +#endif +} + +int cnd_signal(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + int haveWaiters; + + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0) + { + return thrd_error; + } + } + + return thrd_success; +#else + return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; +#endif +} + +int cnd_broadcast(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + int haveWaiters; + + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + return thrd_error; + } + } + + return thrd_success; +#else + return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout) +{ + DWORD result; + int lastWaiter; + + /* Increment number of waiters */ + EnterCriticalSection(&cond->mWaitersCountLock); + ++ cond->mWaitersCount; + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* Release the mutex while waiting for the condition (will decrease + the number of waiters when done)... */ + mtx_unlock(mtx); + + /* Wait for either event to become signaled due to cnd_signal() or + cnd_broadcast() being called */ + result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout); + if (result == WAIT_TIMEOUT) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_timedout; + } + else if (result == WAIT_FAILED) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + + /* Check if we are the last waiter */ + EnterCriticalSection(&cond->mWaitersCountLock); + -- cond->mWaitersCount; + lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) && + (cond->mWaitersCount == 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we are the last waiter to be notified to stop waiting, reset the event */ + if (lastWaiter) + { + if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + } + + /* Re-acquire the mutex */ + mtx_lock(mtx); + + return thrd_success; +} +#endif + +int cnd_wait(cnd_t *cond, mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + return _cnd_timedwait_win32(cond, mtx, INFINITE); +#else + return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error; +#endif +} + +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec now; + if (timespec_get(&now, TIME_UTC) == TIME_UTC) + { + unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000; + unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000; + DWORD delta = (tsInMilliseconds > nowInMilliseconds) ? + (DWORD)(tsInMilliseconds - nowInMilliseconds) : 0; + return _cnd_timedwait_win32(cond, mtx, delta); + } + else + return thrd_error; +#else + int ret; + ret = pthread_cond_timedwait(cond, mtx, ts); + if (ret == ETIMEDOUT) + { + return thrd_timedout; + } + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +struct TinyCThreadTSSData { + void* value; + tss_t key; + struct TinyCThreadTSSData* next; +}; + +static tss_dtor_t _tinycthread_tss_dtors[1088] = { NULL, }; + +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_head = NULL; +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_tail = NULL; + +static void _tinycthread_tss_cleanup (void); + +static void _tinycthread_tss_cleanup (void) { + struct TinyCThreadTSSData* data; + int iteration; + unsigned int again = 1; + void* value; + + for (iteration = 0 ; iteration < TSS_DTOR_ITERATIONS && again > 0 ; iteration++) + { + again = 0; + for (data = _tinycthread_tss_head ; data != NULL ; data = data->next) + { + if (data->value != NULL) + { + value = data->value; + data->value = NULL; + + if (_tinycthread_tss_dtors[data->key] != NULL) + { + again = 1; + _tinycthread_tss_dtors[data->key](value); + } + } + } + } + + while (_tinycthread_tss_head != NULL) { + data = _tinycthread_tss_head->next; + free (_tinycthread_tss_head); + _tinycthread_tss_head = data; + } + _tinycthread_tss_head = NULL; + _tinycthread_tss_tail = NULL; +} + +static void NTAPI _tinycthread_tss_callback(PVOID h, DWORD dwReason, PVOID pv) +{ + (void)h; + (void)pv; + + if (_tinycthread_tss_head != NULL && (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH)) + { + _tinycthread_tss_cleanup(); + } +} + +#if defined(_MSC_VER) + #ifdef _M_X64 + #pragma const_seg(".CRT$XLB") + #else + #pragma data_seg(".CRT$XLB") + #endif + PIMAGE_TLS_CALLBACK p_thread_callback = _tinycthread_tss_callback; + #ifdef _M_X64 + #pragma data_seg() + #else + #pragma const_seg() + #endif +#else + PIMAGE_TLS_CALLBACK p_thread_callback __attribute__((section(".CRT$XLB"))) = _tinycthread_tss_callback; +#endif + +#endif /* defined(_TTHREAD_WIN32_) */ + +/** Information to pass to the new thread (what to run). */ +typedef struct { + thrd_start_t mFunction; /**< Pointer to the function to be executed. */ + void * mArg; /**< Function argument for the thread function. */ +} _thread_start_info; + +/* Thread wrapper function. */ +#if defined(_TTHREAD_WIN32_) +static DWORD WINAPI _thrd_wrapper_function(LPVOID aArg) +#elif defined(_TTHREAD_POSIX_) +static void * _thrd_wrapper_function(void * aArg) +#endif +{ + thrd_start_t fun; + void *arg; + int res; + + /* Get thread startup information */ + _thread_start_info *ti = (_thread_start_info *) aArg; + fun = ti->mFunction; + arg = ti->mArg; + + /* The thread is responsible for freeing the startup information */ + free((void *)ti); + + /* Call the actual client thread function */ + res = fun(arg); + +#if defined(_TTHREAD_WIN32_) + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + return (DWORD)res; +#else + return (void*)(intptr_t)res; +#endif +} + +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) +{ + /* Fill out the thread startup information (passed to the thread wrapper, + which will eventually free it) */ + _thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info)); + if (ti == NULL) + { + return thrd_nomem; + } + ti->mFunction = func; + ti->mArg = arg; + + /* Create the thread */ +#if defined(_TTHREAD_WIN32_) + *thr = CreateThread(NULL, 0, _thrd_wrapper_function, (LPVOID) ti, 0, NULL); +#elif defined(_TTHREAD_POSIX_) + if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0) + { + *thr = 0; + } +#endif + + /* Did we fail to create the thread? */ + if(!*thr) + { + free(ti); + return thrd_error; + } + + return thrd_success; +} + +thrd_t thrd_current(void) +{ +#if defined(_TTHREAD_WIN32_) + return GetCurrentThread(); +#else + return pthread_self(); +#endif +} + +int thrd_detach(thrd_t thr) +{ +#if defined(_TTHREAD_WIN32_) + /* https://stackoverflow.com/questions/12744324/how-to-detach-a-thread-on-windows-c#answer-12746081 */ + return CloseHandle(thr) != 0 ? thrd_success : thrd_error; +#else + return pthread_detach(thr) == 0 ? thrd_success : thrd_error; +#endif +} + +int thrd_equal(thrd_t thr0, thrd_t thr1) +{ +#if defined(_TTHREAD_WIN32_) + return GetThreadId(thr0) == GetThreadId(thr1); +#else + return pthread_equal(thr0, thr1); +#endif +} + +void thrd_exit(int res) +{ +#if defined(_TTHREAD_WIN32_) + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + ExitThread((DWORD)res); +#else + pthread_exit((void*)(intptr_t)res); +#endif +} + +int thrd_join(thrd_t thr, int *res) +{ +#if defined(_TTHREAD_WIN32_) + DWORD dwRes; + + if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED) + { + return thrd_error; + } + if (res != NULL) + { + if (GetExitCodeThread(thr, &dwRes) != 0) + { + *res = (int) dwRes; + } + else + { + return thrd_error; + } + } + CloseHandle(thr); +#elif defined(_TTHREAD_POSIX_) + void *pres; + if (pthread_join(thr, &pres) != 0) + { + return thrd_error; + } + if (res != NULL) + { + *res = (int)(intptr_t)pres; + } +#endif + return thrd_success; +} + +int thrd_sleep(const struct timespec *duration, struct timespec *remaining) +{ +#if !defined(_TTHREAD_WIN32_) + int res = nanosleep(duration, remaining); + if (res == 0) { + return 0; + } else if (errno == EINTR) { + return -1; + } else { + return -2; + } +#else + struct timespec start; + DWORD t; + + timespec_get(&start, TIME_UTC); + + t = SleepEx((DWORD)(duration->tv_sec * 1000 + + duration->tv_nsec / 1000000 + + (((duration->tv_nsec % 1000000) == 0) ? 0 : 1)), + TRUE); + + if (t == 0) { + return 0; + } else { + if (remaining != NULL) { + timespec_get(remaining, TIME_UTC); + remaining->tv_sec -= start.tv_sec; + remaining->tv_nsec -= start.tv_nsec; + if (remaining->tv_nsec < 0) + { + remaining->tv_nsec += 1000000000; + remaining->tv_sec -= 1; + } + } + + return (t == WAIT_IO_COMPLETION) ? -1 : -2; + } +#endif +} + +void thrd_yield(void) +{ +#if defined(_TTHREAD_WIN32_) + Sleep(0); +#else + sched_yield(); +#endif +} + +int tss_create(tss_t *key, tss_dtor_t dtor) +{ +#if defined(_TTHREAD_WIN32_) + *key = TlsAlloc(); + if (*key == TLS_OUT_OF_INDEXES) + { + return thrd_error; + } + _tinycthread_tss_dtors[*key] = dtor; +#else + if (pthread_key_create(key, dtor) != 0) + { + return thrd_error; + } +#endif + return thrd_success; +} + +void tss_delete(tss_t key) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*) TlsGetValue (key); + struct TinyCThreadTSSData* prev = NULL; + if (data != NULL) + { + if (data == _tinycthread_tss_head) + { + _tinycthread_tss_head = data->next; + } + else + { + prev = _tinycthread_tss_head; + if (prev != NULL) + { + while (prev->next != data) + { + prev = prev->next; + } + } + } + + if (data == _tinycthread_tss_tail) + { + _tinycthread_tss_tail = prev; + } + + free (data); + } + _tinycthread_tss_dtors[key] = NULL; + TlsFree(key); +#else + pthread_key_delete(key); +#endif +} + +void *tss_get(tss_t key) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + return NULL; + } + return data->value; +#else + return pthread_getspecific(key); +#endif +} + +int tss_set(tss_t key, void *val) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + data = (struct TinyCThreadTSSData*)malloc(sizeof(struct TinyCThreadTSSData)); + if (data == NULL) + { + return thrd_error; + } + + data->value = NULL; + data->key = key; + data->next = NULL; + + if (_tinycthread_tss_tail != NULL) + { + _tinycthread_tss_tail->next = data; + } + else + { + _tinycthread_tss_tail = data; + } + + if (_tinycthread_tss_head == NULL) + { + _tinycthread_tss_head = data; + } + + if (!TlsSetValue(key, data)) + { + free (data); + return thrd_error; + } + } + data->value = val; +#else + if (pthread_setspecific(key, val) != 0) + { + return thrd_error; + } +#endif + return thrd_success; +} + +#if defined(_TTHREAD_EMULATE_TIMESPEC_GET_) +int _tthread_timespec_get(struct timespec *ts, int base) +{ +#if defined(_TTHREAD_WIN32_) + struct _timeb tb; +#elif !defined(CLOCK_REALTIME) + struct timeval tv; +#endif + + if (base != TIME_UTC) + { + return 0; + } + +#if defined(_TTHREAD_WIN32_) + _ftime_s(&tb); + ts->tv_sec = (time_t)tb.time; + ts->tv_nsec = 1000000L * (long)tb.millitm; +#elif defined(CLOCK_REALTIME) + base = (clock_gettime(CLOCK_REALTIME, ts) == 0) ? base : 0; +#else + gettimeofday(&tv, NULL); + ts->tv_sec = (time_t)tv.tv_sec; + ts->tv_nsec = 1000L * (long)tv.tv_usec; +#endif + + return base; +} +#endif /* _TTHREAD_EMULATE_TIMESPEC_GET_ */ + +#if defined(_TTHREAD_WIN32_) +void call_once(once_flag *flag, void (*func)(void)) +{ + /* The idea here is that we use a spin lock (via the + InterlockedCompareExchange function) to restrict access to the + critical section until we have initialized it, then we use the + critical section to block until the callback has completed + execution. */ + while (flag->status < 3) + { + switch (flag->status) + { + case 0: + if (InterlockedCompareExchange (&(flag->status), 1, 0) == 0) { + InitializeCriticalSection(&(flag->lock)); + EnterCriticalSection(&(flag->lock)); + flag->status = 2; + func(); + flag->status = 3; + LeaveCriticalSection(&(flag->lock)); + return; + } + break; + case 1: + break; + case 2: + EnterCriticalSection(&(flag->lock)); + LeaveCriticalSection(&(flag->lock)); + break; + } + } +} +#endif /* defined(_TTHREAD_WIN32_) */ + +#ifdef __cplusplus +} +#endif diff --git a/third_party/flserial/macos/flserial.podspec b/third_party/flserial/macos/flserial.podspec new file mode 100644 index 00000000..7e0c88ad --- /dev/null +++ b/third_party/flserial/macos/flserial.podspec @@ -0,0 +1,27 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint flserial.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'flserial' + s.version = '0.0.1' + s.summary = 'A new Flutter FFI plugin project.' + s.description = <<-DESC +A new Flutter FFI plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + + # This will ensure the source files in Classes/ are included in the native + # builds of apps using this FFI plugin. Podspec does not support relative + # paths, so Classes contains a forwarder C file that relatively imports + # `../src/*` so that the C sources can be shared among all target platforms. + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'FlutterMacOS' + + s.platform = :osx, '10.11' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } + s.swift_version = '5.0' +end diff --git a/third_party/flserial/pubspec.yaml b/third_party/flserial/pubspec.yaml new file mode 100644 index 00000000..5b9098c7 --- /dev/null +++ b/third_party/flserial/pubspec.yaml @@ -0,0 +1,80 @@ +name: flserial +description: "Flutter Serial Port Plugin FFI based on great C library. Useful to communicate with RS232 devices." +version: 0.3.5 +homepage: https://github.com/grzesl/flserial + +environment: + sdk: ^3.4.0 + flutter: '>=3.3.0' + +dependencies: + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + ffi: ^2.1.3 + test: ^1.25.7 + +dev_dependencies: + ffigen: ^19.1.0 + flutter_test: + sdk: flutter + flutter_lints: ^5.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + # This section identifies this Flutter project as a plugin project. + # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.) + # which should be registered in the plugin registry. This is required for + # using method channels. + # The Android 'package' specifies package in which the registered class is. + # This is required for using method channels on Android. + # The 'ffiPlugin' specifies that native code should be built and bundled. + # This is required for using `dart:ffi`. + # All these are used by the tooling to maintain consistency when + # adding or updating assets for this project. + # + # Please refer to README.md for a detailed explanation. + plugin: + platforms: + macos: + ffiPlugin: true + android: + ffiPlugin: true + linux: + ffiPlugin: true + windows: + ffiPlugin: true + + # To add assets to your plugin package, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + # + # For details regarding assets in packages, see + # https://flutter.dev/to/asset-from-package + # + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # To add custom fonts to your plugin package, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts in packages, see + # https://flutter.dev/to/font-from-package diff --git a/third_party/flserial/src/CMakeLists.txt b/third_party/flserial/src/CMakeLists.txt new file mode 100644 index 00000000..6a914c05 --- /dev/null +++ b/third_party/flserial/src/CMakeLists.txt @@ -0,0 +1,58 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +project(flserial_library VERSION 0.3.5 LANGUAGES C CXX) + +if(MSVC) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) +endif() + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +set(SRC_FILES + "native_libs/src/serial.cpp" + "native_libs/src/tinycthread.c" + "native_libs/src/ringbuffer.c" + "flserial.cpp" + "flserial.def" +) + +if(APPLE) + list(APPEND SRC_FILES native_libs/src/impl/unix.cpp) + list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_osx.cpp) +elseif(ANDROID) + list(APPEND SRC_FILES native_libs/src/cglob.c) + list(APPEND SRC_FILES native_libs/src/impl/unix.cpp) + list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_linux.cpp) +elseif(UNIX) + list(APPEND SRC_FILES native_libs/src/impl/unix.cpp) + list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_linux.cpp) +else() + list(APPEND SRC_FILES native_libs/src/impl/win.cpp) + list(APPEND SRC_FILES native_libs/src/impl/list_ports/list_ports_win.cpp) +endif() + +add_library(flserial SHARED ${SRC_FILES}) + +if(APPLE) +elseif(ANDROID) + target_link_options(flserial PRIVATE "-Wl,-z,max-page-size=16384") +elseif(UNIX) + target_link_libraries(flserial rt pthread) +else() + target_link_libraries(flserial setupapi) +endif() + + + + +include_directories(native_libs/include native_libs/include/serial) + +set_target_properties(flserial PROPERTIES + PUBLIC_HEADER flserial.h + OUTPUT_NAME "flserial" +) + +target_compile_definitions(flserial PUBLIC DART_SHARED_LIB) diff --git a/third_party/flserial/src/flserial.cpp b/third_party/flserial/src/flserial.cpp new file mode 100644 index 00000000..a58206e6 --- /dev/null +++ b/third_party/flserial/src/flserial.cpp @@ -0,0 +1,391 @@ +#include "flserial.h" +#include "native_libs/include/serial/serial.h" +#include "native_libs/include/tinycthread.h" +#include "native_libs/include/ringbuffer.h" +#include + +#define FL_SERIAL_BUFF_LEN (8 * 1024) + +typedef struct _flserial_ +{ + char portname[MAX_PORT_NAME_LEN + 1]; + int baudrate; + serial::Serial *serialport; + enum FlError lasterror; + char lasterrormsg[512]; + thrd_t cthread; + int breakThread; + ring_buffer_t cinfifo; + ring_buffer_t coutfifo; + char inbuff[FL_SERIAL_BUFF_LEN]; + char outbuff[FL_SERIAL_BUFF_LEN]; + mtx_t inFifo_mutex; + mtx_t outFifo_mutex; + flcallback callback; +} FlSerial; + +int SerialThread(void *aArg) +{ + FlSerial *serial = (FlSerial *)aArg; + ring_buffer_size_t res = 0; + uint8_t buff[FL_SERIAL_BUFF_LEN]; + ring_buffer_size_t len = sizeof(buff); + ring_buffer_size_t total = 0; + int isEmpty = 0; + + while (!serial->breakThread) + { + try + { + res = (int)serial->serialport->read((uint8_t *)buff, (size_t)len); + if (res > 0) + { + mtx_lock(&serial->inFifo_mutex); + ring_buffer_queue_arr(&serial->cinfifo, (const char *)buff, res); + mtx_unlock(&serial->inFifo_mutex); + total += res; + if(!serial->serialport->available()){ + // fl_open starts this thread before Dart reaches + // fl_set_callback. A companion that transmits as soon as + // the port opens otherwise calls a null function pointer. + while (serial->callback == nullptr && !serial->breakThread) + { + const struct timespec wait = {0, 1000000L}; + thrd_sleep(&wait, NULL); + } + if (serial->breakThread) + break; + serial->callback(0, total); + total = 0; + } else { + continue; + } + } + + mtx_lock(&serial->outFifo_mutex); + res = (ring_buffer_size_t)ring_buffer_dequeue_arr(&serial->coutfifo, (char *)buff, (int)len); + mtx_unlock(&serial->outFifo_mutex); + if (res > 0) { + res = (int)serial->serialport->write((uint8_t*)buff, (size_t)res); + } + + + } + catch (const serial::IOException &ioe) + { + serial->lasterror = FL_ERROR_IO; + strncpy(serial->lasterrormsg , ioe.what(), sizeof(serial->lasterrormsg) - 1); + } + } + + return 0; +} + +FlSerial *flserial_tab[MAX_PORT_COUNT]; +int flserial_count; +int current_port; + +/// Internal helper: close a single slot and null it out. +/// Safe to call with a NULL entry — returns immediately. +/// Sets breakThread=1 then calls thrd_join() so the SerialThread is +/// guaranteed to have exited before this function returns. This is the +/// critical ordering that prevents the Dart NativeCallable from being +/// invoked after the isolate has freed it ("Callback invoked after it has +/// been deleted"). +static void _fl_close_slot(int slot) +{ + FlSerial *port = flserial_tab[slot]; + if (port == NULL) + return; + + port->breakThread = 1; + + try + { + if (port->cthread != 0) + thrd_join(port->cthread, NULL); + + port->serialport->close(); + + mtx_destroy(&port->inFifo_mutex); + mtx_destroy(&port->outFifo_mutex); + } + catch (const std::exception &) + { + } + + delete port->serialport; + port->serialport = NULL; + delete port; + flserial_tab[slot] = NULL; +} + +FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb) +{ + FlSerial *port = flserial_tab[flh]; + port->callback = cb; + return 0; +} + +FFI_PLUGIN_EXPORT int fl_init(int portCount) +{ + if (portCount > MAX_PORT_COUNT) + return 1; + + flserial_count = portCount; + current_port = -1; + + return 0; +} + +FFI_PLUGIN_EXPORT int fl_open(int flh, char *portname, int baudrate) +{ + int porth = flh; + + if (porth < 0) + porth = ++current_port; + + // If a previous FlSerial (and its SerialThread) is alive in this slot, + // join and free it before overwriting. On Dart hot restart the isolate + // dies without calling fl_close(), leaving the old thread running with a + // dangling NativeCallable pointer. Joining here prevents the crash. + _fl_close_slot(porth); + + FlSerial *port = new FlSerial(); + port->breakThread = 0; + port->callback = nullptr; + port->cthread = 0; + port->serialport = nullptr; + + flserial_tab[porth] = port; + + strncpy(port->portname, portname, MAX_PORT_NAME_LEN); + + port->baudrate = baudrate; + port->lasterror = FL_ERROR_OK; + + port->serialport = new serial::Serial(); +#if !defined(__linux__) && !defined(__APPLE__) + port->serialport->setTimeout(serial::Timeout(0, 2, 0, 0, 0)); +#endif // #if defined(__linux__) + port->serialport->setPort(portname); + port->serialport->setBaudrate(baudrate); + + try + { + port->serialport->open(); + + ring_buffer_init(&port->cinfifo, port->inbuff, FL_SERIAL_BUFF_LEN ); + ring_buffer_init(&port->coutfifo, port->outbuff, FL_SERIAL_BUFF_LEN ); + + port->serialport->setBytesize(serial::bytesize_t::eightbits); + port->serialport->setParity(serial::parity_t::parity_none); + port->serialport->setStopbits(serial::stopbits_one); + mtx_init(&port->inFifo_mutex, mtx_plain); + mtx_init(&port->outFifo_mutex, mtx_plain); + port->callback = nullptr; + thrd_create(&port->cthread, SerialThread, (void *)port); + } + catch (const serial::IOException &ioe) + { + strncpy(port->lasterrormsg, ioe.what(), sizeof(port->lasterrormsg) - 1); + + switch (ioe.getErrorNumber()) + { + case 1: + port->lasterror = FlError::FL_ERROR_PORT_NOT_EXIST; + break; + case 2: + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + break; + default: + port->lasterror = FlError::FL_ERROR_UNKNOW; + break; + } + } + catch (const std::exception) + { + port->lasterror = FlError::FL_ERROR_UNKNOW; + } + + return porth; +} + +FFI_PLUGIN_EXPORT int fl_ports(int index, int buffsize, char *buff) +{ + auto list = serial::list_ports(); + if (serial::list_ports().size() <= index) + { + return 0; + } + else + { + serial::PortInfo info = list[index]; + return snprintf(buff, buffsize, "%s - %s - %s", info.port.c_str(), info.description.c_str(), info.hardware_id.c_str()); + } +} + +FFI_PLUGIN_EXPORT int fl_read(int flh, int len, char *buff) +{ + FlSerial *port = flserial_tab[flh]; + ring_buffer_size_t res = 0; + + char *buf = NULL; + ring_buffer_size_t size = 0; + ring_buffer_size_t read = 0; + + mtx_lock(&port->inFifo_mutex); + read = ring_buffer_dequeue_arr(&port->cinfifo, buff, (ring_buffer_size_t) len); + mtx_unlock(&port->inFifo_mutex); + + return (int)read; +} + +FFI_PLUGIN_EXPORT int fl_write(int flh, int len, char *data) +{ + FlSerial *port = flserial_tab[flh]; + int res = 0; + try + { + mtx_lock(&port->outFifo_mutex); + ring_buffer_queue_arr(&port->coutfifo, data, len); + mtx_unlock(&port->outFifo_mutex); + } + catch (const std::exception &) + { + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + } + + return res; +} + +FFI_PLUGIN_EXPORT int fl_close(int flh) +{ + _fl_close_slot(flh); + return 0; +} + +FFI_PLUGIN_EXPORT int fl_ctrl(int flh, FlCtrl param, int value) +{ + + int result = -1; + FlSerial *port = flserial_tab[flh]; + + try + { + switch (param) + { + case FL_CTRL_IS_PORT_OPEN: + result = port->serialport->isOpen() ? 1 : 0; + break; + case FL_CTRL_LAST_ERROR: + result = port->lasterror; + break; + case FL_CTRL_BREAK: + port->serialport->setBreak(); + result = FL_ERROR_OK; + break; + case FL_CTRL_SET_RTS: + port->serialport->setRTS(value > 0 ? true : false); + result = FL_ERROR_OK; + break; + case FL_CTRL_GET_CTS: + result = port->serialport->getCTS() ? 1 : 0; + break; + case FL_CTRL_SET_DTR: + port->serialport->setDTR(value > 0 ? true : false); + result = FL_ERROR_OK; + break; + case FL_CTRL_GET_DSR: + result = port->serialport->getDSR() ? 1 : 0; + break; + + case FL_CTRL_SET_BYTESIZE_5: + port->serialport->setBytesize(serial::bytesize_t::fivebits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_6: + port->serialport->setBytesize(serial::bytesize_t::sixbits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_7: + port->serialport->setBytesize(serial::bytesize_t::sevenbits); + result = 1; + break; + case FL_CTRL_SET_BYTESIZE_8: + port->serialport->setBytesize(serial::bytesize_t::eightbits); + result = 1; + break; + case FL_CTRL_SET_PARITY_NONE: + port->serialport->setParity(serial::parity_t::parity_none); + result = 1; + break; + case FL_CTRL_SET_PARITY_ODD: + port->serialport->setParity(serial::parity_t::parity_odd); + result = 1; + break; + case FL_CTRL_SET_PARITY_EVEN: + port->serialport->setParity(serial::parity_t::parity_even); + result = 1; + break; + case FL_CTRL_SET_PARITY_MARK: + port->serialport->setParity(serial::parity_t::parity_mark); + result = 1; + break; + case FL_CTRL_SET_PARITY_SPACE: + port->serialport->setParity(serial::parity_t::parity_space); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_ONE: + port->serialport->setStopbits(serial::stopbits_t::stopbits_one); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_TWO: + port->serialport->setStopbits(serial::stopbits_t::stopbits_two); + result = 1; + break; + case FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE: + port->serialport->setStopbits(serial::stopbits_t::stopbits_one_point_five); + result = 1; + break; + case FL_CTRL_SET_FLOWCONTROL_NONE: + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_none); + result = 1; + break; + case FL_CTRL_SET_FLOWCONTROL_HARDWARE: + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_hardware); + result = 1; + break; + port->serialport->setFlowcontrol(serial::flowcontrol_t::flowcontrol_software); + result = 1; + case FL_CTRL_SET_FLOWCONTROL_SOFTWARE: + break; + case FL_CTRL_GET_STATUS_CHANGE: + port->serialport->waitForChange(); + result = 1; + break; + + default: + result = -1; + break; + } + } + catch (const std::exception &) + { + port->lasterror = FlError::FL_ERROR_PORT_ALLREADY_OPEN; + } + return result; +} + +FFI_PLUGIN_EXPORT int fl_free(void) +{ + // Join every live SerialThread before the Dart isolate tears down on hot + // restart. Without this, threads holding freed NativeCallable pointers + // crash with "Callback invoked after it has been deleted". + for (int i = 0; i < MAX_PORT_COUNT; i++) + _fl_close_slot(i); + + flserial_count = 0; + current_port = -1; + return 0; +} diff --git a/third_party/flserial/src/flserial.def b/third_party/flserial/src/flserial.def new file mode 100644 index 00000000..9425a774 --- /dev/null +++ b/third_party/flserial/src/flserial.def @@ -0,0 +1,11 @@ +LIBRARY flserial +EXPORTS + fl_init + fl_open + fl_read + fl_write + fl_close + fl_ctrl + fl_free + fl_ports + fl_set_callback \ No newline at end of file diff --git a/third_party/flserial/src/flserial.h b/third_party/flserial/src/flserial.h new file mode 100644 index 00000000..88f0b11c --- /dev/null +++ b/third_party/flserial/src/flserial.h @@ -0,0 +1,79 @@ +#include +#include +#include + +#if _WIN32 +#include +#else +#include +#include +#endif + +#if _WIN32 +#define FFI_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FFI_PLUGIN_EXPORT +#endif + + +#define MAX_PORT_FIFO_LEN 256*1024 +#define MAX_PORT_NAME_LEN 512 +#define MAX_PORT_COUNT 16 + +typedef enum FlCtrl { + FL_CTRL_LAST_ERROR, + FL_CTRL_IS_PORT_OPEN, + FL_CTRL_BREAK, + FL_CTRL_SET_RTS, + FL_CTRL_GET_CTS, + FL_CTRL_SET_DTR, + FL_CTRL_GET_DSR, + FL_CTRL_SET_BYTESIZE_5, + FL_CTRL_SET_BYTESIZE_6, + FL_CTRL_SET_BYTESIZE_7, + FL_CTRL_SET_BYTESIZE_8, + FL_CTRL_SET_PARITY_NONE, + FL_CTRL_SET_PARITY_ODD, + FL_CTRL_SET_PARITY_EVEN, + FL_CTRL_SET_PARITY_MARK, + FL_CTRL_SET_PARITY_SPACE, + FL_CTRL_SET_STOPBITS_ONE, + FL_CTRL_SET_STOPBITS_TWO, + FL_CTRL_SET_STOPBITS_ONE_POINT_FIVE, + FL_CTRL_SET_FLOWCONTROL_NONE, + FL_CTRL_SET_FLOWCONTROL_HARDWARE, + FL_CTRL_SET_FLOWCONTROL_SOFTWARE, + FL_CTRL_GET_STATUS_CHANGE, + FL_CTRL_LAST, +} FlCtrl; + +typedef enum FlError { + FL_ERROR_OK, + FL_ERROR_UNKNOW, + FL_ERROR_PORT_ALLREADY_OPEN, + FL_ERROR_PORT_NOT_EXIST, + FL_ERROR_IO, + FL_ERROR_HANDLER, + FL_ERROR_LAST, +} FlError; + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*flcallback)(unsigned int, unsigned int); + +FFI_PLUGIN_EXPORT int fl_init (int portCount); +FFI_PLUGIN_EXPORT int fl_set_callback(int flh, flcallback cb); +FFI_PLUGIN_EXPORT int fl_ports (int index, int buffsize, char *buff); +FFI_PLUGIN_EXPORT int fl_open (int flh, char *portname, int baudrate); +FFI_PLUGIN_EXPORT int fl_read (int flh, int len, char *buff); +FFI_PLUGIN_EXPORT int fl_write (int flh, int len, char *data); +FFI_PLUGIN_EXPORT int fl_close (int flh); +FFI_PLUGIN_EXPORT int fl_ctrl (int flh, FlCtrl param, int value); +FFI_PLUGIN_EXPORT int fl_free (void); + + +#ifdef __cplusplus +} +#endif diff --git a/third_party/flserial/src/native_libs/include/cglob.h b/third_party/flserial/src/native_libs/include/cglob.h new file mode 100644 index 00000000..8da8abd9 --- /dev/null +++ b/third_party/flserial/src/native_libs/include/cglob.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)glob.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD$ + */ + +#ifndef _GLOB_H_ +#define _GLOB_H_ + +#include +#include + +#ifndef _SIZE_T_DECLARED +typedef size_t __size_t; +#define _SIZE_T_DECLARED +#endif + +struct stat; +typedef struct { + size_t gl_pathc; /* Count of total paths so far. */ + size_t gl_matchc; /* Count of paths matching pattern. */ + size_t gl_offs; /* Reserved at beginning of gl_pathv. */ + int gl_flags; /* Copy of flags parameter to glob. */ + char **gl_pathv; /* List of paths matching pattern. */ + /* Copy of errfunc parameter to glob. */ + int (*gl_errfunc)(const char *, int); + + /* + * Alternate filesystem access methods for glob; replacement + * versions of closedir(3), readdir(3), opendir(3), stat(2) + * and lstat(2). + */ + void (*gl_closedir)(void *); + struct dirent *(*gl_readdir)(void *); + void *(*gl_opendir)(const char *); + int (*gl_lstat)(const char *, struct stat *); + int (*gl_stat)(const char *, struct stat *); +} cglob_t; + + +/* Believed to have been introduced in 1003.2-1992 */ +#define GLOB_APPEND 0x0001 /* Append to output from previous call. */ +#define GLOB_DOOFFS 0x0002 /* Use gl_offs. */ +#define GLOB_ERR 0x0004 /* Return on error. */ +#define GLOB_MARK 0x0008 /* Append / to matching directories. */ +#define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */ +#define GLOB_NOSORT 0x0020 /* Don't sort. */ +#define GLOB_NOESCAPE 0x2000 /* Disable backslash escaping. */ + +/* Error values returned by glob(3) */ +#define GLOB_NOSPACE (-1) /* Malloc call failed. */ +#define GLOB_ABORTED (-2) /* Unignored error. */ +#define GLOB_NOMATCH (-3) /* No match and GLOB_NOCHECK was not set. */ +#define GLOB_NOSYS (-4) /* Obsolete: source comptability only. */ + + + +#define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */ +#define GLOB_BRACE 0x0080 /* Expand braces ala csh. */ +#define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */ +#define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */ +#define GLOB_QUOTE 0x0400 /* Quote special chars with \. */ +#define GLOB_TILDE 0x0800 /* Expand tilde names from the passwd file. */ +#define GLOB_LIMIT 0x1000 /* limit number of returned paths */ + +/* source compatibility, these are the old names */ +#define GLOB_MAXPATH GLOB_LIMIT +#define GLOB_ABEND GLOB_ABORTED + +__BEGIN_DECLS +int cglob(const char *, int, int (*)(const char *, int), cglob_t *); +void cglobfree(cglob_t *); +__END_DECLS + +#endif /* !_GLOB_H_ */ diff --git a/third_party/flserial/src/native_libs/include/ringbuffer.h b/third_party/flserial/src/native_libs/include/ringbuffer.h new file mode 100644 index 00000000..36da6eb1 --- /dev/null +++ b/third_party/flserial/src/native_libs/include/ringbuffer.h @@ -0,0 +1,144 @@ +#include +#include +#include +/** + * @file + * Prototypes and structures for the ring buffer module. + */ + +#ifndef RINGBUFFER_H +#define RINGBUFFER_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define RING_BUFFER_ASSERT(x) assert(x) + +/** + * Checks if the buffer_size is a power of two. + * Due to the design only RING_BUFFER_SIZE-1 items + * can be contained in the buffer. + * buffer_size must be a power of two. +*/ +#define RING_BUFFER_IS_POWER_OF_TWO(buffer_size) ((buffer_size & (buffer_size - 1)) == 0) + +/** + * The type which is used to hold the size + * and the indicies of the buffer. + */ +typedef size_t ring_buffer_size_t; + +/** + * Used as a modulo operator + * as a % b = (a & (b − 1)) + * where \c a is a positive index in the buffer and + * \c b is the (power of two) size of the buffer. + */ +#define RING_BUFFER_MASK(rb) (rb->buffer_mask) + +/** + * Simplifies the use of struct ring_buffer_t. + */ +typedef struct ring_buffer_t ring_buffer_t; + +/** + * Structure which holds a ring buffer. + * The buffer contains a buffer array + * as well as metadata for the ring buffer. + */ +struct ring_buffer_t { + /** Buffer memory. */ + char *buffer; + /** Buffer mask. */ + ring_buffer_size_t buffer_mask; + /** Index of tail. */ + ring_buffer_size_t tail_index; + /** Index of head. */ + ring_buffer_size_t head_index; +}; + +/** + * Initializes the ring buffer pointed to by buffer. + * This function can also be used to empty/reset the buffer. + * The resulting buffer can contain buf_size-1 bytes. + * @param buffer The ring buffer to initialize. + * @param buf The buffer allocated for the ringbuffer. + * @param buf_size The size of the allocated ringbuffer. + */ +void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size); + +/** + * Adds a byte to a ring buffer. + * @param buffer The buffer in which the data should be placed. + * @param data The byte to place. + */ +void ring_buffer_queue(ring_buffer_t *buffer, char data); + +/** + * Adds an array of bytes to a ring buffer. + * @param buffer The buffer in which the data should be placed. + * @param data A pointer to the array of bytes to place in the queue. + * @param size The size of the array. + */ +void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size); + +/** + * Returns the oldest byte in a ring buffer. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the location at which the data should be placed. + * @return 1 if data was returned; 0 otherwise. + */ +uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data); + +/** + * Returns the len oldest bytes in a ring buffer. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the array at which the data should be placed. + * @param len The maximum number of bytes to return. + * @return The number of bytes returned. + */ +ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len); +/** + * Peeks a ring buffer, i.e. returns an element without removing it. + * @param buffer The buffer from which the data should be returned. + * @param data A pointer to the location at which the data should be placed. + * @param index The index to peek. + * @return 1 if data was returned; 0 otherwise. + */ +uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index); + + +/** + * Returns whether a ring buffer is empty. + * @param buffer The buffer for which it should be returned whether it is empty. + * @return 1 if empty; 0 otherwise. + */ +inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer) { + return (buffer->head_index == buffer->tail_index); +} + +/** + * Returns whether a ring buffer is full. + * @param buffer The buffer for which it should be returned whether it is full. + * @return 1 if full; 0 otherwise. + */ +inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer) { + return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)) == RING_BUFFER_MASK(buffer); +} + +/** + * Returns the number of items in a ring buffer. + * @param buffer The buffer for which the number of items should be returned. + * @return The number of items in the ring buffer. + */ +inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer) { + return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK(buffer)); +} + +#ifdef __cplusplus +} +#endif + +#endif /* RINGBUFFER_H */ diff --git a/third_party/flserial/src/native_libs/include/serial/impl/unix.h b/third_party/flserial/src/native_libs/include/serial/impl/unix.h new file mode 100644 index 00000000..02d85e9d --- /dev/null +++ b/third_party/flserial/src/native_libs/include/serial/impl/unix.h @@ -0,0 +1,221 @@ +/*! + * \file serial/impl/unix.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall, John Harrison + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a unix based pimpl for the Serial class. This implementation is + * based off termios.h and uses select for multiplexing the IO ports. + * + */ + +#if !defined(_WIN32) + +#ifndef SERIAL_IMPL_UNIX_H +#define SERIAL_IMPL_UNIX_H + +#include "../../../include/serial/serial.h" + +#include + +namespace serial { + +using std::size_t; +using std::string; +using std::invalid_argument; + +using serial::SerialException; +using serial::IOException; + +class MillisecondTimer { +public: + MillisecondTimer(const uint32_t millis); + int64_t remaining(); + +private: + static timespec timespec_now(); + timespec expiry; +}; + +class serial::Serial::SerialImpl { +public: + SerialImpl (const string &port, + unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, + stopbits_t stopbits, + flowcontrol_t flowcontrol); + + virtual ~SerialImpl (); + + void + open (); + + void + close (); + + bool + isOpen () const; + + size_t + available (); + + bool + waitReadable (uint32_t timeout); + + void + waitByteTimes (size_t count); + + size_t + read (uint8_t *buf, size_t size = 1); + + size_t + write (const uint8_t *data, size_t length); + + void + flush (); + + void + flushInput (); + + void + flushOutput (); + + void + sendBreak (int duration); + + void + setBreak (bool level); + + void + setRTS (bool level); + + void + setDTR (bool level); + + bool + waitForChange (); + + bool + getCTS (); + + bool + getDSR (); + + bool + getRI (); + + bool + getCD (); + + void + setPort (const string &port); + + string + getPort () const; + + void + setTimeout (Timeout &timeout); + + Timeout + getTimeout () const; + + void + setBaudrate (unsigned long baudrate); + + unsigned long + getBaudrate () const; + + void + setBytesize (bytesize_t bytesize); + + bytesize_t + getBytesize () const; + + void + setParity (parity_t parity); + + parity_t + getParity () const; + + void + setStopbits (stopbits_t stopbits); + + stopbits_t + getStopbits () const; + + void + setFlowcontrol (flowcontrol_t flowcontrol); + + flowcontrol_t + getFlowcontrol () const; + + void + readLock (); + + void + readUnlock (); + + void + writeLock (); + + void + writeUnlock (); + +protected: + void reconfigurePort (); + +private: + string port_; // Path to the file descriptor + int fd_; // The current file descriptor + + bool is_open_; + bool xonxoff_; + bool rtscts_; + + Timeout timeout_; // Timeout for read operations + unsigned long baudrate_; // Baudrate + uint32_t byte_time_ns_; // Nanoseconds to transmit/receive a single byte + + parity_t parity_; // Parity + bytesize_t bytesize_; // Size of the bytes + stopbits_t stopbits_; // Stop Bits + flowcontrol_t flowcontrol_; // Flow Control + + // Mutex used to lock the read functions + pthread_mutex_t read_mutex; + // Mutex used to lock the write functions + pthread_mutex_t write_mutex; +}; + +} + +#endif // SERIAL_IMPL_UNIX_H + +#endif // !defined(_WIN32) diff --git a/third_party/flserial/src/native_libs/include/serial/impl/win.h b/third_party/flserial/src/native_libs/include/serial/impl/win.h new file mode 100644 index 00000000..2c0c6cde --- /dev/null +++ b/third_party/flserial/src/native_libs/include/serial/impl/win.h @@ -0,0 +1,207 @@ +/*! + * \file serial/impl/windows.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall, John Harrison + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a windows implementation of the Serial class interface. + * + */ + +#if defined(_WIN32) + +#ifndef SERIAL_IMPL_WINDOWS_H +#define SERIAL_IMPL_WINDOWS_H + +#include "serial/serial.h" + +#include "windows.h" + +namespace serial { + +using std::string; +using std::wstring; +using std::invalid_argument; + +using serial::SerialException; +using serial::IOException; + +class serial::Serial::SerialImpl { +public: + SerialImpl (const string &port, + unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, + stopbits_t stopbits, + flowcontrol_t flowcontrol); + + virtual ~SerialImpl (); + + void + open (); + + void + close (); + + bool + isOpen () const; + + size_t + available (); + + bool + waitReadable (uint32_t timeout); + + void + waitByteTimes (size_t count); + + size_t + read (uint8_t *buf, size_t size = 1); + + size_t + write (const uint8_t *data, size_t length); + + void + flush (); + + void + flushInput (); + + void + flushOutput (); + + void + sendBreak (int duration); + + void + setBreak (bool level); + + void + setRTS (bool level); + + void + setDTR (bool level); + + bool + waitForChange (); + + bool + getCTS (); + + bool + getDSR (); + + bool + getRI (); + + bool + getCD (); + + void + setPort (const string &port); + + string + getPort () const; + + void + setTimeout (Timeout &timeout); + + Timeout + getTimeout () const; + + void + setBaudrate (unsigned long baudrate); + + unsigned long + getBaudrate () const; + + void + setBytesize (bytesize_t bytesize); + + bytesize_t + getBytesize () const; + + void + setParity (parity_t parity); + + parity_t + getParity () const; + + void + setStopbits (stopbits_t stopbits); + + stopbits_t + getStopbits () const; + + void + setFlowcontrol (flowcontrol_t flowcontrol); + + flowcontrol_t + getFlowcontrol () const; + + void + readLock (); + + void + readUnlock (); + + void + writeLock (); + + void + writeUnlock (); + +protected: + void reconfigurePort (); + +private: + wstring port_; // Path to the file descriptor + HANDLE fd_; + + bool is_open_; + + Timeout timeout_; // Timeout for read operations + unsigned long baudrate_; // Baudrate + + parity_t parity_; // Parity + bytesize_t bytesize_; // Size of the bytes + stopbits_t stopbits_; // Stop Bits + flowcontrol_t flowcontrol_; // Flow Control + + // Mutex used to lock the read functions + HANDLE read_mutex; + // Mutex used to lock the write functions + HANDLE write_mutex; +}; + +} + +#endif // SERIAL_IMPL_WINDOWS_H + +#endif // if defined(_WIN32) diff --git a/third_party/flserial/src/native_libs/include/serial/serial.h b/third_party/flserial/src/native_libs/include/serial/serial.h new file mode 100644 index 00000000..642febf3 --- /dev/null +++ b/third_party/flserial/src/native_libs/include/serial/serial.h @@ -0,0 +1,780 @@ +/*! + * \file serial/serial.h + * \author William Woodall + * \author John Harrison + * \version 0.1 + * + * \section LICENSE + * + * The MIT License + * + * Copyright (c) 2012 William Woodall + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * \section DESCRIPTION + * + * This provides a cross platform interface for interacting with Serial Ports. + */ + +#ifndef SERIAL_H +#define SERIAL_H + +#include +#include +#include +#include +#include +#include +#include +#include "v8stdint.h" + + + +#define THROWEX(exceptionClass, message, errorno) throw exceptionClass(__FILE__, \ +__LINE__, (message), (errorno) ) + +#define THROW(exceptionClass, message) throw exceptionClass(__FILE__, \ +__LINE__, (message) ) + +namespace serial { + +/*! + * Enumeration defines the possible bytesizes for the serial port. + */ +typedef enum { + fivebits = 5, + sixbits = 6, + sevenbits = 7, + eightbits = 8 +} bytesize_t; + +/*! + * Enumeration defines the possible parity types for the serial port. + */ +typedef enum { + parity_none = 0, + parity_odd = 1, + parity_even = 2, + parity_mark = 3, + parity_space = 4 +} parity_t; + +/*! + * Enumeration defines the possible stopbit types for the serial port. + */ +typedef enum { + stopbits_one = 1, + stopbits_two = 2, + stopbits_one_point_five +} stopbits_t; + +/*! + * Enumeration defines the possible flowcontrol types for the serial port. + */ +typedef enum { + flowcontrol_none = 0, + flowcontrol_software, + flowcontrol_hardware +} flowcontrol_t; + +/*! + * Structure for setting the timeout of the serial port, times are + * in milliseconds. + * + * In order to disable the interbyte timeout, set it to Timeout::max(). + */ +struct Timeout { +#ifdef max +# undef max +#endif + static uint32_t max() {return std::numeric_limits::max();} + /*! + * Convenience function to generate Timeout structs using a + * single absolute timeout. + * + * \param timeout A long that defines the time in milliseconds until a + * timeout occurs after a call to read or write is made. + * + * \return Timeout struct that represents this simple timeout provided. + */ + static Timeout simpleTimeout(uint32_t timeout) { + return Timeout(10, timeout, 0, timeout, 0); + } + + /*! Number of milliseconds between bytes received to timeout on. */ + uint32_t inter_byte_timeout; + /*! A constant number of milliseconds to wait after calling read. */ + uint32_t read_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling read. + */ + uint32_t read_timeout_multiplier; + /*! A constant number of milliseconds to wait after calling write. */ + uint32_t write_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling write. + */ + uint32_t write_timeout_multiplier; + + explicit Timeout (uint32_t inter_byte_timeout_=0, + uint32_t read_timeout_constant_=0, + uint32_t read_timeout_multiplier_=0, + uint32_t write_timeout_constant_=0, + uint32_t write_timeout_multiplier_=0) + : inter_byte_timeout(inter_byte_timeout_), + read_timeout_constant(read_timeout_constant_), + read_timeout_multiplier(read_timeout_multiplier_), + write_timeout_constant(write_timeout_constant_), + write_timeout_multiplier(write_timeout_multiplier_) + {} +}; + +/*! + * Class that provides a portable serial port interface. + */ +class Serial { +public: + /*! + * Creates a Serial object and opens the port if a port is specified, + * otherwise it remains closed until serial::Serial::open is called. + * + * \param port A std::string containing the address of the serial port, + * which would be something like 'COM1' on Windows and '/dev/ttyS0' + * on Linux. + * + * \param baudrate An unsigned 32-bit integer that represents the baudrate + * + * \param timeout A serial::Timeout struct that defines the timeout + * conditions for the serial port. \see serial::Timeout + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \param flowcontrol Type of flowcontrol used, default is + * flowcontrol_none, possible values are: flowcontrol_none, + * flowcontrol_software, flowcontrol_hardware + * + * \throw serial::PortNotOpenedException + * \throw serial::IOException + * \throw std::invalid_argument + */ + Serial (const std::string &port = "", + uint32_t baudrate = 9600, + Timeout timeout = Timeout(), + bytesize_t bytesize = eightbits, + parity_t parity = parity_none, + stopbits_t stopbits = stopbits_one, + flowcontrol_t flowcontrol = flowcontrol_none); + + /*! Destructor */ + virtual ~Serial (); + + /*! + * Opens the serial port as long as the port is set and the port isn't + * already open. + * + * If the port is provided to the constructor then an explicit call to open + * is not needed. + * + * \see Serial::Serial + * + * \throw std::invalid_argument + * \throw serial::SerialException + * \throw serial::IOException + */ + void + open (); + + /*! Gets the open status of the serial port. + * + * \return Returns true if the port is open, false otherwise. + */ + bool + isOpen () const; + + /*! Closes the serial port. */ + void + close (); + + /*! Return the number of characters in the buffer. */ + size_t + available (); + + /*! Block until there is serial data to read or read_timeout_constant + * number of milliseconds have elapsed. The return value is true when + * the function exits with the port in a readable state, false otherwise + * (due to timeout or select interruption). */ + bool + waitReadable (); + + /*! Block for a period of time corresponding to the transmission time of + * count characters at present serial settings. This may be used in con- + * junction with waitReadable to read larger blocks of data from the + * port. */ + void + waitByteTimes (size_t count); + + /*! Read a given amount of bytes from the serial port into a given buffer. + * + * The read function will return in one of three cases: + * * The number of requested bytes was read. + * * In this case the number of bytes requested will match the size_t + * returned by read. + * * A timeout occurred, in this case the number of bytes read will not + * match the amount requested, but no exception will be thrown. One of + * two possible timeouts occurred: + * * The inter byte timeout expired, this means that number of + * milliseconds elapsed between receiving bytes from the serial port + * exceeded the inter byte timeout. + * * The total timeout expired, which is calculated by multiplying the + * read timeout multiplier by the number of requested bytes and then + * added to the read timeout constant. If that total number of + * milliseconds elapses after the initial call to read a timeout will + * occur. + * * An exception occurred, in this case an actual exception will be thrown. + * + * \param buffer An uint8_t array of at least the requested size. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (uint8_t *buffer, size_t size); + + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::vector of uint8_t. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::vector &buffer, size_t size = 1); + + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::string. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::string &buffer, size_t size = 1); + + /*! Read a given amount of bytes from the serial port and return a string + * containing the data. + * + * \param size A size_t defining how many bytes to be read. + * + * \return A std::string containing the data read from the port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + read (size_t size = 1); + + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param buffer A std::string reference used to store the data. + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A size_t representing the number of bytes read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + readline (std::string &buffer, size_t size = 65536, std::string eol = "\n"); + + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A std::string containing the line. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + readline (size_t size = 65536, std::string eol = "\n"); + + /*! Reads in multiple lines until the serial port times out. + * + * This requires a timeout > 0 before it can be run. It will read until a + * timeout occurs and return a list of strings. + * + * \param size A maximum length of combined lines, defaults to 65536 (2^16) + * + * \param eol A string to match against for the EOL. + * + * \return A vector containing the lines. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::vector + readlines (size_t size = 65536, std::string eol = "\n"); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \param size A size_t that indicates how many bytes should be written from + * the given data buffer. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const uint8_t *data, size_t size); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::vector &data); + + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::string &data); + + /*! Sets the serial port identifier. + * + * \param port A const std::string reference containing the address of the + * serial port, which would be something like 'COM1' on Windows and + * '/dev/ttyS0' on Linux. + * + * \throw std::invalid_argument + */ + void + setPort (const std::string &port); + + /*! Gets the serial port identifier. + * + * \see Serial::setPort + * + * \throw std::invalid_argument + */ + std::string + getPort () const; + + /*! Sets the timeout for reads and writes using the Timeout struct. + * + * There are two timeout conditions described here: + * * The inter byte timeout: + * * The inter_byte_timeout component of serial::Timeout defines the + * maximum amount of time, in milliseconds, between receiving bytes on + * the serial port that can pass before a timeout occurs. Setting this + * to zero will prevent inter byte timeouts from occurring. + * * Total time timeout: + * * The constant and multiplier component of this timeout condition, + * for both read and write, are defined in serial::Timeout. This + * timeout occurs if the total time since the read or write call was + * made exceeds the specified time in milliseconds. + * * The limit is defined by multiplying the multiplier component by the + * number of requested bytes and adding that product to the constant + * component. In this way if you want a read call, for example, to + * timeout after exactly one second regardless of the number of bytes + * you asked for then set the read_timeout_constant component of + * serial::Timeout to 1000 and the read_timeout_multiplier to zero. + * This timeout condition can be used in conjunction with the inter + * byte timeout condition with out any problems, timeout will simply + * occur when one of the two timeout conditions is met. This allows + * users to have maximum control over the trade-off between + * responsiveness and efficiency. + * + * Read and write functions will return in one of three cases. When the + * reading or writing is complete, when a timeout occurs, or when an + * exception occurs. + * + * A timeout of 0 enables non-blocking mode. + * + * \param timeout A serial::Timeout struct containing the inter byte + * timeout, and the read and write timeout constants and multipliers. + * + * \see serial::Timeout + */ + void + setTimeout (Timeout &timeout); + + /*! Sets the timeout for reads and writes. */ + void + setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant, + uint32_t read_timeout_multiplier, uint32_t write_timeout_constant, + uint32_t write_timeout_multiplier) + { + Timeout timeout(inter_byte_timeout, read_timeout_constant, + read_timeout_multiplier, write_timeout_constant, + write_timeout_multiplier); + return setTimeout(timeout); + } + + /*! Gets the timeout for reads in seconds. + * + * \return A Timeout struct containing the inter_byte_timeout, and read + * and write timeout constants and multipliers. + * + * \see Serial::setTimeout + */ + Timeout + getTimeout () const; + + /*! Sets the baudrate for the serial port. + * + * Possible baudrates depends on the system but some safe baudrates include: + * 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000, + * 57600, 115200 + * Some other baudrates that are supported by some comports: + * 128000, 153600, 230400, 256000, 460800, 500000, 921600 + * + * \param baudrate An integer that sets the baud rate for the serial port. + * + * \throw std::invalid_argument + */ + void + setBaudrate (uint32_t baudrate); + + /*! Gets the baudrate for the serial port. + * + * \return An integer that sets the baud rate for the serial port. + * + * \see Serial::setBaudrate + * + * \throw std::invalid_argument + */ + uint32_t + getBaudrate () const; + + /*! Sets the bytesize for the serial port. + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \throw std::invalid_argument + */ + void + setBytesize (bytesize_t bytesize); + + /*! Gets the bytesize for the serial port. + * + * \see Serial::setBytesize + * + * \throw std::invalid_argument + */ + bytesize_t + getBytesize () const; + + /*! Sets the parity for the serial port. + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \throw std::invalid_argument + */ + void + setParity (parity_t parity); + + /*! Gets the parity for the serial port. + * + * \see Serial::setParity + * + * \throw std::invalid_argument + */ + parity_t + getParity () const; + + /*! Sets the stopbits for the serial port. + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \throw std::invalid_argument + */ + void + setStopbits (stopbits_t stopbits); + + /*! Gets the stopbits for the serial port. + * + * \see Serial::setStopbits + * + * \throw std::invalid_argument + */ + stopbits_t + getStopbits () const; + + /*! Sets the flow control for the serial port. + * + * \param flowcontrol Type of flowcontrol used, default is flowcontrol_none, + * possible values are: flowcontrol_none, flowcontrol_software, + * flowcontrol_hardware + * + * \throw std::invalid_argument + */ + void + setFlowcontrol (flowcontrol_t flowcontrol); + + /*! Gets the flow control for the serial port. + * + * \see Serial::setFlowcontrol + * + * \throw std::invalid_argument + */ + flowcontrol_t + getFlowcontrol () const; + + /*! Flush the input and output buffers */ + void + flush (); + + /*! Flush only the input buffer */ + void + flushInput (); + + /*! Flush only the output buffer */ + void + flushOutput (); + + /*! Sends the RS-232 break signal. See tcsendbreak(3). */ + void + sendBreak (int duration); + + /*! Set the break condition to a given level. Defaults to true. */ + void + setBreak (bool level = true); + + /*! Set the RTS handshaking line to the given level. Defaults to true. */ + void + setRTS (bool level = true); + + /*! Set the DTR handshaking line to the given level. Defaults to true. */ + void + setDTR (bool level = true); + + /*! + * Blocks until CTS, DSR, RI, CD changes or something interrupts it. + * + * Can throw an exception if an error occurs while waiting. + * You can check the status of CTS, DSR, RI, and CD once this returns. + * Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a + * resolution of less than +-1ms and as good as +-0.2ms. Otherwise a + * polling method is used which can give +-2ms. + * + * \return Returns true if one of the lines changed, false if something else + * occurred. + * + * \throw SerialException + */ + bool + waitForChange (); + + /*! Returns the current status of the CTS line. */ + bool + getCTS (); + + /*! Returns the current status of the DSR line. */ + bool + getDSR (); + + /*! Returns the current status of the RI line. */ + bool + getRI (); + + /*! Returns the current status of the CD line. */ + bool + getCD (); + +private: + // Disable copy constructors + Serial(const Serial&); + Serial& operator=(const Serial&); + + // Pimpl idiom, d_pointer + class SerialImpl; + SerialImpl *pimpl_; + + // Scoped Lock Classes + class ScopedReadLock; + class ScopedWriteLock; + + // Read common function + size_t + read_ (uint8_t *buffer, size_t size); + // Write common function + size_t + write_ (const uint8_t *data, size_t length); + +}; + +class SerialException : public std::exception +{ + // Disable copy constructors + SerialException& operator=(const SerialException&); + std::string e_what_; +public: + SerialException (const char *description) { + std::stringstream ss; + ss << "SerialException " << description << " failed."; + e_what_ = ss.str(); + } + SerialException (const SerialException& other) : e_what_(other.e_what_) {} + virtual ~SerialException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +class IOException : public std::exception +{ + // Disable copy constructors + IOException& operator=(const IOException&); + std::string file_; + int line_; + std::string e_what_; + int errno_; +public: + explicit IOException (std::string file, int line, int errnum = 0) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; +#if defined(_WIN32) && !defined(__MINGW32__) + char error_str [1024]; + strerror_s(error_str, 1024, errnum); +#else + char * error_str = strerror(errnum); +#endif + ss << "IO Exception (" << errno_ << "): " << error_str; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + explicit IOException (std::string file, int line, const char * description, int errnum = 0) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; + ss << "IO Exception: " << description; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + virtual ~IOException() throw() {} + IOException (const IOException& other) : line_(other.line_), e_what_(other.e_what_), errno_(other.errno_) {} + + int getErrorNumber () const { return errno_; } + + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +class PortNotOpenedException : public std::exception +{ + // Disable copy constructors + const PortNotOpenedException& operator=(PortNotOpenedException); + std::string e_what_; +public: + PortNotOpenedException (const char * description) { + std::stringstream ss; + ss << "PortNotOpenedException " << description << " failed."; + e_what_ = ss.str(); + } + PortNotOpenedException (const PortNotOpenedException& other) : e_what_(other.e_what_) {} + virtual ~PortNotOpenedException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } +}; + +/*! + * Structure that describes a serial device. + */ +struct PortInfo { + + /*! Address of the serial port (this can be passed to the constructor of Serial). */ + std::string port; + + /*! Human readable description of serial device if available. */ + std::string description; + + /*! Hardware ID (e.g. VID:PID of USB serial devices) or "n/a" if not available. */ + std::string hardware_id; + +}; + +/* Lists the serial ports available on the system + * + * Returns a vector of available serial ports, each represented + * by a serial::PortInfo data structure: + * + * \return vector of serial::PortInfo. + */ +std::vector +list_ports(); + +} // namespace serial + +#endif diff --git a/third_party/flserial/src/native_libs/include/serial/v8stdint.h b/third_party/flserial/src/native_libs/include/serial/v8stdint.h new file mode 100644 index 00000000..f3be96b1 --- /dev/null +++ b/third_party/flserial/src/native_libs/include/serial/v8stdint.h @@ -0,0 +1,57 @@ +// This header is from the v8 google project: +// http://code.google.com/p/v8/source/browse/trunk/include/v8stdint.h + +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Load definitions of standard types. + +#ifndef V8STDINT_H_ +#define V8STDINT_H_ + +#include +#include + +#if defined(_WIN32) && !defined(__MINGW32__) + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; // NOLINT +typedef unsigned short uint16_t; // NOLINT +typedef int int32_t; +typedef unsigned int uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +// intptr_t and friends are defined in crtdefs.h through stdio.h. + +#else + +#include + +#endif + +#endif // V8STDINT_H_ diff --git a/third_party/flserial/src/native_libs/include/tinycthread.h b/third_party/flserial/src/native_libs/include/tinycthread.h new file mode 100644 index 00000000..cb6f3b82 --- /dev/null +++ b/third_party/flserial/src/native_libs/include/tinycthread.h @@ -0,0 +1,485 @@ +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#ifndef _TINYCTHREAD_H_ +#define _TINYCTHREAD_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @file +* @mainpage TinyCThread API Reference +* +* @section intro_sec Introduction +* TinyCThread is a minimal, portable implementation of basic threading +* classes for C. +* +* They closely mimic the functionality and naming of the C11 standard, and +* should be easily replaceable with the corresponding standard variants. +* +* @section port_sec Portability +* The Win32 variant uses the native Win32 API for implementing the thread +* classes, while for other systems, the POSIX threads API (pthread) is used. +* +* @section misc_sec Miscellaneous +* The following special keywords are available: #_Thread_local. +* +* For more detailed information, browse the different sections of this +* documentation. A good place to start is: +* tinycthread.h. +*/ + +/* Which platform are we on? */ +#if !defined(_TTHREAD_PLATFORM_DEFINED_) + #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) + #define _TTHREAD_WIN32_ + #else + #define _TTHREAD_POSIX_ + #endif + #define _TTHREAD_PLATFORM_DEFINED_ +#endif + +/* Activate some POSIX functionality (e.g. clock_gettime and recursive mutexes) */ +#if defined(_TTHREAD_POSIX_) + #undef _FEATURES_H + #if !defined(_GNU_SOURCE) + #define _GNU_SOURCE + #endif + #if !defined(_POSIX_C_SOURCE) || ((_POSIX_C_SOURCE - 0) < 199309L) + #undef _POSIX_C_SOURCE + #define _POSIX_C_SOURCE 199309L + #endif + #if !defined(_XOPEN_SOURCE) || ((_XOPEN_SOURCE - 0) < 500) + #undef _XOPEN_SOURCE + #define _XOPEN_SOURCE 500 + #endif + #define _XPG6 +#endif + +/* Generic includes */ +#include + +/* Platform specific includes */ +#if defined(_TTHREAD_POSIX_) + #include +#elif defined(_TTHREAD_WIN32_) + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #define __UNDEF_LEAN_AND_MEAN + #endif + #include + #ifdef __UNDEF_LEAN_AND_MEAN + #undef WIN32_LEAN_AND_MEAN + #undef __UNDEF_LEAN_AND_MEAN + #endif +#endif + +/* Compiler-specific information */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define TTHREAD_NORETURN _Noreturn +#elif defined(__GNUC__) + #define TTHREAD_NORETURN __attribute__((__noreturn__)) +#else + #define TTHREAD_NORETURN +#endif + +/* If TIME_UTC is missing, provide it and provide a wrapper for + timespec_get. */ +#ifndef TIME_UTC +#define TIME_UTC 1 +#define _TTHREAD_EMULATE_TIMESPEC_GET_ + +#if defined(_TTHREAD_WIN32_) +struct _tthread_timespec { + time_t tv_sec; + long tv_nsec; +}; +#define timespec _tthread_timespec +#endif + +int _tthread_timespec_get(struct timespec *ts, int base); +#define timespec_get _tthread_timespec_get +#endif + +/** TinyCThread version (major number). */ +#define TINYCTHREAD_VERSION_MAJOR 1 +/** TinyCThread version (minor number). */ +#define TINYCTHREAD_VERSION_MINOR 2 +/** TinyCThread version (full version). */ +#define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR) + +/** +* @def _Thread_local +* Thread local storage keyword. +* A variable that is declared with the @c _Thread_local keyword makes the +* value of the variable local to each thread (known as thread-local storage, +* or TLS). Example usage: +* @code +* // This variable is local to each thread. +* _Thread_local int variable; +* @endcode +* @note The @c _Thread_local keyword is a macro that maps to the corresponding +* compiler directive (e.g. @c __declspec(thread)). +* @note This directive is currently not supported on Mac OS X (it will give +* a compiler error), since compile-time TLS is not supported in the Mac OS X +* executable format. Also, some older versions of MinGW (before GCC 4.x) do +* not support this directive, nor does the Tiny C Compiler. +* @hideinitializer +*/ + +#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local) + #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) + #define _Thread_local __thread + #else + #define _Thread_local __declspec(thread) + #endif +#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && (((__GNUC__ << 8) | __GNUC_MINOR__) < ((4 << 8) | 9)) + #define _Thread_local __thread +#endif + +/* Macros */ +#if defined(_TTHREAD_WIN32_) +#define TSS_DTOR_ITERATIONS (4) +#else +#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS +#endif + +/* Function return values */ +#define thrd_error 0 /**< The requested operation failed */ +#define thrd_success 1 /**< The requested operation succeeded */ +#define thrd_timedout 2 /**< The time specified in the call was reached without acquiring the requested resource */ +#define thrd_busy 3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */ +#define thrd_nomem 4 /**< The requested operation failed because it was unable to allocate memory */ + +/* Mutex types */ +#define mtx_plain 0 +#define mtx_timed 1 +#define mtx_recursive 2 + +/* Mutex */ +#if defined(_TTHREAD_WIN32_) +typedef struct { + union { + CRITICAL_SECTION cs; /* Critical section handle (used for non-timed mutexes) */ + HANDLE mut; /* Mutex handle (used for timed mutex) */ + } mHandle; /* Mutex handle */ + int mAlreadyLocked; /* TRUE if the mutex is already locked */ + int mRecursive; /* TRUE if the mutex is recursive */ + int mTimed; /* TRUE if the mutex is timed */ +} mtx_t; +#else +typedef pthread_mutex_t mtx_t; +#endif + +/** Create a mutex object. +* @param mtx A mutex object. +* @param type Bit-mask that must have one of the following six values: +* @li @c mtx_plain for a simple non-recursive mutex +* @li @c mtx_timed for a non-recursive mutex that supports timeout +* @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive) +* @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive) +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_init(mtx_t *mtx, int type); + +/** Release any resources used by the given mutex. +* @param mtx A mutex object. +*/ +void mtx_destroy(mtx_t *mtx); + +/** Lock the given mutex. +* Blocks until the given mutex can be locked. If the mutex is non-recursive, and +* the calling thread already has a lock on the mutex, this call will block +* forever. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_lock(mtx_t *mtx); + +/** Lock the given mutex, or block until a specific point in time. +* Blocks until either the given mutex can be locked, or the specified TIME_UTC +* based time. +* @param mtx A mutex object. +* @param ts A UTC based calendar time +* @return @ref The mtx_timedlock function returns thrd_success on success, or +* thrd_timedout if the time specified was reached without acquiring the +* requested resource, or thrd_error if the request could not be honored. +*/ +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts); + +/** Try to lock the given mutex. +* The specified mutex shall support either test and return or timeout. If the +* mutex is already locked, the function returns without blocking. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_busy if the resource +* requested is already in use, or @ref thrd_error if the request could not be +* honored. +*/ +int mtx_trylock(mtx_t *mtx); + +/** Unlock the given mutex. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int mtx_unlock(mtx_t *mtx); + +/* Condition variable */ +#if defined(_TTHREAD_WIN32_) +typedef struct { + HANDLE mEvents[2]; /* Signal and broadcast event HANDLEs. */ + unsigned int mWaitersCount; /* Count of the number of waiters. */ + CRITICAL_SECTION mWaitersCountLock; /* Serialize access to mWaitersCount. */ +} cnd_t; +#else +typedef pthread_cond_t cnd_t; +#endif + +/** Create a condition variable object. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_init(cnd_t *cond); + +/** Release any resources used by the given condition variable. +* @param cond A condition variable object. +*/ +void cnd_destroy(cnd_t *cond); + +/** Signal a condition variable. +* Unblocks one of the threads that are blocked on the given condition variable +* at the time of the call. If no threads are blocked on the condition variable +* at the time of the call, the function does nothing and return success. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_signal(cnd_t *cond); + +/** Broadcast a condition variable. +* Unblocks all of the threads that are blocked on the given condition variable +* at the time of the call. If no threads are blocked on the condition variable +* at the time of the call, the function does nothing and return success. +* @param cond A condition variable object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_broadcast(cnd_t *cond); + +/** Wait for a condition variable to become signaled. +* The function atomically unlocks the given mutex and endeavors to block until +* the given condition variable is signaled by a call to cnd_signal or to +* cnd_broadcast. When the calling thread becomes unblocked it locks the mutex +* before it returns. +* @param cond A condition variable object. +* @param mtx A mutex object. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int cnd_wait(cnd_t *cond, mtx_t *mtx); + +/** Wait for a condition variable to become signaled. +* The function atomically unlocks the given mutex and endeavors to block until +* the given condition variable is signaled by a call to cnd_signal or to +* cnd_broadcast, or until after the specified time. When the calling thread +* becomes unblocked it locks the mutex before it returns. +* @param cond A condition variable object. +* @param mtx A mutex object. +* @param xt A point in time at which the request will time out (absolute time). +* @return @ref thrd_success upon success, or @ref thrd_timeout if the time +* specified in the call was reached without acquiring the requested resource, or +* @ref thrd_error if the request could not be honored. +*/ +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts); + +/* Thread */ +#if defined(_TTHREAD_WIN32_) +typedef HANDLE thrd_t; +#else +typedef pthread_t thrd_t; +#endif + +/** Thread start function. +* Any thread that is started with the @ref thrd_create() function must be +* started through a function of this type. +* @param arg The thread argument (the @c arg argument of the corresponding +* @ref thrd_create() call). +* @return The thread return value, which can be obtained by another thread +* by using the @ref thrd_join() function. +*/ +typedef int (*thrd_start_t)(void *arg); + +/** Create a new thread. +* @param thr Identifier of the newly created thread. +* @param func A function pointer to the function that will be executed in +* the new thread. +* @param arg An argument to the thread function. +* @return @ref thrd_success on success, or @ref thrd_nomem if no memory could +* be allocated for the thread requested, or @ref thrd_error if the request +* could not be honored. +* @note A thread’s identifier may be reused for a different thread once the +* original thread has exited and either been detached or joined to another +* thread. +*/ +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg); + +/** Identify the calling thread. +* @return The identifier of the calling thread. +*/ +thrd_t thrd_current(void); + +/** Dispose of any resources allocated to the thread when that thread exits. + * @return thrd_success, or thrd_error on error +*/ +int thrd_detach(thrd_t thr); + +/** Compare two thread identifiers. +* The function determines if two thread identifiers refer to the same thread. +* @return Zero if the two thread identifiers refer to different threads. +* Otherwise a nonzero value is returned. +*/ +int thrd_equal(thrd_t thr0, thrd_t thr1); + +/** Terminate execution of the calling thread. +* @param res Result code of the calling thread. +*/ +TTHREAD_NORETURN void thrd_exit(int res); + +/** Wait for a thread to terminate. +* The function joins the given thread with the current thread by blocking +* until the other thread has terminated. +* @param thr The thread to join with. +* @param res If this pointer is not NULL, the function will store the result +* code of the given thread in the integer pointed to by @c res. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int thrd_join(thrd_t thr, int *res); + +/** Put the calling thread to sleep. +* Suspend execution of the calling thread. +* @param duration Interval to sleep for +* @param remaining If non-NULL, this parameter will hold the remaining +* time until time_point upon return. This will +* typically be zero, but if the thread was woken up +* by a signal that is not ignored before duration was +* reached @c remaining will hold a positive time. +* @return 0 (zero) on successful sleep, -1 if an interrupt occurred, +* or a negative value if the operation fails. +*/ +int thrd_sleep(const struct timespec *duration, struct timespec *remaining); + +/** Yield execution to another thread. +* Permit other threads to run, even if the current thread would ordinarily +* continue to run. +*/ +void thrd_yield(void); + +/* Thread local storage */ +#if defined(_TTHREAD_WIN32_) +typedef DWORD tss_t; +#else +typedef pthread_key_t tss_t; +#endif + +/** Destructor function for a thread-specific storage. +* @param val The value of the destructed thread-specific storage. +*/ +typedef void (*tss_dtor_t)(void *val); + +/** Create a thread-specific storage. +* @param key The unique key identifier that will be set if the function is +* successful. +* @param dtor Destructor function. This can be NULL. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +* @note On Windows, the @c dtor will definitely be called when +* appropriate for threads created with @ref thrd_create. It will be +* called for other threads in most cases, the possible exception being +* for DLLs loaded with LoadLibraryEx. In order to be certain, you +* should use @ref thrd_create whenever possible. +*/ +int tss_create(tss_t *key, tss_dtor_t dtor); + +/** Delete a thread-specific storage. +* The function releases any resources used by the given thread-specific +* storage. +* @param key The key that shall be deleted. +*/ +void tss_delete(tss_t key); + +/** Get the value for a thread-specific storage. +* @param key The thread-specific storage identifier. +* @return The value for the current thread held in the given thread-specific +* storage. +*/ +void *tss_get(tss_t key); + +/** Set the value for a thread-specific storage. +* @param key The thread-specific storage identifier. +* @param val The value of the thread-specific storage to set for the current +* thread. +* @return @ref thrd_success on success, or @ref thrd_error if the request could +* not be honored. +*/ +int tss_set(tss_t key, void *val); + +#if defined(_TTHREAD_WIN32_) + typedef struct { + LONG volatile status; + CRITICAL_SECTION lock; + } once_flag; + #define ONCE_FLAG_INIT {0,} +#else + #ifndef once_flag + #define once_flag pthread_once_t + #endif + #ifndef ONCE_FLAG_INIT + #define ONCE_FLAG_INIT PTHREAD_ONCE_INIT + #endif +#endif + +/** Invoke a callback exactly once + * @param flag Flag used to ensure the callback is invoked exactly + * once. + * @param func Callback to invoke. + */ +#if defined(_TTHREAD_WIN32_) + void call_once(once_flag *flag, void (*func)(void)); +#else + #ifndef call_once + #define call_once(flag,func) pthread_once(flag,func) + #endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _TINYTHREAD_H_ */ diff --git a/third_party/flserial/src/native_libs/src/LICENSE_glob b/third_party/flserial/src/native_libs/src/LICENSE_glob new file mode 100644 index 00000000..8c49b6b4 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/LICENSE_glob @@ -0,0 +1,34 @@ +/* + * Natanael Arndt, 2011: removed collate.h dependencies + * (my changes are trivial) + * + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ \ No newline at end of file diff --git a/third_party/flserial/src/native_libs/src/LICENSE_ringbuffer b/third_party/flserial/src/native_libs/src/LICENSE_ringbuffer new file mode 100644 index 00000000..4e5491e4 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/LICENSE_ringbuffer @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Anders Kalør + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/third_party/flserial/src/native_libs/src/LICENSE_serial b/third_party/flserial/src/native_libs/src/LICENSE_serial new file mode 100644 index 00000000..bd087f8d --- /dev/null +++ b/third_party/flserial/src/native_libs/src/LICENSE_serial @@ -0,0 +1,7 @@ +Copyright (c) 2012 William Woodall, John Harrison + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/third_party/flserial/src/native_libs/src/LICENSE_tinycthread b/third_party/flserial/src/native_libs/src/LICENSE_tinycthread new file mode 100644 index 00000000..d24cfe88 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/LICENSE_tinycthread @@ -0,0 +1,25 @@ + +License +------- + +Copyright (c) 2012 Marcus Geelnard + 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. diff --git a/third_party/flserial/src/native_libs/src/cglob.c b/third_party/flserial/src/native_libs/src/cglob.c new file mode 100644 index 00000000..7903dbc4 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/cglob.c @@ -0,0 +1,908 @@ +/* + * Natanael Arndt, 2011: removed collate.h dependencies + * (my changes are trivial) + * + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD$"); + +/* + * glob(3) -- a superset of the one defined in POSIX 1003.2. + * + * The [!...] convention to negate a range is supported (SysV, Posix, ksh). + * + * Optional extra services, controlled by flags not defined by POSIX: + * + * GLOB_QUOTE: + * Escaping convention: \ inhibits any special meaning the following + * character might have (except \ at end of string is retained). + * GLOB_MAGCHAR: + * Set in gl_flags if pattern contained a globbing character. + * GLOB_NOMAGIC: + * Same as GLOB_NOCHECK, but it will only append pattern if it did + * not contain any magic characters. [Used in csh style globbing] + * GLOB_ALTDIRFUNC: + * Use alternately specified directory access functions. + * GLOB_TILDE: + * expand ~user/foo to the /home/dir/of/user/foo + * GLOB_BRACE: + * expand {1,2}{a,b} to 1a 1b 2a 2b + * gl_matchc: + * Number of matches in the current invocation of glob. + */ + +/* + * Some notes on multibyte character support: + * 1. Patterns with illegal byte sequences match nothing - even if + * GLOB_NOCHECK is specified. + * 2. Illegal byte sequences in filenames are handled by treating them as + * single-byte characters with a value of the first byte of the sequence + * cast to wchar_t. + * 3. State-dependent encodings are not currently supported. + */ + +#include +#include + +#include +#include +#include +#include "cglob.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define DOLLAR '$' +#define DOT '.' +#define EOS '\0' +#define LBRACKET '[' +#define NOT '!' +#define QUESTION '?' +#define QUOTE '\\' +#define RANGE '-' +#define RBRACKET ']' +#define SEP '/' +#define STAR '*' +#define TILDE '~' +#define UNDERSCORE '_' +#define LBRACE '{' +#define RBRACE '}' +#define SLASH '/' +#define COMMA ',' + +#ifndef DEBUG + +#define M_QUOTE 0x8000000000ULL +#define M_PROTECT 0x4000000000ULL +#define M_MASK 0xffffffffffULL +#define M_CHAR 0x00ffffffffULL + +typedef uint_fast64_t Char; + +#else + +#define M_QUOTE 0x80 +#define M_PROTECT 0x40 +#define M_MASK 0xff +#define M_CHAR 0x7f + +typedef char Char; + +#endif + + +#define CHAR(c) ((Char)((c)&M_CHAR)) +#define META(c) ((Char)((c)|M_QUOTE)) +#define M_ALL META('*') +#define M_END META(']') +#define M_NOT META('!') +#define M_ONE META('?') +#define M_RNG META('-') +#define M_SET META('[') +#define ismeta(c) (((c)&M_QUOTE) != 0) + + +static int compare(const void *, const void *); +static int g_Ctoc(const Char *, char *, size_t); +static int g_lstat(Char *, struct stat *, cglob_t *); +static DIR *g_opendir(Char *, cglob_t *); +static const Char *g_strchr(const Char *, wchar_t); +#ifdef notdef +static Char *g_strcat(Char *, const Char *); +#endif +static int g_stat(Char *, struct stat *, cglob_t *); +static int glob0(const Char *, cglob_t *, size_t *); +static int glob1(Char *, cglob_t *, size_t *); +static int glob2(Char *, Char *, Char *, Char *, cglob_t *, size_t *); +static int glob3(Char *, Char *, Char *, Char *, Char *, cglob_t *, size_t *); +static int globextend(const Char *, cglob_t *, size_t *); +static const Char * + globtilde(const Char *, Char *, size_t, cglob_t *); +static int globexp1(const Char *, cglob_t *, size_t *); +static int globexp2(const Char *, const Char *, cglob_t *, int *, size_t *); +static int match(Char *, Char *, Char *); +#ifdef DEBUG +static void qprintf(const char *, Char *); +#endif + +int +cglob(const char *pattern, int flags, int (*errfunc)(const char *, int), cglob_t *pglob) +{ + const char *patnext; + size_t limit; + Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot; + mbstate_t mbs; + wchar_t wc; + size_t clen; + + patnext = pattern; + if (!(flags & GLOB_APPEND)) { + pglob->gl_pathc = 0; + pglob->gl_pathv = NULL; + if (!(flags & GLOB_DOOFFS)) + pglob->gl_offs = 0; + } + + if (flags & GLOB_LIMIT) { + limit = pglob->gl_matchc; + if (limit == 0) + limit = ARG_MAX; + } else + limit = 0; + + pglob->gl_flags = flags & ~GLOB_MAGCHAR; + pglob->gl_errfunc = errfunc; + pglob->gl_matchc = 0; + + bufnext = patbuf; + bufend = bufnext + MAXPATHLEN - 1; + if (flags & GLOB_NOESCAPE) { + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc; + patnext += clen; + } + } else { + /* Protect the quoted characters. */ + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + if (*patnext == QUOTE) { + if (*++patnext == EOS) { + *bufnext++ = QUOTE | M_PROTECT; + continue; + } + prot = M_PROTECT; + } else + prot = 0; + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc | prot; + patnext += clen; + } + } + *bufnext = EOS; + + if (flags & GLOB_BRACE) + return globexp1(patbuf, pglob, &limit); + else + return glob0(patbuf, pglob, &limit); +} + +/* + * Expand recursively a glob {} pattern. When there is no more expansion + * invoke the standard globbing routine to glob the rest of the magic + * characters + */ +static int +globexp1(const Char *pattern, cglob_t *pglob, size_t *limit) +{ + const Char* ptr = pattern; + int rv; + + /* Protect a single {}, for find(1), like csh */ + if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS) + return glob0(pattern, pglob, limit); + + while ((ptr = g_strchr(ptr, LBRACE)) != NULL) + if (!globexp2(ptr, pattern, pglob, &rv, limit)) + return rv; + + return glob0(pattern, pglob, limit); +} + + +/* + * Recursive brace globbing helper. Tries to expand a single brace. + * If it succeeds then it invokes globexp1 with the new pattern. + * If it fails then it tries to glob the rest of the pattern and returns. + */ +static int +globexp2(const Char *ptr, const Char *pattern, cglob_t *pglob, int *rv, size_t *limit) +{ + int i; + Char *lm, *ls; + const Char *pe, *pm, *pm1, *pl; + Char patbuf[MAXPATHLEN]; + + /* copy part up to the brace */ + for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++) + continue; + *lm = EOS; + ls = lm; + + /* Find the balanced brace */ + for (i = 0, pe = ++ptr; *pe; pe++) + if (*pe == LBRACKET) { + /* Ignore everything between [] */ + for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++) + continue; + if (*pe == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pe = pm; + } + } + else if (*pe == LBRACE) + i++; + else if (*pe == RBRACE) { + if (i == 0) + break; + i--; + } + + /* Non matching braces; just glob the pattern */ + if (i != 0 || *pe == EOS) { + *rv = glob0(patbuf, pglob, limit); + return 0; + } + + for (i = 0, pl = pm = ptr; pm <= pe; pm++) + switch (*pm) { + case LBRACKET: + /* Ignore everything between [] */ + for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++) + continue; + if (*pm == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pm = pm1; + } + break; + + case LBRACE: + i++; + break; + + case RBRACE: + if (i) { + i--; + break; + } + /* FALLTHROUGH */ + case COMMA: + if (i && *pm == COMMA) + break; + else { + /* Append the current string */ + for (lm = ls; (pl < pm); *lm++ = *pl++) + continue; + /* + * Append the rest of the pattern after the + * closing brace + */ + for (pl = pe + 1; (*lm++ = *pl++) != EOS;) + continue; + + /* Expand the current pattern */ +#ifdef DEBUG + qprintf("globexp2:", patbuf); +#endif + *rv = globexp1(patbuf, pglob, limit); + + /* move after the comma, to the next string */ + pl = pm + 1; + } + break; + + default: + break; + } + *rv = 0; + return 0; +} + + + +/* + * expand tilde from the passwd file. + */ +static const Char * +globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, cglob_t *pglob) +{ + struct passwd *pwd; + char *h; + const Char *p; + Char *b, *eb; + + if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE)) + return pattern; + + /* + * Copy up to the end of the string or / + */ + eb = &patbuf[patbuf_len - 1]; + for (p = pattern + 1, h = (char *) patbuf; + h < (char *)eb && *p && *p != SLASH; *h++ = *p++) + continue; + + *h = EOS; + + if (((char *) patbuf)[0] == EOS) { + /* + * handle a plain ~ or ~/ by expanding $HOME first (iff + * we're not running setuid or setgid) and then trying + * the password file + */ + /*if (issetugid() != 0 || + (h = getenv("HOME")) == NULL) { + if (((h = getlogin()) != NULL && + (pwd = getpwnam(h)) != NULL) || + (pwd = getpwuid(getuid())) != NULL) + h = pwd->pw_dir; + else + return pattern; + }*/ + } + else { + /* + * Expand a ~user + */ + if ((pwd = getpwnam((char*) patbuf)) == NULL) + return pattern; + else + h = pwd->pw_dir; + } + + /* Copy the home directory */ + for (b = patbuf; b < eb && *h; *b++ = *h++) + continue; + + /* Append the rest of the pattern */ + while (b < eb && (*b++ = *p++) != EOS) + continue; + *b = EOS; + + return patbuf; +} + + +/* + * The main glob() routine: compiles the pattern (optionally processing + * quotes), calls glob1() to do the real pattern matching, and finally + * sorts the list (unless unsorted operation is requested). Returns 0 + * if things went well, nonzero if errors occurred. + */ +static int +glob0(const Char *pattern, cglob_t *pglob, size_t *limit) +{ + const Char *qpatnext; + int err; + size_t oldpathc; + Char *bufnext, c, patbuf[MAXPATHLEN]; + + qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob); + oldpathc = pglob->gl_pathc; + bufnext = patbuf; + + /* We don't need to check for buffer overflow any more. */ + while ((c = *qpatnext++) != EOS) { + switch (c) { + case LBRACKET: + c = *qpatnext; + if (c == NOT) + ++qpatnext; + if (*qpatnext == EOS || + g_strchr(qpatnext+1, RBRACKET) == NULL) { + *bufnext++ = LBRACKET; + if (c == NOT) + --qpatnext; + break; + } + *bufnext++ = M_SET; + if (c == NOT) + *bufnext++ = M_NOT; + c = *qpatnext++; + do { + *bufnext++ = CHAR(c); + if (*qpatnext == RANGE && + (c = qpatnext[1]) != RBRACKET) { + *bufnext++ = M_RNG; + *bufnext++ = CHAR(c); + qpatnext += 2; + } + } while ((c = *qpatnext++) != RBRACKET); + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_END; + break; + case QUESTION: + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_ONE; + break; + case STAR: + pglob->gl_flags |= GLOB_MAGCHAR; + /* collapse adjacent stars to one, + * to avoid exponential behavior + */ + if (bufnext == patbuf || bufnext[-1] != M_ALL) + *bufnext++ = M_ALL; + break; + default: + *bufnext++ = CHAR(c); + break; + } + } + *bufnext = EOS; +#ifdef DEBUG + qprintf("glob0:", patbuf); +#endif + + if ((err = glob1(patbuf, pglob, limit)) != 0) + return(err); + + /* + * If there was no match we are going to append the pattern + * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified + * and the pattern did not contain any magic characters + * GLOB_NOMAGIC is there just for compatibility with csh. + */ + if (pglob->gl_pathc == oldpathc) { + if (((pglob->gl_flags & GLOB_NOCHECK) || + ((pglob->gl_flags & GLOB_NOMAGIC) && + !(pglob->gl_flags & GLOB_MAGCHAR)))) + return(globextend(pattern, pglob, limit)); + else + return(GLOB_NOMATCH); + } + if (!(pglob->gl_flags & GLOB_NOSORT)) + qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc, + pglob->gl_pathc - oldpathc, sizeof(char *), compare); + return(0); +} + +static int +compare(const void *p, const void *q) +{ + return(strcmp(*(char **)p, *(char **)q)); +} + +static int +glob1(Char *pattern, cglob_t *pglob, size_t *limit) +{ + Char pathbuf[MAXPATHLEN]; + + /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */ + if (*pattern == EOS) + return(0); + return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1, + pattern, pglob, limit)); +} + +/* + * The functions glob2 and glob3 are mutually recursive; there is one level + * of recursion for each segment in the pattern that contains one or more + * meta characters. + */ +static int +glob2(Char *pathbuf, Char *pathend, Char *pathend_last, Char *pattern, + cglob_t *pglob, size_t *limit) +{ + struct stat sb; + Char *p, *q; + int anymeta; + + /* + * Loop over pattern segments until end of pattern or until + * segment with meta character found. + */ + for (anymeta = 0;;) { + if (*pattern == EOS) { /* End of pattern? */ + *pathend = EOS; + if (g_lstat(pathbuf, &sb, pglob)) + return(0); + + if (((pglob->gl_flags & GLOB_MARK) && + pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) + || (S_ISLNK(sb.st_mode) && + (g_stat(pathbuf, &sb, pglob) == 0) && + S_ISDIR(sb.st_mode)))) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = SEP; + *pathend = EOS; + } + ++pglob->gl_matchc; + return(globextend(pathbuf, pglob, limit)); + } + + /* Find end of next segment, copy tentatively to pathend. */ + q = pathend; + p = pattern; + while (*p != EOS && *p != SEP) { + if (ismeta(*p)) + anymeta = 1; + if (q + 1 > pathend_last) + return (GLOB_ABORTED); + *q++ = *p++; + } + + if (!anymeta) { /* No expansion, do next segment. */ + pathend = q; + pattern = p; + while (*pattern == SEP) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = *pattern++; + } + } else /* Need expansion, recurse. */ + return(glob3(pathbuf, pathend, pathend_last, pattern, p, + pglob, limit)); + } + /* NOTREACHED */ +} + +static int +glob3(Char *pathbuf, Char *pathend, Char *pathend_last, + Char *pattern, Char *restpattern, + cglob_t *pglob, size_t *limit) +{ + struct dirent *dp; + DIR *dirp; + int err; + char buf[MAXPATHLEN]; + + /* + * The readdirfunc declaration can't be prototyped, because it is + * assigned, below, to two functions which are prototyped in glob.h + * and dirent.h as taking pointers to differently typed opaque + * structures. + */ + struct dirent *(*readdirfunc)(); + + if (pathend > pathend_last) + return (GLOB_ABORTED); + *pathend = EOS; + errno = 0; + + if ((dirp = g_opendir(pathbuf, pglob)) == NULL) { + /* TODO: don't call for ENOENT or ENOTDIR? */ + if (pglob->gl_errfunc) { + if (g_Ctoc(pathbuf, buf, sizeof(buf))) + return (GLOB_ABORTED); + if (pglob->gl_errfunc(buf, errno) || + pglob->gl_flags & GLOB_ERR) + return (GLOB_ABORTED); + } + return(0); + } + + err = 0; + + /* Search directory for matching names. */ + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + readdirfunc = pglob->gl_readdir; + else + readdirfunc = readdir; + while ((dp = (*readdirfunc)(dirp))) { + char *sc; + Char *dc; + wchar_t wc; + size_t clen; + mbstate_t mbs; + + /* Initial DOT must be matched literally. */ + if (dp->d_name[0] == DOT && *pattern != DOT) + continue; + memset(&mbs, 0, sizeof(mbs)); + dc = pathend; + sc = dp->d_name; + while (dc < pathend_last) { + clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) { + wc = *sc; + clen = 1; + memset(&mbs, 0, sizeof(mbs)); + } + if ((*dc++ = wc) == EOS) + break; + sc += clen; + } + if (!match(pathend, pattern, restpattern)) { + *pathend = EOS; + continue; + } + err = glob2(pathbuf, --dc, pathend_last, restpattern, + pglob, limit); + if (err) + break; + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + (*pglob->gl_closedir)(dirp); + else + closedir(dirp); + return(err); +} + + +/* + * Extend the gl_pathv member of a glob_t structure to accomodate a new item, + * add the new item, and update gl_pathc. + * + * This assumes the BSD realloc, which only copies the block when its size + * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic + * behavior. + * + * Return 0 if new item added, error code if memory couldn't be allocated. + * + * Invariant of the glob_t structure: + * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and + * gl_pathv points to (gl_offs + gl_pathc + 1) items. + */ +static int +globextend(const Char *path, cglob_t *pglob, size_t *limit) +{ + char **pathv; + size_t i, newsize, len; + char *copy; + const Char *p; + + if (*limit && pglob->gl_pathc > *limit) { + errno = 0; + return (GLOB_NOSPACE); + } + + newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs); + pathv = pglob->gl_pathv ? + realloc((char *)pglob->gl_pathv, newsize) : + malloc(newsize); + if (pathv == NULL) { + if (pglob->gl_pathv) { + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } + return(GLOB_NOSPACE); + } + + if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) { + /* first time around -- clear initial gl_offs items */ + pathv += pglob->gl_offs; + for (i = pglob->gl_offs + 1; --i > 0; ) + *--pathv = NULL; + } + pglob->gl_pathv = pathv; + + for (p = path; *p++;) + continue; + len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */ + if ((copy = malloc(len)) != NULL) { + if (g_Ctoc(path, copy, len)) { + free(copy); + return (GLOB_NOSPACE); + } + pathv[pglob->gl_offs + pglob->gl_pathc++] = copy; + } + pathv[pglob->gl_offs + pglob->gl_pathc] = NULL; + return(copy == NULL ? GLOB_NOSPACE : 0); +} + +/* + * pattern matching function for filenames. Each occurrence of the * + * pattern causes a recursion level. + */ +static int +match(Char *name, Char *pat, Char *patend) +{ + int ok, negate_range; + Char c, k; + + while (pat < patend) { + c = *pat++; + switch (c & M_MASK) { + case M_ALL: + if (pat == patend) + return(1); + do + if (match(name, pat, patend)) + return(1); + while (*name++ != EOS); + return(0); + case M_ONE: + if (*name++ == EOS) + return(0); + break; + case M_SET: + ok = 0; + if ((k = *name++) == EOS) + return(0); + if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS) + ++pat; + while (((c = *pat++) & M_MASK) != M_END) + if ((*pat & M_MASK) == M_RNG) { + if (CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1])) ok = 1; + pat += 2; + } else if (c == k) + ok = 1; + if (ok == negate_range) + return(0); + break; + default: + if (*name++ != c) + return(0); + break; + } + } + return(*name == EOS); +} + +/* Free allocated data belonging to a glob_t structure. */ +void +cglobfree(cglob_t *pglob) +{ + size_t i; + char **pp; + + if (pglob->gl_pathv != NULL) { + pp = pglob->gl_pathv + pglob->gl_offs; + for (i = pglob->gl_pathc; i--; ++pp) + if (*pp) + free(*pp); + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } +} + +static DIR * +g_opendir(Char *str, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (!*str) + strcpy(buf, "."); + else { + if (g_Ctoc(str, buf, sizeof(buf))) + return (NULL); + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_opendir)(buf)); + + return(opendir(buf)); +} + +static int +g_lstat(Char *fn, struct stat *sb, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_lstat)(buf, sb)); + return(lstat(buf, sb)); +} + +static int +g_stat(Char *fn, struct stat *sb, cglob_t *pglob) +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_stat)(buf, sb)); + return(stat(buf, sb)); +} + +static const Char * +g_strchr(const Char *str, wchar_t ch) +{ + + do { + if (*str == ch) + return (str); + } while (*str++); + return (NULL); +} + +static int +g_Ctoc(const Char *str, char *buf, size_t len) +{ + mbstate_t mbs; + size_t clen; + + memset(&mbs, 0, sizeof(mbs)); + while (len >= MB_CUR_MAX) { + clen = wcrtomb(buf, *str, &mbs); + if (clen == (size_t)-1) + return (1); + if (*str == L'\0') + return (0); + str++; + buf += clen; + len -= clen; + } + return (1); +} + +#ifdef DEBUG +static void +qprintf(const char *str, Char *s) +{ + Char *p; + + (void)printf("%s:\n", str); + for (p = s; *p; p++) + (void)printf("%c", CHAR(*p)); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", *p & M_PROTECT ? '"' : ' '); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", ismeta(*p) ? '_' : ' '); + (void)printf("\n"); +} +#endif diff --git a/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_linux.cpp b/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_linux.cpp new file mode 100644 index 00000000..5799d6ac --- /dev/null +++ b/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_linux.cpp @@ -0,0 +1,342 @@ +#if defined(__linux__) + +/* + * Copyright (c) 2014 Craig Lilley + * This software is made available under the terms of the MIT licence. + * A copy of the licence can be obtained from: + * http://opensource.org/licenses/MIT + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef ANDROID +#include "cglob.h" +#else +#include +#define cglob glob +#define cglobfree globfree +#define cglob_t glob_t +#endif +#include +#include +#include + +#include "serial/serial.h" + +using serial::PortInfo; +using std::istringstream; +using std::ifstream; +using std::getline; +using std::vector; +using std::string; +using std::cout; +using std::endl; + +static vector glob(const vector& patterns); +static string basename(const string& path); +static string dirname(const string& path); +static bool path_exists(const string& path); +static string realpath(const string& path); +static string usb_sysfs_friendly_name(const string& sys_usb_path); +static vector get_sysfs_info(const string& device_path); +static string read_line(const string& file); +static string usb_sysfs_hw_string(const string& sysfs_path); +static string format(const char* format, ...); + +vector +glob(const vector& patterns) +{ + vector paths_found; + + if(patterns.size() == 0) + return paths_found; + + cglob_t glob_results; + + int glob_retval = cglob(patterns[0].c_str(), 0, NULL, &glob_results); + + vector::const_iterator iter = patterns.begin(); + + while(++iter != patterns.end()) + { + glob_retval = cglob(iter->c_str(), GLOB_APPEND, NULL, &glob_results); + } + + for(int path_index = 0; path_index < glob_results.gl_pathc; path_index++) + { + paths_found.push_back(glob_results.gl_pathv[path_index]); + } + + cglobfree(&glob_results); + + return paths_found; +} + +string +basename(const string& path) +{ + size_t pos = path.rfind("/"); + + if(pos == std::string::npos) + return path; + + return string(path, pos+1, string::npos); +} + +string +dirname(const string& path) +{ + size_t pos = path.rfind("/"); + + if(pos == std::string::npos) + return path; + else if(pos == 0) + return "/"; + + return string(path, 0, pos); +} + +bool +path_exists(const string& path) +{ + struct stat sb; + + if( stat(path.c_str(), &sb ) == 0 ) + return true; + + return false; +} + +string +realpath(const string& path) +{ + char* real_path = realpath(path.c_str(), NULL); + + string result; + + if(real_path != NULL) + { + result = real_path; + + free(real_path); + } + + return result; +} + +string +usb_sysfs_friendly_name(const string& sys_usb_path) +{ + unsigned int device_number = 0; + + istringstream( read_line(sys_usb_path + "/devnum") ) >> device_number; + + string manufacturer = read_line( sys_usb_path + "/manufacturer" ); + + string product = read_line( sys_usb_path + "/product" ); + + string serial = read_line( sys_usb_path + "/serial" ); + + if( manufacturer.empty() && product.empty() && serial.empty() ) + return ""; + + return format("%s %s %s", manufacturer.c_str(), product.c_str(), serial.c_str() ); +} + +vector +get_sysfs_info(const string& device_path) +{ + string device_name = basename( device_path ); + + string friendly_name; + + string hardware_id; + + string sys_device_path = format( "/sys/class/tty/%s/device", device_name.c_str() ); + + if( device_name.compare(0,6,"ttyUSB") == 0 ) + { + sys_device_path = dirname( dirname( realpath( sys_device_path ) ) ); + + if( path_exists( sys_device_path ) ) + { + friendly_name = usb_sysfs_friendly_name( sys_device_path ); + + hardware_id = usb_sysfs_hw_string( sys_device_path ); + } + } + else if( device_name.compare(0,6,"ttyACM") == 0 ) + { + sys_device_path = dirname( realpath( sys_device_path ) ); + + if( path_exists( sys_device_path ) ) + { + friendly_name = usb_sysfs_friendly_name( sys_device_path ); + + hardware_id = usb_sysfs_hw_string( sys_device_path ); + } + } + else + { + // Try to read ID string of PCI device + + string sys_id_path = sys_device_path + "/id"; + + if( path_exists( sys_id_path ) ) + hardware_id = read_line( sys_id_path ); + } + + if( friendly_name.empty() ) + friendly_name = device_name; + + if( hardware_id.empty() ) + hardware_id = "n/a"; + + vector result; + result.push_back(friendly_name); + result.push_back(hardware_id); + + return result; +} + +string +read_line(const string& file) +{ + ifstream ifs(file.c_str(), ifstream::in); + + string line; + + if(ifs) + { + getline(ifs, line); + } + + return line; +} + +string +format(const char* format, ...) +{ + va_list ap; + + size_t buffer_size_bytes = 256; + + string result; + + char* buffer = (char*)malloc(buffer_size_bytes); + + if( buffer == NULL ) + return result; + + bool done = false; + + unsigned int loop_count = 0; + + while(!done) + { + va_start(ap, format); + + int return_value = vsnprintf(buffer, buffer_size_bytes, format, ap); + + if( return_value < 0 ) + { + done = true; + } + else if( return_value >= buffer_size_bytes ) + { + // Realloc and try again. + + buffer_size_bytes = return_value + 1; + + char* new_buffer_ptr = (char*)realloc(buffer, buffer_size_bytes); + + if( new_buffer_ptr == NULL ) + { + done = true; + } + else + { + buffer = new_buffer_ptr; + } + } + else + { + result = buffer; + done = true; + } + + va_end(ap); + + if( ++loop_count > 5 ) + done = true; + } + + free(buffer); + + return result; +} + +string +usb_sysfs_hw_string(const string& sysfs_path) +{ + string serial_number = read_line( sysfs_path + "/serial" ); + + if( serial_number.length() > 0 ) + { + serial_number = format( "SNR=%s", serial_number.c_str() ); + } + + string vid = read_line( sysfs_path + "/idVendor" ); + + string pid = read_line( sysfs_path + "/idProduct" ); + + return format("USB VID:PID=%s:%s %s", vid.c_str(), pid.c_str(), serial_number.c_str() ); +} + +vector +serial::list_ports() +{ + vector results; + + vector search_globs; + search_globs.push_back("/dev/ttyACM*"); + search_globs.push_back("/dev/ttyS*"); + search_globs.push_back("/dev/ttyUSB*"); + search_globs.push_back("/dev/tty.*"); + search_globs.push_back("/dev/cu.*"); + search_globs.push_back("/dev/rfcomm*"); + + vector devices_found = glob( search_globs ); + + vector::iterator iter = devices_found.begin(); + + while( iter != devices_found.end() ) + { + string device = *iter++; + + vector sysfs_info = get_sysfs_info( device ); + + string friendly_name = sysfs_info[0]; + + string hardware_id = sysfs_info[1]; + + PortInfo device_entry; + device_entry.port = device; + device_entry.description = friendly_name; + device_entry.hardware_id = hardware_id; + + results.push_back( device_entry ); + + } + + return results; +} + +#endif // defined(__linux__) diff --git a/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_osx.cpp b/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_osx.cpp new file mode 100644 index 00000000..8005c62b --- /dev/null +++ b/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_osx.cpp @@ -0,0 +1,286 @@ +#if defined(__APPLE__) + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "../../../include/serial/serial.h" + +using serial::PortInfo; +using std::string; +using std::vector; + +#define HARDWARE_ID_STRING_LENGTH 128 + +string cfstring_to_string( CFStringRef cfstring ); +string get_device_path( io_object_t& serial_port ); +string get_class_name( io_object_t& obj ); +io_registry_entry_t get_parent_iousb_device( io_object_t& serial_port ); +string get_string_property( io_object_t& device, const char* property ); +uint16_t get_int_property( io_object_t& device, const char* property ); +string rtrim(const string& str); + +string +cfstring_to_string( CFStringRef cfstring ) +{ + char cstring[MAXPATHLEN]; + string result; + + if( cfstring ) + { + Boolean success = CFStringGetCString( cfstring, + cstring, + sizeof(cstring), + kCFStringEncodingASCII ); + + if( success ) + result = cstring; + } + + return result; +} + +string +get_device_path( io_object_t& serial_port ) +{ + CFTypeRef callout_path; + string device_path; + + callout_path = IORegistryEntryCreateCFProperty( serial_port, + CFSTR(kIOCalloutDeviceKey), + kCFAllocatorDefault, + 0 ); + + if (callout_path) + { + if( CFGetTypeID(callout_path) == CFStringGetTypeID() ) + device_path = cfstring_to_string( static_cast(callout_path) ); + + CFRelease(callout_path); + } + + return device_path; +} + +string +get_class_name( io_object_t& obj ) +{ + string result; + io_name_t class_name; + kern_return_t kern_result; + + kern_result = IOObjectGetClass( obj, class_name ); + + if( kern_result == KERN_SUCCESS ) + result = class_name; + + return result; +} + +io_registry_entry_t +get_parent_iousb_device( io_object_t& serial_port ) +{ + io_object_t device = serial_port; + io_registry_entry_t parent = 0; + io_registry_entry_t result = 0; + kern_return_t kern_result = KERN_FAILURE; + string name = get_class_name(device); + + // Walk the IO Registry tree looking for this devices parent IOUSBDevice. + while( name != "IOUSBDevice" ) + { + kern_result = IORegistryEntryGetParentEntry( device, + kIOServicePlane, + &parent ); + + if(kern_result != KERN_SUCCESS) + { + result = 0; + break; + } + + device = parent; + + name = get_class_name(device); + } + + if(kern_result == KERN_SUCCESS) + result = device; + + return result; +} + +string +get_string_property( io_object_t& device, const char* property ) +{ + string property_name; + + if( device ) + { + CFStringRef property_as_cfstring = CFStringCreateWithCString ( + kCFAllocatorDefault, + property, + kCFStringEncodingASCII ); + + CFTypeRef name_as_cfstring = IORegistryEntryCreateCFProperty( + device, + property_as_cfstring, + kCFAllocatorDefault, + 0 ); + + if( name_as_cfstring ) + { + if( CFGetTypeID(name_as_cfstring) == CFStringGetTypeID() ) + property_name = cfstring_to_string( static_cast(name_as_cfstring) ); + + CFRelease(name_as_cfstring); + } + + if(property_as_cfstring) + CFRelease(property_as_cfstring); + } + + return property_name; +} + +uint16_t +get_int_property( io_object_t& device, const char* property ) +{ + uint16_t result = 0; + + if( device ) + { + CFStringRef property_as_cfstring = CFStringCreateWithCString ( + kCFAllocatorDefault, + property, + kCFStringEncodingASCII ); + + CFTypeRef number = IORegistryEntryCreateCFProperty( device, + property_as_cfstring, + kCFAllocatorDefault, + 0 ); + + if(property_as_cfstring) + CFRelease(property_as_cfstring); + + if( number ) + { + if( CFGetTypeID(number) == CFNumberGetTypeID() ) + { + bool success = CFNumberGetValue( static_cast(number), + kCFNumberSInt16Type, + &result ); + + if( !success ) + result = 0; + } + + CFRelease(number); + } + + } + + return result; +} + +string rtrim(const string& str) +{ + string result = str; + + string whitespace = " \t\f\v\n\r"; + + std::size_t found = result.find_last_not_of(whitespace); + + if (found != std::string::npos) + result.erase(found+1); + else + result.clear(); + + return result; +} + +vector +serial::list_ports(void) +{ + vector devices_found; + CFMutableDictionaryRef classes_to_match; + io_iterator_t serial_port_iterator; + io_object_t serial_port; + mach_port_t master_port; + kern_return_t kern_result; + + kern_result = IOMasterPort(MACH_PORT_NULL, &master_port); + + if(kern_result != KERN_SUCCESS) + return devices_found; + + classes_to_match = IOServiceMatching(kIOSerialBSDServiceValue); + + if (classes_to_match == NULL) + return devices_found; + + CFDictionarySetValue( classes_to_match, + CFSTR(kIOSerialBSDTypeKey), + CFSTR(kIOSerialBSDAllTypes) ); + + kern_result = IOServiceGetMatchingServices(master_port, classes_to_match, &serial_port_iterator); + + if (KERN_SUCCESS != kern_result) + return devices_found; + + while ( (serial_port = IOIteratorNext(serial_port_iterator)) ) + { + string device_path = get_device_path( serial_port ); + io_registry_entry_t parent = get_parent_iousb_device( serial_port ); + IOObjectRelease(serial_port); + + if( device_path.empty() ) + continue; + + PortInfo port_info; + port_info.port = device_path; + port_info.description = "n/a"; + port_info.hardware_id = "n/a"; + + string device_name = rtrim( get_string_property( parent, "USB Product Name" ) ); + string vendor_name = rtrim( get_string_property( parent, "USB Vendor Name") ); + string description = rtrim( vendor_name + " " + device_name ); + if( !description.empty() ) + port_info.description = description; + + string serial_number = rtrim(get_string_property( parent, "USB Serial Number" ) ); + uint16_t vendor_id = get_int_property( parent, "idVendor" ); + uint16_t product_id = get_int_property( parent, "idProduct" ); + + if( vendor_id && product_id ) + { + char cstring[HARDWARE_ID_STRING_LENGTH]; + + if(serial_number.empty()) + serial_number = "None"; + + int ret = snprintf( cstring, HARDWARE_ID_STRING_LENGTH, "USB VID:PID=%04x:%04x SNR=%s", + vendor_id, + product_id, + serial_number.c_str() ); + + if( (ret >= 0) && (ret < HARDWARE_ID_STRING_LENGTH) ) + port_info.hardware_id = cstring; + } + + devices_found.push_back(port_info); + } + + IOObjectRelease(serial_port_iterator); + return devices_found; +} + +#endif // defined(__APPLE__) diff --git a/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_win.cpp b/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_win.cpp new file mode 100644 index 00000000..7da40c44 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/impl/list_ports/list_ports_win.cpp @@ -0,0 +1,152 @@ +#if defined(_WIN32) + +/* + * Copyright (c) 2014 Craig Lilley + * This software is made available under the terms of the MIT licence. + * A copy of the licence can be obtained from: + * http://opensource.org/licenses/MIT + */ + +#include "serial/serial.h" +#include +#include +#include +#include +#include +#include + +using serial::PortInfo; +using std::vector; +using std::string; + +static const DWORD port_name_max_length = 256; +static const DWORD friendly_name_max_length = 256; +static const DWORD hardware_id_max_length = 256; + +// Convert a wide Unicode string to an UTF8 string +std::string utf8_encode(const std::wstring &wstr) +{ + int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); + std::string strTo( size_needed, 0 ); + WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); + return strTo; +} + +vector +serial::list_ports() +{ + vector devices_found; + + HDEVINFO device_info_set = SetupDiGetClassDevs( + (const GUID *) &GUID_DEVCLASS_PORTS, + NULL, + NULL, + DIGCF_PRESENT); + + unsigned int device_info_set_index = 0; + SP_DEVINFO_DATA device_info_data; + + device_info_data.cbSize = sizeof(SP_DEVINFO_DATA); + + while(SetupDiEnumDeviceInfo(device_info_set, device_info_set_index, &device_info_data)) + { + device_info_set_index++; + + // Get port name + + HKEY hkey = SetupDiOpenDevRegKey( + device_info_set, + &device_info_data, + DICS_FLAG_GLOBAL, + 0, + DIREG_DEV, + KEY_READ); + + TCHAR port_name[port_name_max_length]; + DWORD port_name_length = port_name_max_length; + + LONG return_code = RegQueryValueEx( + hkey, + _T("PortName"), + NULL, + NULL, + (LPBYTE)port_name, + &port_name_length); + + RegCloseKey(hkey); + + if(return_code != EXIT_SUCCESS) + continue; + + if(port_name_length > 0 && port_name_length <= port_name_max_length) + port_name[port_name_length-1] = '\0'; + else + port_name[0] = '\0'; + + // Ignore parallel ports + + if(_tcsstr(port_name, _T("LPT")) != NULL) + continue; + + // Get port friendly name + + TCHAR friendly_name[friendly_name_max_length]; + DWORD friendly_name_actual_length = 0; + + BOOL got_friendly_name = SetupDiGetDeviceRegistryProperty( + device_info_set, + &device_info_data, + SPDRP_FRIENDLYNAME, + NULL, + (PBYTE)friendly_name, + friendly_name_max_length, + &friendly_name_actual_length); + + if(got_friendly_name == TRUE && friendly_name_actual_length > 0) + friendly_name[friendly_name_actual_length-1] = '\0'; + else + friendly_name[0] = '\0'; + + // Get hardware ID + + TCHAR hardware_id[hardware_id_max_length]; + DWORD hardware_id_actual_length = 0; + + BOOL got_hardware_id = SetupDiGetDeviceRegistryProperty( + device_info_set, + &device_info_data, + SPDRP_HARDWAREID, + NULL, + (PBYTE)hardware_id, + hardware_id_max_length, + &hardware_id_actual_length); + + if(got_hardware_id == TRUE && hardware_id_actual_length > 0) + hardware_id[hardware_id_actual_length-1] = '\0'; + else + hardware_id[0] = '\0'; + + #ifdef UNICODE + std::string portName = utf8_encode(port_name); + std::string friendlyName = utf8_encode(friendly_name); + std::string hardwareId = utf8_encode(hardware_id); + #else + std::string portName = port_name; + std::string friendlyName = friendly_name; + std::string hardwareId = hardware_id; + #endif + + PortInfo port_entry; + port_entry.port = portName; + port_entry.description = friendlyName; + port_entry.hardware_id = hardwareId; + + devices_found.push_back(port_entry); + } + + SetupDiDestroyDeviceInfoList(device_info_set); + + return devices_found; +} + +#endif // #if defined(_WIN32) diff --git a/third_party/flserial/src/native_libs/src/impl/unix.cpp b/third_party/flserial/src/native_libs/src/impl/unix.cpp new file mode 100644 index 00000000..0ad59cf8 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/impl/unix.cpp @@ -0,0 +1,1138 @@ +/* Copyright 2012 William Woodall and John Harrison + * + * Additional Contributors: Christopher Baker @bakercp + */ + +#if !defined(_WIN32) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +# include +#endif + +#include +#include +#include +#ifdef __MACH__ +#include +#include +#include +#endif + +#include "../../include/serial/impl/unix.h" + +#ifndef TIOCINQ +#ifdef FIONREAD +#define TIOCINQ FIONREAD +#else +#define TIOCINQ 0x541B +#endif +#endif + +#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3) +#include +#endif + +using std::string; +using std::stringstream; +using std::invalid_argument; +using serial::MillisecondTimer; +using serial::Serial; +using serial::SerialException; +using serial::PortNotOpenedException; +using serial::IOException; + +// glibc 2.42 made cfsetispeed/cfsetospeed default to GLIBC_2.42 and turned +// the B* macros into plain baud numbers. A library built on that glibc will +// not load on Ubuntu 24.04 / Linux Mint 22 (glibc 2.39). Bind the old symbols +// and pass the legacy c_cflag values those symbols still expect. +#if defined(__linux__) && defined(__GLIBC__) +__asm__(".symver cfsetispeed, cfsetispeed@GLIBC_2.2.5"); +__asm__(".symver cfsetospeed, cfsetospeed@GLIBC_2.2.5"); + +static speed_t glibc_legacy_baud(speed_t baud) { +#if defined(B115200) && (B115200 == 115200) + switch (static_cast(baud)) { + case 50: return 0000001; + case 75: return 0000002; + case 110: return 0000003; + case 134: return 0000004; + case 150: return 0000005; + case 200: return 0000006; + case 300: return 0000007; + case 600: return 0000010; + case 1200: return 0000011; + case 1800: return 0000012; + case 2400: return 0000013; + case 4800: return 0000014; + case 9600: return 0000015; + case 19200: return 0000016; + case 38400: return 0000017; + case 57600: return 0010001; + case 115200: return 0010002; + case 230400: return 0010003; + case 460800: return 0010004; + case 500000: return 0010005; + case 576000: return 0010006; + case 921600: return 0010007; + case 1000000: return 0010010; + case 1152000: return 0010011; + case 1500000: return 0010012; + case 2000000: return 0010013; + case 2500000: return 0010014; + case 3000000: return 0010015; + case 3500000: return 0010016; + case 4000000: return 0010017; + default: return baud; + } +#else + return baud; +#endif +} +#else +static speed_t glibc_legacy_baud(speed_t baud) { return baud; } +#endif + + +MillisecondTimer::MillisecondTimer (const uint32_t millis) + : expiry(timespec_now()) +{ + int64_t tv_nsec = expiry.tv_nsec + (millis * 1e6); + if (tv_nsec >= 1e9) { + int64_t sec_diff = tv_nsec / static_cast (1e9); + expiry.tv_nsec = tv_nsec % static_cast(1e9); + expiry.tv_sec += sec_diff; + } else { + expiry.tv_nsec = tv_nsec; + } +} + +int64_t +MillisecondTimer::remaining () +{ + timespec now(timespec_now()); + int64_t millis = (expiry.tv_sec - now.tv_sec) * 1e3; + millis += (expiry.tv_nsec - now.tv_nsec) / 1e6; + return millis; +} + +timespec +MillisecondTimer::timespec_now () +{ + timespec time; +# ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + time.tv_sec = mts.tv_sec; + time.tv_nsec = mts.tv_nsec; +# else + clock_gettime(CLOCK_MONOTONIC, &time); +# endif + return time; +} + +timespec +timespec_from_ms (const uint32_t millis) +{ + timespec time; + time.tv_sec = millis / 1e3; + time.tv_nsec = (millis - (time.tv_sec * 1e3)) * 1e6; + return time; +} + +Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : port_ (port), fd_ (-1), is_open_ (false), xonxoff_ (false), rtscts_ (false), + baudrate_ (baudrate), parity_ (parity), + bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol) +{ + pthread_mutex_init(&this->read_mutex, NULL); + pthread_mutex_init(&this->write_mutex, NULL); + if (port_.empty () == false) + open (); +} + +Serial::SerialImpl::~SerialImpl () +{ + close(); + pthread_mutex_destroy(&this->read_mutex); + pthread_mutex_destroy(&this->write_mutex); +} + +void +Serial::SerialImpl::open () +{ + if (port_.empty ()) { + throw invalid_argument ("Empty port is invalid."); + } + if (is_open_ == true) { + throw SerialException ("Serial port already open."); + } + + fd_ = ::open (port_.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); + + int err = errno; + if (fd_ == -1) { + switch (err) { + case EINTR: + // Recurse because this is a recoverable error. + open (); + return; + case ENFILE: + case EMFILE: + THROW (IOException, "Too many file handles open."); + default: + char buff[32]; + sprintf(buff, "%08X", err); + THROW (IOException, buff); + } + } + + reconfigurePort(); + is_open_ = true; +} + +void +Serial::SerialImpl::reconfigurePort () +{ + if (fd_ == -1) { + // Can only operate on a valid file descriptor + THROW (IOException, "Invalid file descriptor, is the serial port open?"); + } + + struct termios options; // The options for the file descriptor + + if (tcgetattr(fd_, &options) == -1) { + THROW (IOException, "::tcgetattr"); + } + + // set up raw mode / no echo / binary + options.c_cflag |= (tcflag_t) (CLOCAL | CREAD); + options.c_lflag &= (tcflag_t) ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | + ISIG | IEXTEN); //|ECHOPRT + + options.c_oflag &= (tcflag_t) ~(OPOST); + options.c_iflag &= (tcflag_t) ~(INLCR | IGNCR | ICRNL | IGNBRK); +#ifdef IUCLC + options.c_iflag &= (tcflag_t) ~IUCLC; +#endif +#ifdef PARMRK + options.c_iflag &= (tcflag_t) ~PARMRK; +#endif + + // setup baud rate + bool custom_baud = false; + speed_t baud; + switch (baudrate_) { +#ifdef B0 + case 0: baud = B0; break; +#endif +#ifdef B50 + case 50: baud = B50; break; +#endif +#ifdef B75 + case 75: baud = B75; break; +#endif +#ifdef B110 + case 110: baud = B110; break; +#endif +#ifdef B134 + case 134: baud = B134; break; +#endif +#ifdef B150 + case 150: baud = B150; break; +#endif +#ifdef B200 + case 200: baud = B200; break; +#endif +#ifdef B300 + case 300: baud = B300; break; +#endif +#ifdef B600 + case 600: baud = B600; break; +#endif +#ifdef B1200 + case 1200: baud = B1200; break; +#endif +#ifdef B1800 + case 1800: baud = B1800; break; +#endif +#ifdef B2400 + case 2400: baud = B2400; break; +#endif +#ifdef B4800 + case 4800: baud = B4800; break; +#endif +#ifdef B7200 + case 7200: baud = B7200; break; +#endif +#ifdef B9600 + case 9600: baud = B9600; break; +#endif +#ifdef B14400 + case 14400: baud = B14400; break; +#endif +#ifdef B19200 + case 19200: baud = B19200; break; +#endif +#ifdef B28800 + case 28800: baud = B28800; break; +#endif +#ifdef B57600 + case 57600: baud = B57600; break; +#endif +#ifdef B76800 + case 76800: baud = B76800; break; +#endif +#ifdef B38400 + case 38400: baud = B38400; break; +#endif +#ifdef B115200 + case 115200: baud = B115200; break; +#endif +#ifdef B128000 + case 128000: baud = B128000; break; +#endif +#ifdef B153600 + case 153600: baud = B153600; break; +#endif +#ifdef B230400 + case 230400: baud = B230400; break; +#endif +#ifdef B256000 + case 256000: baud = B256000; break; +#endif +#ifdef B460800 + case 460800: baud = B460800; break; +#endif +#ifdef B500000 + case 500000: baud = B500000; break; +#endif +#ifdef B576000 + case 576000: baud = B576000; break; +#endif +#ifdef B921600 + case 921600: baud = B921600; break; +#endif +#ifdef B1000000 + case 1000000: baud = B1000000; break; +#endif +#ifdef B1152000 + case 1152000: baud = B1152000; break; +#endif +#ifdef B1500000 + case 1500000: baud = B1500000; break; +#endif +#ifdef B2000000 + case 2000000: baud = B2000000; break; +#endif +#ifdef B2500000 + case 2500000: baud = B2500000; break; +#endif +#ifdef B3000000 + case 3000000: baud = B3000000; break; +#endif +#ifdef B3500000 + case 3500000: baud = B3500000; break; +#endif +#ifdef B4000000 + case 4000000: baud = B4000000; break; +#endif + default: + custom_baud = true; + } + if (custom_baud == false) { +#ifdef _BSD_SOURCE + ::cfsetspeed(&options, baud); +#else + ::cfsetispeed(&options, glibc_legacy_baud(baud)); + ::cfsetospeed(&options, glibc_legacy_baud(baud)); +#endif + } + + // setup char len + options.c_cflag &= (tcflag_t) ~CSIZE; + if (bytesize_ == eightbits) + options.c_cflag |= CS8; + else if (bytesize_ == sevenbits) + options.c_cflag |= CS7; + else if (bytesize_ == sixbits) + options.c_cflag |= CS6; + else if (bytesize_ == fivebits) + options.c_cflag |= CS5; + else + throw invalid_argument ("invalid char len"); + // setup stopbits + if (stopbits_ == stopbits_one) + options.c_cflag &= (tcflag_t) ~(CSTOPB); + else if (stopbits_ == stopbits_one_point_five) + // ONE POINT FIVE same as TWO.. there is no POSIX support for 1.5 + options.c_cflag |= (CSTOPB); + else if (stopbits_ == stopbits_two) + options.c_cflag |= (CSTOPB); + else + throw invalid_argument ("invalid stop bit"); + // setup parity + options.c_iflag &= (tcflag_t) ~(INPCK | ISTRIP); + if (parity_ == parity_none) { + options.c_cflag &= (tcflag_t) ~(PARENB | PARODD); + } else if (parity_ == parity_even) { + options.c_cflag &= (tcflag_t) ~(PARODD); + options.c_cflag |= (PARENB); + } else if (parity_ == parity_odd) { + options.c_cflag |= (PARENB | PARODD); + } +#ifdef CMSPAR + else if (parity_ == parity_mark) { + options.c_cflag |= (PARENB | CMSPAR | PARODD); + } + else if (parity_ == parity_space) { + options.c_cflag |= (PARENB | CMSPAR); + options.c_cflag &= (tcflag_t) ~(PARODD); + } +#else + // CMSPAR is not defined on OSX. So do not support mark or space parity. + else if (parity_ == parity_mark || parity_ == parity_space) { + throw invalid_argument ("OS does not support mark or space parity"); + } +#endif // ifdef CMSPAR + else { + throw invalid_argument ("invalid parity"); + } + // setup flow control + if (flowcontrol_ == flowcontrol_none) { + xonxoff_ = false; + rtscts_ = false; + } + if (flowcontrol_ == flowcontrol_software) { + xonxoff_ = true; + rtscts_ = false; + } + if (flowcontrol_ == flowcontrol_hardware) { + xonxoff_ = false; + rtscts_ = true; + } + // xonxoff +#ifdef IXANY + if (xonxoff_) + options.c_iflag |= (IXON | IXOFF); //|IXANY) + else + options.c_iflag &= (tcflag_t) ~(IXON | IXOFF | IXANY); +#else + if (xonxoff_) + options.c_iflag |= (IXON | IXOFF); + else + options.c_iflag &= (tcflag_t) ~(IXON | IXOFF); +#endif + // rtscts +#ifdef CRTSCTS + if (rtscts_) + options.c_cflag |= (CRTSCTS); + else + options.c_cflag &= (unsigned long) ~(CRTSCTS); +#elif defined CNEW_RTSCTS + if (rtscts_) + options.c_cflag |= (CNEW_RTSCTS); + else + options.c_cflag &= (unsigned long) ~(CNEW_RTSCTS); +#else +#error "OS Support seems wrong." +#endif + + // http://www.unixwiz.net/techtips/termios-vmin-vtime.html + // this basically sets the read call up to be a polling read, + // but we are using select to ensure there is data available + // to read before each call, so we should never needlessly poll + options.c_cc[VMIN] = 0; + options.c_cc[VTIME] = 0; + + // activate settings + ::tcsetattr (fd_, TCSANOW, &options); + + // apply custom baud rate, if any + if (custom_baud == true) { + // OS X support +#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4) + // Starting with Tiger, the IOSSIOSPEED ioctl can be used to set arbitrary baud rates + // other than those specified by POSIX. The driver for the underlying serial hardware + // ultimately determines which baud rates can be used. This ioctl sets both the input + // and output speed. + speed_t new_baud = static_cast (baudrate_); + // PySerial uses IOSSIOSPEED=0x80045402 + if (-1 == ioctl (fd_, IOSSIOSPEED, &new_baud, 1)) { + THROW (IOException, errno); + } + // Linux Support +#elif defined(__linux__) && defined (TIOCSSERIAL) + struct serial_struct ser; + + if (-1 == ioctl (fd_, TIOCGSERIAL, &ser)) { + THROW (IOException, errno); + } + + // set custom divisor + ser.custom_divisor = ser.baud_base / static_cast (baudrate_); + // update flags + ser.flags &= ~ASYNC_SPD_MASK; + ser.flags |= ASYNC_SPD_CUST; + + if (-1 == ioctl (fd_, TIOCSSERIAL, &ser)) { + THROW (IOException, errno); + } +#else + throw invalid_argument ("OS does not currently support custom bauds"); +#endif + } + + // Update byte_time_ based on the new settings. + uint32_t bit_time_ns = 1e9 / baudrate_; + byte_time_ns_ = bit_time_ns * (1 + bytesize_ + parity_ + stopbits_); + + // Compensate for the stopbits_one_point_five enum being equal to int 3, + // and not 1.5. + if (stopbits_ == stopbits_one_point_five) { + byte_time_ns_ += ((1.5 - stopbits_one_point_five) * bit_time_ns); + } +} + +void +Serial::SerialImpl::close () +{ + if (is_open_ == true) { + if (fd_ != -1) { + int ret; + ret = ::close (fd_); + if (ret == 0) { + fd_ = -1; + } else { + THROW (IOException, errno); + } + } + is_open_ = false; + } +} + +bool +Serial::SerialImpl::isOpen () const +{ + return is_open_; +} + +size_t +Serial::SerialImpl::available () +{ + if (!is_open_) { + return 0; + } + int count = 0; + if (-1 == ioctl (fd_, TIOCINQ, &count)) { + THROW (IOException, errno); + } else { + return static_cast (count); + } +} + +bool +Serial::SerialImpl::waitReadable (uint32_t timeout) +{ + // Setup a select call to block for serial data or a timeout + fd_set readfds; + FD_ZERO (&readfds); + FD_SET (fd_, &readfds); + timespec timeout_ts (timespec_from_ms (timeout)); + int r = pselect (fd_ + 1, &readfds, NULL, NULL, &timeout_ts, NULL); + + if (r < 0) { + // Select was interrupted + if (errno == EINTR) { + return false; + } + // Otherwise there was some error + THROW (IOException, errno); + } + // Timeout occurred + if (r == 0) { + return false; + } + // This shouldn't happen, if r > 0 our fd has to be in the list! + if (!FD_ISSET (fd_, &readfds)) { + THROW (IOException, "select reports ready to read, but our fd isn't" + " in the list, this shouldn't happen!"); + } + // Data available to read. + return true; +} + +void +Serial::SerialImpl::waitByteTimes (size_t count) +{ + timespec wait_time = { 0, static_cast(byte_time_ns_ * count)}; + pselect (0, NULL, NULL, NULL, &wait_time, NULL); +} + +size_t +Serial::SerialImpl::read (uint8_t *buf, size_t size) +{ + // If the port is not open, throw + if (!is_open_) { + throw PortNotOpenedException ("Serial::read"); + } + size_t bytes_read = 0; + + // Calculate total timeout in milliseconds t_c + (t_m * N) + long total_timeout_ms = timeout_.read_timeout_constant; + total_timeout_ms += timeout_.read_timeout_multiplier * static_cast (size); + MillisecondTimer total_timeout(total_timeout_ms); + + // Pre-fill buffer with available bytes + { + ssize_t bytes_read_now = ::read (fd_, buf, size); + if (bytes_read_now > 0) { + bytes_read = bytes_read_now; + } + } + + while (bytes_read < size) { + int64_t timeout_remaining_ms = total_timeout.remaining(); + if (timeout_remaining_ms <= 0) { + // Timed out + break; + } + // Timeout for the next select is whichever is less of the remaining + // total read timeout and the inter-byte timeout. + uint32_t timeout = std::min(static_cast (timeout_remaining_ms), + timeout_.inter_byte_timeout); + // Wait for the device to be readable, and then attempt to read. + if (waitReadable(timeout)) { + // If it's a fixed-length multi-byte read, insert a wait here so that + // we can attempt to grab the whole thing in a single IO call. Skip + // this wait if a non-max inter_byte_timeout is specified. + if (size > 1 && timeout_.inter_byte_timeout == Timeout::max()) { + size_t bytes_available = available(); + if (bytes_available + bytes_read < size) { + waitByteTimes(size - (bytes_available + bytes_read)); + } + } + // This should be non-blocking returning only what is available now + // Then returning so that select can block again. + ssize_t bytes_read_now = + ::read (fd_, buf + bytes_read, size - bytes_read); + // read should always return some data as select reported it was + // ready to read when we get to this point. + if (bytes_read_now < 1) { + // Disconnected devices, at least on Linux, show the + // behavior that they are always ready to read immediately + // but reading returns nothing. + throw SerialException ("device reports readiness to read but " + "returned no data (device disconnected?)"); + } + // Update bytes_read + bytes_read += static_cast (bytes_read_now); + // If bytes_read == size then we have read everything we need + if (bytes_read == size) { + break; + } + // If bytes_read < size then we have more to read + if (bytes_read < size) { + continue; + } + // If bytes_read > size then we have over read, which shouldn't happen + if (bytes_read > size) { + throw SerialException ("read over read, too many bytes where " + "read, this shouldn't happen, might be " + "a logical error!"); + } + } + } + return bytes_read; +} + +size_t +Serial::SerialImpl::write (const uint8_t *data, size_t length) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::write"); + } + fd_set writefds; + size_t bytes_written = 0; + + // Calculate total timeout in milliseconds t_c + (t_m * N) + long total_timeout_ms = timeout_.write_timeout_constant; + total_timeout_ms += timeout_.write_timeout_multiplier * static_cast (length); + MillisecondTimer total_timeout(total_timeout_ms); + + bool first_iteration = true; + while (bytes_written < length) { + int64_t timeout_remaining_ms = total_timeout.remaining(); + // Only consider the timeout if it's not the first iteration of the loop + // otherwise a timeout of 0 won't be allowed through + if (!first_iteration && (timeout_remaining_ms <= 0)) { + // Timed out + break; + } + first_iteration = false; + + timespec timeout(timespec_from_ms(timeout_remaining_ms)); + + FD_ZERO (&writefds); + FD_SET (fd_, &writefds); + + // Do the select + int r = pselect (fd_ + 1, NULL, &writefds, NULL, &timeout, NULL); + + // Figure out what happened by looking at select's response 'r' + /** Error **/ + if (r < 0) { + // Select was interrupted, try again + if (errno == EINTR) { + continue; + } + // Otherwise there was some error + THROW (IOException, errno); + } + /** Timeout **/ + if (r == 0) { + break; + } + /** Port ready to write **/ + if (r > 0) { + // Make sure our file descriptor is in the ready to write list + if (FD_ISSET (fd_, &writefds)) { + // This will write some + ssize_t bytes_written_now = + ::write (fd_, data + bytes_written, length - bytes_written); + + // even though pselect returned readiness the call might still be + // interrupted. In that case simply retry. + if (bytes_written_now == -1 && errno == EINTR) { + continue; + } + + // write should always return some data as select reported it was + // ready to write when we get to this point. + if (bytes_written_now < 1) { + // Disconnected devices, at least on Linux, show the + // behavior that they are always ready to write immediately + // but writing returns nothing. + std::stringstream strs; + strs << "device reports readiness to write but " + "returned no data (device disconnected?)"; + strs << " errno=" << errno; + strs << " bytes_written_now= " << bytes_written_now; + strs << " bytes_written=" << bytes_written; + strs << " length=" << length; + throw SerialException(strs.str().c_str()); + } + // Update bytes_written + bytes_written += static_cast (bytes_written_now); + // If bytes_written == size then we have written everything we need to + if (bytes_written == length) { + break; + } + // If bytes_written < size then we have more to write + if (bytes_written < length) { + continue; + } + // If bytes_written > size then we have over written, which shouldn't happen + if (bytes_written > length) { + throw SerialException ("write over wrote, too many bytes where " + "written, this shouldn't happen, might be " + "a logical error!"); + } + } + // This shouldn't happen, if r > 0 our fd has to be in the list! + THROW (IOException, "select reports ready to write, but our fd isn't" + " in the list, this shouldn't happen!"); + } + } + return bytes_written; +} + +void +Serial::SerialImpl::setPort (const string &port) +{ + port_ = port; +} + +string +Serial::SerialImpl::getPort () const +{ + return port_; +} + +void +Serial::SerialImpl::setTimeout (serial::Timeout &timeout) +{ + timeout_ = timeout; +} + +serial::Timeout +Serial::SerialImpl::getTimeout () const +{ + return timeout_; +} + +void +Serial::SerialImpl::setBaudrate (unsigned long baudrate) +{ + baudrate_ = baudrate; + if (is_open_) + reconfigurePort (); +} + +unsigned long +Serial::SerialImpl::getBaudrate () const +{ + return baudrate_; +} + +void +Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize) +{ + bytesize_ = bytesize; + if (is_open_) + reconfigurePort (); +} + +serial::bytesize_t +Serial::SerialImpl::getBytesize () const +{ + return bytesize_; +} + +void +Serial::SerialImpl::setParity (serial::parity_t parity) +{ + parity_ = parity; + if (is_open_) + reconfigurePort (); +} + +serial::parity_t +Serial::SerialImpl::getParity () const +{ + return parity_; +} + +void +Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits) +{ + stopbits_ = stopbits; + if (is_open_) + reconfigurePort (); +} + +serial::stopbits_t +Serial::SerialImpl::getStopbits () const +{ + return stopbits_; +} + +void +Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol) +{ + flowcontrol_ = flowcontrol; + if (is_open_) + reconfigurePort (); +} + +serial::flowcontrol_t +Serial::SerialImpl::getFlowcontrol () const +{ + return flowcontrol_; +} + +void +Serial::SerialImpl::flush () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flush"); + } + tcdrain (fd_); +} + +void +Serial::SerialImpl::flushInput () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flushInput"); + } + tcflush (fd_, TCIFLUSH); +} + +void +Serial::SerialImpl::flushOutput () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flushOutput"); + } + tcflush (fd_, TCOFLUSH); +} + +void +Serial::SerialImpl::sendBreak (int duration) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::sendBreak"); + } + tcsendbreak (fd_, static_cast (duration / 4)); +} + +void +Serial::SerialImpl::setBreak (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setBreak"); + } + + if (level) { + if (-1 == ioctl (fd_, TIOCSBRK)) + { + stringstream ss; + ss << "setBreak failed on a call to ioctl(TIOCSBRK): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCCBRK)) + { + stringstream ss; + ss << "setBreak failed on a call to ioctl(TIOCCBRK): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +void +Serial::SerialImpl::setRTS (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setRTS"); + } + + int command = TIOCM_RTS; + + if (level) { + if (-1 == ioctl (fd_, TIOCMBIS, &command)) + { + stringstream ss; + ss << "setRTS failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCMBIC, &command)) + { + stringstream ss; + ss << "setRTS failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +void +Serial::SerialImpl::setDTR (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setDTR"); + } + + int command = TIOCM_DTR; + + if (level) { + if (-1 == ioctl (fd_, TIOCMBIS, &command)) + { + stringstream ss; + ss << "setDTR failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } else { + if (-1 == ioctl (fd_, TIOCMBIC, &command)) + { + stringstream ss; + ss << "setDTR failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + } +} + +bool +Serial::SerialImpl::waitForChange () +{ +#ifndef TIOCMIWAIT + +while (is_open_ == true) { + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "waitForChange failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + if (0 != (status & TIOCM_CTS) + || 0 != (status & TIOCM_DSR) + || 0 != (status & TIOCM_RI) + || 0 != (status & TIOCM_CD)) + { + return true; + } + } + + usleep(1000); + } + + return false; +#else + int command = (TIOCM_CD|TIOCM_DSR|TIOCM_RI|TIOCM_CTS); + + if (-1 == ioctl (fd_, TIOCMIWAIT, &command)) { + stringstream ss; + ss << "waitForDSR failed on a call to ioctl(TIOCMIWAIT): " + << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + return true; +#endif +} + +bool +Serial::SerialImpl::getCTS () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCTS"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getCTS failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_CTS); + } +} + +bool +Serial::SerialImpl::getDSR () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getDSR"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getDSR failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_DSR); + } +} + +bool +Serial::SerialImpl::getRI () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getRI"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getRI failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_RI); + } +} + +bool +Serial::SerialImpl::getCD () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCD"); + } + + int status; + + if (-1 == ioctl (fd_, TIOCMGET, &status)) + { + stringstream ss; + ss << "getCD failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno); + throw(SerialException(ss.str().c_str())); + } + else + { + return 0 != (status & TIOCM_CD); + } +} + +void +Serial::SerialImpl::readLock () +{ + int result = pthread_mutex_lock(&this->read_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::readUnlock () +{ + int result = pthread_mutex_unlock(&this->read_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::writeLock () +{ + int result = pthread_mutex_lock(&this->write_mutex); + if (result) { + THROW (IOException, result); + } +} + +void +Serial::SerialImpl::writeUnlock () +{ + int result = pthread_mutex_unlock(&this->write_mutex); + if (result) { + THROW (IOException, result); + } +} + +#endif // !defined(_WIN32) diff --git a/third_party/flserial/src/native_libs/src/impl/win.cpp b/third_party/flserial/src/native_libs/src/impl/win.cpp new file mode 100644 index 00000000..cbccf048 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/impl/win.cpp @@ -0,0 +1,651 @@ +#if defined(_WIN32) + +/* Copyright 2012 William Woodall and John Harrison */ + +#include + +#include "serial/impl/win.h" + +using std::string; +using std::wstring; +using std::stringstream; +using std::invalid_argument; +using serial::Serial; +using serial::Timeout; +using serial::bytesize_t; +using serial::parity_t; +using serial::stopbits_t; +using serial::flowcontrol_t; +using serial::SerialException; +using serial::PortNotOpenedException; +using serial::IOException; + +inline wstring +_prefix_port_if_needed(const wstring &input) +{ + static wstring windows_com_port_prefix = L"\\\\.\\"; + if (input.compare(0, windows_com_port_prefix.size(), windows_com_port_prefix) != 0) + { + return windows_com_port_prefix + input; + } + return input; +} + +Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate, + bytesize_t bytesize, + parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : port_ (port.begin(), port.end()), fd_ (INVALID_HANDLE_VALUE), is_open_ (false), + baudrate_ (baudrate), parity_ (parity), + bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol) +{ + if (port_.empty () == false) + open (); + read_mutex = CreateMutex(NULL, false, NULL); + write_mutex = CreateMutex(NULL, false, NULL); +} + +Serial::SerialImpl::~SerialImpl () +{ + this->close(); + CloseHandle(read_mutex); + CloseHandle(write_mutex); +} + +void +Serial::SerialImpl::open () +{ + if (port_.empty ()) { + throw invalid_argument ("Empty port is invalid."); + } + if (is_open_ == true) { + throw SerialException ("Serial port already open."); + } + + // See: https://github.com/wjwwood/serial/issues/84 + wstring port_with_prefix = _prefix_port_if_needed(port_); + LPCWSTR lp_port = port_with_prefix.c_str(); + fd_ = CreateFileW(lp_port, + GENERIC_READ | GENERIC_WRITE, + 0, + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + 0); + + if (fd_ == INVALID_HANDLE_VALUE) { + DWORD create_file_err = GetLastError(); + stringstream ss; + switch (create_file_err) { + case ERROR_FILE_NOT_FOUND: + // Use this->getPort to convert to a std::string + ss << "Specified port, " << this->getPort() << ", does not exist."; + THROWEX (IOException, ss.str().c_str(), 1); + case ERROR_ACCESS_DENIED: + ss << "Specified port, " << this->getPort() << ", allready open."; + THROWEX (IOException, ss.str().c_str(), 2); + default: + ss << "Unknown error opening the serial port: " << create_file_err; + THROW (IOException, ss.str().c_str()); + } + } + + + + reconfigurePort(); + is_open_ = true; +} + +void +Serial::SerialImpl::reconfigurePort () +{ + if (fd_ == INVALID_HANDLE_VALUE) { + // Can only operate on a valid file descriptor + THROW (IOException, "Invalid file descriptor, is the serial port open?"); + } + + DCB dcbSerialParams = {0}; + + dcbSerialParams.DCBlength=sizeof(dcbSerialParams); + + if (!GetCommState(fd_, &dcbSerialParams)) { + //error getting state + THROW (IOException, "Error getting the serial port state."); + } + + // setup baud rate + switch (baudrate_) { +#ifdef CBR_0 + case 0: dcbSerialParams.BaudRate = CBR_0; break; +#endif +#ifdef CBR_50 + case 50: dcbSerialParams.BaudRate = CBR_50; break; +#endif +#ifdef CBR_75 + case 75: dcbSerialParams.BaudRate = CBR_75; break; +#endif +#ifdef CBR_110 + case 110: dcbSerialParams.BaudRate = CBR_110; break; +#endif +#ifdef CBR_134 + case 134: dcbSerialParams.BaudRate = CBR_134; break; +#endif +#ifdef CBR_150 + case 150: dcbSerialParams.BaudRate = CBR_150; break; +#endif +#ifdef CBR_200 + case 200: dcbSerialParams.BaudRate = CBR_200; break; +#endif +#ifdef CBR_300 + case 300: dcbSerialParams.BaudRate = CBR_300; break; +#endif +#ifdef CBR_600 + case 600: dcbSerialParams.BaudRate = CBR_600; break; +#endif +#ifdef CBR_1200 + case 1200: dcbSerialParams.BaudRate = CBR_1200; break; +#endif +#ifdef CBR_1800 + case 1800: dcbSerialParams.BaudRate = CBR_1800; break; +#endif +#ifdef CBR_2400 + case 2400: dcbSerialParams.BaudRate = CBR_2400; break; +#endif +#ifdef CBR_4800 + case 4800: dcbSerialParams.BaudRate = CBR_4800; break; +#endif +#ifdef CBR_7200 + case 7200: dcbSerialParams.BaudRate = CBR_7200; break; +#endif +#ifdef CBR_9600 + case 9600: dcbSerialParams.BaudRate = CBR_9600; break; +#endif +#ifdef CBR_14400 + case 14400: dcbSerialParams.BaudRate = CBR_14400; break; +#endif +#ifdef CBR_19200 + case 19200: dcbSerialParams.BaudRate = CBR_19200; break; +#endif +#ifdef CBR_28800 + case 28800: dcbSerialParams.BaudRate = CBR_28800; break; +#endif +#ifdef CBR_57600 + case 57600: dcbSerialParams.BaudRate = CBR_57600; break; +#endif +#ifdef CBR_76800 + case 76800: dcbSerialParams.BaudRate = CBR_76800; break; +#endif +#ifdef CBR_38400 + case 38400: dcbSerialParams.BaudRate = CBR_38400; break; +#endif +#ifdef CBR_115200 + case 115200: dcbSerialParams.BaudRate = CBR_115200; break; +#endif +#ifdef CBR_128000 + case 128000: dcbSerialParams.BaudRate = CBR_128000; break; +#endif +#ifdef CBR_153600 + case 153600: dcbSerialParams.BaudRate = CBR_153600; break; +#endif +#ifdef CBR_230400 + case 230400: dcbSerialParams.BaudRate = CBR_230400; break; +#endif +#ifdef CBR_256000 + case 256000: dcbSerialParams.BaudRate = CBR_256000; break; +#endif +#ifdef CBR_460800 + case 460800: dcbSerialParams.BaudRate = CBR_460800; break; +#endif +#ifdef CBR_921600 + case 921600: dcbSerialParams.BaudRate = CBR_921600; break; +#endif + default: + // Try to blindly assign it + dcbSerialParams.BaudRate = baudrate_; + } + + // setup char len + if (bytesize_ == eightbits) + dcbSerialParams.ByteSize = 8; + else if (bytesize_ == sevenbits) + dcbSerialParams.ByteSize = 7; + else if (bytesize_ == sixbits) + dcbSerialParams.ByteSize = 6; + else if (bytesize_ == fivebits) + dcbSerialParams.ByteSize = 5; + else + throw invalid_argument ("invalid char len"); + + // setup stopbits + if (stopbits_ == stopbits_one) + dcbSerialParams.StopBits = ONESTOPBIT; + else if (stopbits_ == stopbits_one_point_five) + dcbSerialParams.StopBits = ONE5STOPBITS; + else if (stopbits_ == stopbits_two) + dcbSerialParams.StopBits = TWOSTOPBITS; + else + throw invalid_argument ("invalid stop bit"); + + // setup parity + if (parity_ == parity_none) { + dcbSerialParams.Parity = NOPARITY; + } else if (parity_ == parity_even) { + dcbSerialParams.Parity = EVENPARITY; + } else if (parity_ == parity_odd) { + dcbSerialParams.Parity = ODDPARITY; + } else if (parity_ == parity_mark) { + dcbSerialParams.Parity = MARKPARITY; + } else if (parity_ == parity_space) { + dcbSerialParams.Parity = SPACEPARITY; + } else { + throw invalid_argument ("invalid parity"); + } + + // setup flowcontrol + if (flowcontrol_ == flowcontrol_none) { + dcbSerialParams.fOutxCtsFlow = false; + dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE; + dcbSerialParams.fOutX = false; + dcbSerialParams.fInX = false; + } + if (flowcontrol_ == flowcontrol_software) { + dcbSerialParams.fOutxCtsFlow = false; + dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE; + dcbSerialParams.fOutX = true; + dcbSerialParams.fInX = true; + } + if (flowcontrol_ == flowcontrol_hardware) { + dcbSerialParams.fOutxCtsFlow = true; + dcbSerialParams.fRtsControl = RTS_CONTROL_HANDSHAKE; + dcbSerialParams.fOutX = false; + dcbSerialParams.fInX = false; + } + + // activate settings + if (!SetCommState(fd_, &dcbSerialParams)){ + CloseHandle(fd_); + THROW (IOException, "Error setting serial port settings."); + } + + // Setup timeouts + COMMTIMEOUTS timeouts = {0}; + timeouts.ReadIntervalTimeout = timeout_.inter_byte_timeout; + timeouts.ReadTotalTimeoutConstant = timeout_.read_timeout_constant; + timeouts.ReadTotalTimeoutMultiplier = timeout_.read_timeout_multiplier; + timeouts.WriteTotalTimeoutConstant = timeout_.write_timeout_constant; + timeouts.WriteTotalTimeoutMultiplier = timeout_.write_timeout_multiplier; + if (!SetCommTimeouts(fd_, &timeouts)) { + THROW (IOException, "Error setting timeouts."); + } +} + +void +Serial::SerialImpl::close () +{ + if (is_open_ == true) { + if (fd_ != INVALID_HANDLE_VALUE) { + int ret; + ret = CloseHandle(fd_); + if (ret == 0) { + stringstream ss; + ss << "Error while closing serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } else { + fd_ = INVALID_HANDLE_VALUE; + } + } + is_open_ = false; + } +} + +bool +Serial::SerialImpl::isOpen () const +{ + return is_open_; +} + +size_t +Serial::SerialImpl::available () +{ + if (!is_open_) { + return 0; + } + COMSTAT cs; + if (!ClearCommError(fd_, NULL, &cs)) { + stringstream ss; + ss << "Error while checking status of the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return static_cast(cs.cbInQue); +} + +bool +Serial::SerialImpl::waitReadable (uint32_t /*timeout*/) +{ + THROW (IOException, "waitReadable is not implemented on Windows."); + return false; +} + +void +Serial::SerialImpl::waitByteTimes (size_t /*count*/) +{ + THROW (IOException, "waitByteTimes is not implemented on Windows."); +} + +size_t +Serial::SerialImpl::read (uint8_t *buf, size_t size) +{ + if (!is_open_) { + throw PortNotOpenedException ("Serial::read"); + } + DWORD bytes_read; + if (!ReadFile(fd_, buf, static_cast(size), &bytes_read, NULL)) { + stringstream ss; + ss << "Error while reading from the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return (size_t) (bytes_read); +} + +size_t +Serial::SerialImpl::write (const uint8_t *data, size_t length) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::write"); + } + DWORD bytes_written; + if (!WriteFile(fd_, data, static_cast(length), &bytes_written, NULL)) { + stringstream ss; + ss << "Error while writing to the serial port: " << GetLastError(); + THROW (IOException, ss.str().c_str()); + } + return (size_t) (bytes_written); +} + +void +Serial::SerialImpl::setPort (const string &port) +{ + port_ = wstring(port.begin(), port.end()); +} + +string +Serial::SerialImpl::getPort () const +{ + return string(port_.begin(), port_.end()); +} + +void +Serial::SerialImpl::setTimeout (serial::Timeout &timeout) +{ + timeout_ = timeout; + if (is_open_) { + reconfigurePort (); + } +} + +serial::Timeout +Serial::SerialImpl::getTimeout () const +{ + return timeout_; +} + +void +Serial::SerialImpl::setBaudrate (unsigned long baudrate) +{ + baudrate_ = baudrate; + if (is_open_) { + reconfigurePort (); + } +} + +unsigned long +Serial::SerialImpl::getBaudrate () const +{ + return baudrate_; +} + +void +Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize) +{ + bytesize_ = bytesize; + if (is_open_) { + reconfigurePort (); + } +} + +serial::bytesize_t +Serial::SerialImpl::getBytesize () const +{ + return bytesize_; +} + +void +Serial::SerialImpl::setParity (serial::parity_t parity) +{ + parity_ = parity; + if (is_open_) { + reconfigurePort (); + } +} + +serial::parity_t +Serial::SerialImpl::getParity () const +{ + return parity_; +} + +void +Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits) +{ + stopbits_ = stopbits; + if (is_open_) { + reconfigurePort (); + } +} + +serial::stopbits_t +Serial::SerialImpl::getStopbits () const +{ + return stopbits_; +} + +void +Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol) +{ + flowcontrol_ = flowcontrol; + if (is_open_) { + reconfigurePort (); + } +} + +serial::flowcontrol_t +Serial::SerialImpl::getFlowcontrol () const +{ + return flowcontrol_; +} + +void +Serial::SerialImpl::flush () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::flush"); + } + FlushFileBuffers (fd_); +} + +void +Serial::SerialImpl::flushInput () +{ + if (is_open_ == false) { + throw PortNotOpenedException("Serial::flushInput"); + } + PurgeComm(fd_, PURGE_RXCLEAR); +} + +void +Serial::SerialImpl::flushOutput () +{ + if (is_open_ == false) { + throw PortNotOpenedException("Serial::flushOutput"); + } + PurgeComm(fd_, PURGE_TXCLEAR); +} + +void +Serial::SerialImpl::sendBreak (int /*duration*/) +{ + THROW (IOException, "sendBreak is not supported on Windows."); +} + +void +Serial::SerialImpl::setBreak (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setBreak"); + } + if (level) { + EscapeCommFunction (fd_, SETBREAK); + } else { + EscapeCommFunction (fd_, CLRBREAK); + } +} + +void +Serial::SerialImpl::setRTS (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setRTS"); + } + if (level) { + EscapeCommFunction (fd_, SETRTS); + } else { + EscapeCommFunction (fd_, CLRRTS); + } +} + +void +Serial::SerialImpl::setDTR (bool level) +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::setDTR"); + } + if (level) { + EscapeCommFunction (fd_, SETDTR); + } else { + EscapeCommFunction (fd_, CLRDTR); + } +} + +bool +Serial::SerialImpl::waitForChange () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::waitForChange"); + } + DWORD dwCommEvent; + + if (!SetCommMask(fd_, EV_CTS | EV_DSR | EV_RING | EV_RLSD)) { + // Error setting communications mask + return false; + } + + if (!WaitCommEvent(fd_, &dwCommEvent, NULL)) { + // An error occurred waiting for the event. + return false; + } else { + // Event has occurred. + return true; + } +} + +bool +Serial::SerialImpl::getCTS () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCTS"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the CTS line."); + } + + return (MS_CTS_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getDSR () +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getDSR"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the DSR line."); + } + + return (MS_DSR_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getRI() +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getRI"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + THROW (IOException, "Error getting the status of the RI line."); + } + + return (MS_RING_ON & dwModemStatus) != 0; +} + +bool +Serial::SerialImpl::getCD() +{ + if (is_open_ == false) { + throw PortNotOpenedException ("Serial::getCD"); + } + DWORD dwModemStatus; + if (!GetCommModemStatus(fd_, &dwModemStatus)) { + // Error in GetCommModemStatus; + THROW (IOException, "Error getting the status of the CD line."); + } + + return (MS_RLSD_ON & dwModemStatus) != 0; +} + +void +Serial::SerialImpl::readLock() +{ + if (WaitForSingleObject(read_mutex, INFINITE) != WAIT_OBJECT_0) { + THROW (IOException, "Error claiming read mutex."); + } +} + +void +Serial::SerialImpl::readUnlock() +{ + if (!ReleaseMutex(read_mutex)) { + THROW (IOException, "Error releasing read mutex."); + } +} + +void +Serial::SerialImpl::writeLock() +{ + if (WaitForSingleObject(write_mutex, INFINITE) != WAIT_OBJECT_0) { + THROW (IOException, "Error claiming write mutex."); + } +} + +void +Serial::SerialImpl::writeUnlock() +{ + if (!ReleaseMutex(write_mutex)) { + THROW (IOException, "Error releasing write mutex."); + } +} + +#endif // #if defined(_WIN32) + diff --git a/third_party/flserial/src/native_libs/src/ringbuffer.c b/third_party/flserial/src/native_libs/src/ringbuffer.c new file mode 100644 index 00000000..39fbea59 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/ringbuffer.c @@ -0,0 +1,78 @@ +#include "ringbuffer.h" + +/** + * @file + * Implementation of ring buffer functions. + */ + +void ring_buffer_init(ring_buffer_t *buffer, char *buf, size_t buf_size) { + RING_BUFFER_ASSERT(RING_BUFFER_IS_POWER_OF_TWO(buf_size) == 1); + buffer->buffer = buf; + buffer->buffer_mask = buf_size - 1; + buffer->tail_index = 0; + buffer->head_index = 0; +} + +void ring_buffer_queue(ring_buffer_t *buffer, char data) { + /* Is buffer full? */ + if(ring_buffer_is_full(buffer)) { + /* Is going to overwrite the oldest byte */ + /* Increase tail index */ + buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer)); + } + + /* Place data in buffer */ + buffer->buffer[buffer->head_index] = data; + buffer->head_index = ((buffer->head_index + 1) & RING_BUFFER_MASK(buffer)); +} + +void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size) { + /* Add bytes; one by one */ + ring_buffer_size_t i; + for(i = 0; i < size; i++) { + ring_buffer_queue(buffer, data[i]); + } +} + +uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data) { + if(ring_buffer_is_empty(buffer)) { + /* No items */ + return 0; + } + + *data = buffer->buffer[buffer->tail_index]; + buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK(buffer)); + return 1; +} + +ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len) { + if(ring_buffer_is_empty(buffer)) { + /* No items */ + return 0; + } + + char *data_ptr = data; + ring_buffer_size_t cnt = 0; + while((cnt < len) && ring_buffer_dequeue(buffer, data_ptr)) { + cnt++; + data_ptr++; + } + return cnt; +} + +uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index) { + if(index >= ring_buffer_num_items(buffer)) { + /* No items at index */ + return 0; + } + + /* Add index to pointer */ + ring_buffer_size_t data_index = ((buffer->tail_index + index) & RING_BUFFER_MASK(buffer)); + *data = buffer->buffer[data_index]; + return 1; +} + +extern inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer); +extern inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer); +extern inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer); + diff --git a/third_party/flserial/src/native_libs/src/serial.cpp b/third_party/flserial/src/native_libs/src/serial.cpp new file mode 100644 index 00000000..06a15a99 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/serial.cpp @@ -0,0 +1,432 @@ +/* Copyright 2012 William Woodall and John Harrison */ +#include + +#if !defined(_WIN32) && !defined(__OpenBSD__) && !defined(__FreeBSD__) +# include +#endif + +#if defined (__MINGW32__) +# define alloca __builtin_alloca +#endif + +#include "../include/serial/serial.h" + +#ifdef _WIN32 +#include "serial/impl/win.h" +#else +#include "../include/serial/impl/unix.h" +#endif + +using std::invalid_argument; +using std::min; +using std::numeric_limits; +using std::vector; +using std::size_t; +using std::string; + +using serial::Serial; +using serial::SerialException; +using serial::IOException; +using serial::bytesize_t; +using serial::parity_t; +using serial::stopbits_t; +using serial::flowcontrol_t; + +class Serial::ScopedReadLock { +public: + ScopedReadLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->readLock(); + } + ~ScopedReadLock() { + this->pimpl_->readUnlock(); + } +private: + // Disable copy constructors + ScopedReadLock(const ScopedReadLock&); + const ScopedReadLock& operator=(ScopedReadLock); + + SerialImpl *pimpl_; +}; + +class Serial::ScopedWriteLock { +public: + ScopedWriteLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->writeLock(); + } + ~ScopedWriteLock() { + this->pimpl_->writeUnlock(); + } +private: + // Disable copy constructors + ScopedWriteLock(const ScopedWriteLock&); + const ScopedWriteLock& operator=(ScopedWriteLock); + SerialImpl *pimpl_; +}; + +Serial::Serial (const string &port, uint32_t baudrate, serial::Timeout timeout, + bytesize_t bytesize, parity_t parity, stopbits_t stopbits, + flowcontrol_t flowcontrol) + : pimpl_(new SerialImpl (port, baudrate, bytesize, parity, + stopbits, flowcontrol)) +{ + pimpl_->setTimeout(timeout); +} + +Serial::~Serial () +{ + delete pimpl_; +} + +void +Serial::open () +{ + pimpl_->open (); +} + +void +Serial::close () +{ + pimpl_->close (); +} + +bool +Serial::isOpen () const +{ + return pimpl_->isOpen (); +} + +size_t +Serial::available () +{ + return pimpl_->available (); +} + +bool +Serial::waitReadable () +{ + serial::Timeout timeout(pimpl_->getTimeout ()); + return pimpl_->waitReadable(timeout.read_timeout_constant); +} + +void +Serial::waitByteTimes (size_t count) +{ + pimpl_->waitByteTimes(count); +} + +size_t +Serial::read_ (uint8_t *buffer, size_t size) +{ + return this->pimpl_->read (buffer, size); +} + +size_t +Serial::read (uint8_t *buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + return this->pimpl_->read (buffer, size); +} + +size_t +Serial::read (std::vector &buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + uint8_t *buffer_ = new uint8_t[size]; + size_t bytes_read = 0; + + try { + bytes_read = this->pimpl_->read (buffer_, size); + } + catch (const std::exception) { + delete[] buffer_; + throw; + } + + buffer.insert (buffer.end (), buffer_, buffer_+bytes_read); + delete[] buffer_; + return bytes_read; +} + +size_t +Serial::read (std::string &buffer, size_t size) +{ + ScopedReadLock lock(this->pimpl_); + uint8_t *buffer_ = new uint8_t[size]; + size_t bytes_read = 0; + try { + bytes_read = this->pimpl_->read (buffer_, size); + } + catch (const std::exception) { + delete[] buffer_; + throw; + } + buffer.append (reinterpret_cast(buffer_), bytes_read); + delete[] buffer_; + return bytes_read; +} + +string +Serial::read (size_t size) +{ + std::string buffer; + this->read (buffer, size); + return buffer; +} + +size_t +Serial::readline (string &buffer, size_t size, string eol) +{ + ScopedReadLock lock(this->pimpl_); + size_t eol_len = eol.length (); + uint8_t *buffer_ = static_cast + (alloca (size * sizeof (uint8_t))); + size_t read_so_far = 0; + while (true) + { + size_t bytes_read = this->read_ (buffer_ + read_so_far, 1); + read_so_far += bytes_read; + if (bytes_read == 0) { + break; // Timeout occured on reading 1 byte + } + if(read_so_far < eol_len) continue; + if (string (reinterpret_cast + (buffer_ + read_so_far - eol_len), eol_len) == eol) { + break; // EOL found + } + if (read_so_far == size) { + break; // Reached the maximum read length + } + } + buffer.append(reinterpret_cast (buffer_), read_so_far); + return read_so_far; +} + +string +Serial::readline (size_t size, string eol) +{ + std::string buffer; + this->readline (buffer, size, eol); + return buffer; +} + +vector +Serial::readlines (size_t size, string eol) +{ + ScopedReadLock lock(this->pimpl_); + std::vector lines; + size_t eol_len = eol.length (); + uint8_t *buffer_ = static_cast + (alloca (size * sizeof (uint8_t))); + size_t read_so_far = 0; + size_t start_of_line = 0; + while (read_so_far < size) { + size_t bytes_read = this->read_ (buffer_+read_so_far, 1); + read_so_far += bytes_read; + if (bytes_read == 0) { + if (start_of_line != read_so_far) { + lines.push_back ( + string (reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + } + break; // Timeout occured on reading 1 byte + } + if(read_so_far < eol_len) continue; + if (string (reinterpret_cast + (buffer_ + read_so_far - eol_len), eol_len) == eol) { + // EOL found + lines.push_back( + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + start_of_line = read_so_far; + } + if (read_so_far == size) { + if (start_of_line != read_so_far) { + lines.push_back( + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); + } + break; // Reached the maximum read length + } + } + return lines; +} + +size_t +Serial::write (const string &data) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_ (reinterpret_cast(data.c_str()), + data.length()); +} + +size_t +Serial::write (const std::vector &data) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_ (&data[0], data.size()); +} + +size_t +Serial::write (const uint8_t *data, size_t size) +{ + ScopedWriteLock lock(this->pimpl_); + return this->write_(data, size); +} + +size_t +Serial::write_ (const uint8_t *data, size_t length) +{ + return pimpl_->write (data, length); +} + +void +Serial::setPort (const string &port) +{ + ScopedReadLock rlock(this->pimpl_); + ScopedWriteLock wlock(this->pimpl_); + bool was_open = pimpl_->isOpen (); + if (was_open) close(); + pimpl_->setPort (port); + if (was_open) open (); +} + +string +Serial::getPort () const +{ + return pimpl_->getPort (); +} + +void +Serial::setTimeout (serial::Timeout &timeout) +{ + pimpl_->setTimeout (timeout); +} + +serial::Timeout +Serial::getTimeout () const { + return pimpl_->getTimeout (); +} + +void +Serial::setBaudrate (uint32_t baudrate) +{ + pimpl_->setBaudrate (baudrate); +} + +uint32_t +Serial::getBaudrate () const +{ + return uint32_t(pimpl_->getBaudrate ()); +} + +void +Serial::setBytesize (bytesize_t bytesize) +{ + pimpl_->setBytesize (bytesize); +} + +bytesize_t +Serial::getBytesize () const +{ + return pimpl_->getBytesize (); +} + +void +Serial::setParity (parity_t parity) +{ + pimpl_->setParity (parity); +} + +parity_t +Serial::getParity () const +{ + return pimpl_->getParity (); +} + +void +Serial::setStopbits (stopbits_t stopbits) +{ + pimpl_->setStopbits (stopbits); +} + +stopbits_t +Serial::getStopbits () const +{ + return pimpl_->getStopbits (); +} + +void +Serial::setFlowcontrol (flowcontrol_t flowcontrol) +{ + pimpl_->setFlowcontrol (flowcontrol); +} + +flowcontrol_t +Serial::getFlowcontrol () const +{ + return pimpl_->getFlowcontrol (); +} + +void Serial::flush () +{ + ScopedReadLock rlock(this->pimpl_); + ScopedWriteLock wlock(this->pimpl_); + pimpl_->flush (); +} + +void Serial::flushInput () +{ + ScopedReadLock lock(this->pimpl_); + pimpl_->flushInput (); +} + +void Serial::flushOutput () +{ + ScopedWriteLock lock(this->pimpl_); + pimpl_->flushOutput (); +} + +void Serial::sendBreak (int duration) +{ + pimpl_->sendBreak (duration); +} + +void Serial::setBreak (bool level) +{ + pimpl_->setBreak (level); +} + +void Serial::setRTS (bool level) +{ + pimpl_->setRTS (level); +} + +void Serial::setDTR (bool level) +{ + pimpl_->setDTR (level); +} + +bool Serial::waitForChange() +{ + return pimpl_->waitForChange(); +} + +bool Serial::getCTS () +{ + return pimpl_->getCTS (); +} + +bool Serial::getDSR () +{ + return pimpl_->getDSR (); +} + +bool Serial::getRI () +{ + return pimpl_->getRI (); +} + +bool Serial::getCD () +{ + return pimpl_->getCD (); +} diff --git a/third_party/flserial/src/native_libs/src/tinycthread.c b/third_party/flserial/src/native_libs/src/tinycthread.c new file mode 100644 index 00000000..c28f03c4 --- /dev/null +++ b/third_party/flserial/src/native_libs/src/tinycthread.c @@ -0,0 +1,931 @@ +/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- +Copyright (c) 2012 Marcus Geelnard +Copyright (c) 2013-2016 Evan Nemerson + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include +#include "../include/tinycthread.h" + +/* Platform specific includes */ +#if defined(_TTHREAD_POSIX_) + #include + #include + #include + #include + #include +#elif defined(_TTHREAD_WIN32_) + #include + #include +#endif + +/* Standard, good-to-have defines */ +#ifndef NULL + #define NULL (void*)0 +#endif +#ifndef TRUE + #define TRUE 1 +#endif +#ifndef FALSE + #define FALSE 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +int mtx_init(mtx_t *mtx, int type) +{ +#if defined(_TTHREAD_WIN32_) + mtx->mAlreadyLocked = FALSE; + mtx->mRecursive = type & mtx_recursive; + mtx->mTimed = type & mtx_timed; + if (!mtx->mTimed) + { + InitializeCriticalSection(&(mtx->mHandle.cs)); + } + else + { + mtx->mHandle.mut = CreateMutex(NULL, FALSE, NULL); + if (mtx->mHandle.mut == NULL) + { + return thrd_error; + } + } + return thrd_success; +#else + int ret; + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + if (type & mtx_recursive) + { + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + } + ret = pthread_mutex_init(mtx, &attr); + pthread_mutexattr_destroy(&attr); + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +void mtx_destroy(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + if (!mtx->mTimed) + { + DeleteCriticalSection(&(mtx->mHandle.cs)); + } + else + { + CloseHandle(mtx->mHandle.mut); + } +#else + pthread_mutex_destroy(mtx); +#endif +} + +int mtx_lock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + if (!mtx->mTimed) + { + EnterCriticalSection(&(mtx->mHandle.cs)); + } + else + { + switch (WaitForSingleObject(mtx->mHandle.mut, INFINITE)) + { + case WAIT_OBJECT_0: + break; + case WAIT_ABANDONED: + default: + return thrd_error; + } + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + return thrd_success; +#else + return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; +#endif +} + +int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec current_ts; + DWORD timeoutMs; + + if (!mtx->mTimed) + { + return thrd_error; + } + + timespec_get(¤t_ts, TIME_UTC); + + if ((current_ts.tv_sec > ts->tv_sec) || ((current_ts.tv_sec == ts->tv_sec) && (current_ts.tv_nsec >= ts->tv_nsec))) + { + timeoutMs = 0; + } + else + { + timeoutMs = (DWORD)(ts->tv_sec - current_ts.tv_sec) * 1000; + timeoutMs += (ts->tv_nsec - current_ts.tv_nsec) / 1000000; + timeoutMs += 1; + } + + /* TODO: the timeout for WaitForSingleObject doesn't include time + while the computer is asleep. */ + switch (WaitForSingleObject(mtx->mHandle.mut, timeoutMs)) + { + case WAIT_OBJECT_0: + break; + case WAIT_TIMEOUT: + return thrd_timedout; + case WAIT_ABANDONED: + default: + return thrd_error; + } + + if (!mtx->mRecursive) + { + while(mtx->mAlreadyLocked) Sleep(1); /* Simulate deadlock... */ + mtx->mAlreadyLocked = TRUE; + } + + return thrd_success; +#elif defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS >= 200112L) && defined(_POSIX_THREADS) && (_POSIX_THREADS >= 200112L) + switch (pthread_mutex_timedlock(mtx, ts)) { + case 0: + return thrd_success; + case ETIMEDOUT: + return thrd_timedout; + default: + return thrd_error; + } +#else + int rc; + struct timespec cur, dur; + + /* Try to acquire the lock and, if we fail, sleep for 5ms. */ + while ((rc = pthread_mutex_trylock (mtx)) == EBUSY) { + timespec_get(&cur, TIME_UTC); + + if ((cur.tv_sec > ts->tv_sec) || ((cur.tv_sec == ts->tv_sec) && (cur.tv_nsec >= ts->tv_nsec))) + { + break; + } + + dur.tv_sec = ts->tv_sec - cur.tv_sec; + dur.tv_nsec = ts->tv_nsec - cur.tv_nsec; + if (dur.tv_nsec < 0) + { + dur.tv_sec--; + dur.tv_nsec += 1000000000; + } + + if ((dur.tv_sec != 0) || (dur.tv_nsec > 5000000)) + { + dur.tv_sec = 0; + dur.tv_nsec = 5000000; + } + + nanosleep(&dur, NULL); + } + + switch (rc) { + case 0: + return thrd_success; + case ETIMEDOUT: + case EBUSY: + return thrd_timedout; + default: + return thrd_error; + } +#endif +} + +int mtx_trylock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + int ret; + + if (!mtx->mTimed) + { + ret = TryEnterCriticalSection(&(mtx->mHandle.cs)) ? thrd_success : thrd_busy; + } + else + { + ret = (WaitForSingleObject(mtx->mHandle.mut, 0) == WAIT_OBJECT_0) ? thrd_success : thrd_busy; + } + + if ((!mtx->mRecursive) && (ret == thrd_success)) + { + if (mtx->mAlreadyLocked) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + ret = thrd_busy; + } + else + { + mtx->mAlreadyLocked = TRUE; + } + } + return ret; +#else + return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy; +#endif +} + +int mtx_unlock(mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + mtx->mAlreadyLocked = FALSE; + if (!mtx->mTimed) + { + LeaveCriticalSection(&(mtx->mHandle.cs)); + } + else + { + if (!ReleaseMutex(mtx->mHandle.mut)) + { + return thrd_error; + } + } + return thrd_success; +#else + return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;; +#endif +} + +#if defined(_TTHREAD_WIN32_) +#define _CONDITION_EVENT_ONE 0 +#define _CONDITION_EVENT_ALL 1 +#endif + +int cnd_init(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + cond->mWaitersCount = 0; + + /* Init critical section */ + InitializeCriticalSection(&cond->mWaitersCountLock); + + /* Init events */ + cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL) + { + cond->mEvents[_CONDITION_EVENT_ALL] = NULL; + return thrd_error; + } + cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL); + if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + cond->mEvents[_CONDITION_EVENT_ONE] = NULL; + return thrd_error; + } + + return thrd_success; +#else + return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error; +#endif +} + +void cnd_destroy(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); + } + if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL) + { + CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]); + } + DeleteCriticalSection(&cond->mWaitersCountLock); +#else + pthread_cond_destroy(cond); +#endif +} + +int cnd_signal(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + int haveWaiters; + + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0) + { + return thrd_error; + } + } + + return thrd_success; +#else + return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; +#endif +} + +int cnd_broadcast(cnd_t *cond) +{ +#if defined(_TTHREAD_WIN32_) + int haveWaiters; + + /* Are there any waiters? */ + EnterCriticalSection(&cond->mWaitersCountLock); + haveWaiters = (cond->mWaitersCount > 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we have any waiting threads, send them a signal */ + if(haveWaiters) + { + if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + return thrd_error; + } + } + + return thrd_success; +#else + return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout) +{ + DWORD result; + int lastWaiter; + + /* Increment number of waiters */ + EnterCriticalSection(&cond->mWaitersCountLock); + ++ cond->mWaitersCount; + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* Release the mutex while waiting for the condition (will decrease + the number of waiters when done)... */ + mtx_unlock(mtx); + + /* Wait for either event to become signaled due to cnd_signal() or + cnd_broadcast() being called */ + result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout); + if (result == WAIT_TIMEOUT) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_timedout; + } + else if (result == WAIT_FAILED) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + + /* Check if we are the last waiter */ + EnterCriticalSection(&cond->mWaitersCountLock); + -- cond->mWaitersCount; + lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) && + (cond->mWaitersCount == 0); + LeaveCriticalSection(&cond->mWaitersCountLock); + + /* If we are the last waiter to be notified to stop waiting, reset the event */ + if (lastWaiter) + { + if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) + { + /* The mutex is locked again before the function returns, even if an error occurred */ + mtx_lock(mtx); + return thrd_error; + } + } + + /* Re-acquire the mutex */ + mtx_lock(mtx); + + return thrd_success; +} +#endif + +int cnd_wait(cnd_t *cond, mtx_t *mtx) +{ +#if defined(_TTHREAD_WIN32_) + return _cnd_timedwait_win32(cond, mtx, INFINITE); +#else + return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error; +#endif +} + +int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) +{ +#if defined(_TTHREAD_WIN32_) + struct timespec now; + if (timespec_get(&now, TIME_UTC) == TIME_UTC) + { + unsigned long long nowInMilliseconds = now.tv_sec * 1000 + now.tv_nsec / 1000000; + unsigned long long tsInMilliseconds = ts->tv_sec * 1000 + ts->tv_nsec / 1000000; + DWORD delta = (tsInMilliseconds > nowInMilliseconds) ? + (DWORD)(tsInMilliseconds - nowInMilliseconds) : 0; + return _cnd_timedwait_win32(cond, mtx, delta); + } + else + return thrd_error; +#else + int ret; + ret = pthread_cond_timedwait(cond, mtx, ts); + if (ret == ETIMEDOUT) + { + return thrd_timedout; + } + return ret == 0 ? thrd_success : thrd_error; +#endif +} + +#if defined(_TTHREAD_WIN32_) +struct TinyCThreadTSSData { + void* value; + tss_t key; + struct TinyCThreadTSSData* next; +}; + +static tss_dtor_t _tinycthread_tss_dtors[1088] = { NULL, }; + +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_head = NULL; +static _Thread_local struct TinyCThreadTSSData* _tinycthread_tss_tail = NULL; + +static void _tinycthread_tss_cleanup (void); + +static void _tinycthread_tss_cleanup (void) { + struct TinyCThreadTSSData* data; + int iteration; + unsigned int again = 1; + void* value; + + for (iteration = 0 ; iteration < TSS_DTOR_ITERATIONS && again > 0 ; iteration++) + { + again = 0; + for (data = _tinycthread_tss_head ; data != NULL ; data = data->next) + { + if (data->value != NULL) + { + value = data->value; + data->value = NULL; + + if (_tinycthread_tss_dtors[data->key] != NULL) + { + again = 1; + _tinycthread_tss_dtors[data->key](value); + } + } + } + } + + while (_tinycthread_tss_head != NULL) { + data = _tinycthread_tss_head->next; + free (_tinycthread_tss_head); + _tinycthread_tss_head = data; + } + _tinycthread_tss_head = NULL; + _tinycthread_tss_tail = NULL; +} + +static void NTAPI _tinycthread_tss_callback(PVOID h, DWORD dwReason, PVOID pv) +{ + (void)h; + (void)pv; + + if (_tinycthread_tss_head != NULL && (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH)) + { + _tinycthread_tss_cleanup(); + } +} + +#if defined(_MSC_VER) + #ifdef _M_X64 + #pragma const_seg(".CRT$XLB") + #else + #pragma data_seg(".CRT$XLB") + #endif + PIMAGE_TLS_CALLBACK p_thread_callback = _tinycthread_tss_callback; + #ifdef _M_X64 + #pragma data_seg() + #else + #pragma const_seg() + #endif +#else + PIMAGE_TLS_CALLBACK p_thread_callback __attribute__((section(".CRT$XLB"))) = _tinycthread_tss_callback; +#endif + +#endif /* defined(_TTHREAD_WIN32_) */ + +/** Information to pass to the new thread (what to run). */ +typedef struct { + thrd_start_t mFunction; /**< Pointer to the function to be executed. */ + void * mArg; /**< Function argument for the thread function. */ +} _thread_start_info; + +/* Thread wrapper function. */ +#if defined(_TTHREAD_WIN32_) +static DWORD WINAPI _thrd_wrapper_function(LPVOID aArg) +#elif defined(_TTHREAD_POSIX_) +static void * _thrd_wrapper_function(void * aArg) +#endif +{ + thrd_start_t fun; + void *arg; + int res; + + /* Get thread startup information */ + _thread_start_info *ti = (_thread_start_info *) aArg; + fun = ti->mFunction; + arg = ti->mArg; + + /* The thread is responsible for freeing the startup information */ + free((void *)ti); + + /* Call the actual client thread function */ + res = fun(arg); + +#if defined(_TTHREAD_WIN32_) + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + return (DWORD)res; +#else + return (void*)(intptr_t)res; +#endif +} + +int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) +{ + /* Fill out the thread startup information (passed to the thread wrapper, + which will eventually free it) */ + _thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info)); + if (ti == NULL) + { + return thrd_nomem; + } + ti->mFunction = func; + ti->mArg = arg; + + /* Create the thread */ +#if defined(_TTHREAD_WIN32_) + *thr = CreateThread(NULL, 0, _thrd_wrapper_function, (LPVOID) ti, 0, NULL); +#elif defined(_TTHREAD_POSIX_) + if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0) + { + *thr = 0; + } +#endif + + /* Did we fail to create the thread? */ + if(!*thr) + { + free(ti); + return thrd_error; + } + + return thrd_success; +} + +thrd_t thrd_current(void) +{ +#if defined(_TTHREAD_WIN32_) + return GetCurrentThread(); +#else + return pthread_self(); +#endif +} + +int thrd_detach(thrd_t thr) +{ +#if defined(_TTHREAD_WIN32_) + /* https://stackoverflow.com/questions/12744324/how-to-detach-a-thread-on-windows-c#answer-12746081 */ + return CloseHandle(thr) != 0 ? thrd_success : thrd_error; +#else + return pthread_detach(thr) == 0 ? thrd_success : thrd_error; +#endif +} + +int thrd_equal(thrd_t thr0, thrd_t thr1) +{ +#if defined(_TTHREAD_WIN32_) + return GetThreadId(thr0) == GetThreadId(thr1); +#else + return pthread_equal(thr0, thr1); +#endif +} + +void thrd_exit(int res) +{ +#if defined(_TTHREAD_WIN32_) + if (_tinycthread_tss_head != NULL) + { + _tinycthread_tss_cleanup(); + } + + ExitThread((DWORD)res); +#else + pthread_exit((void*)(intptr_t)res); +#endif +} + +int thrd_join(thrd_t thr, int *res) +{ +#if defined(_TTHREAD_WIN32_) + DWORD dwRes; + + if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED) + { + return thrd_error; + } + if (res != NULL) + { + if (GetExitCodeThread(thr, &dwRes) != 0) + { + *res = (int) dwRes; + } + else + { + return thrd_error; + } + } + CloseHandle(thr); +#elif defined(_TTHREAD_POSIX_) + void *pres; + if (pthread_join(thr, &pres) != 0) + { + return thrd_error; + } + if (res != NULL) + { + *res = (int)(intptr_t)pres; + } +#endif + return thrd_success; +} + +int thrd_sleep(const struct timespec *duration, struct timespec *remaining) +{ +#if !defined(_TTHREAD_WIN32_) + int res = nanosleep(duration, remaining); + if (res == 0) { + return 0; + } else if (errno == EINTR) { + return -1; + } else { + return -2; + } +#else + struct timespec start; + DWORD t; + + timespec_get(&start, TIME_UTC); + + t = SleepEx((DWORD)(duration->tv_sec * 1000 + + duration->tv_nsec / 1000000 + + (((duration->tv_nsec % 1000000) == 0) ? 0 : 1)), + TRUE); + + if (t == 0) { + return 0; + } else { + if (remaining != NULL) { + timespec_get(remaining, TIME_UTC); + remaining->tv_sec -= start.tv_sec; + remaining->tv_nsec -= start.tv_nsec; + if (remaining->tv_nsec < 0) + { + remaining->tv_nsec += 1000000000; + remaining->tv_sec -= 1; + } + } + + return (t == WAIT_IO_COMPLETION) ? -1 : -2; + } +#endif +} + +void thrd_yield(void) +{ +#if defined(_TTHREAD_WIN32_) + Sleep(0); +#else + sched_yield(); +#endif +} + +int tss_create(tss_t *key, tss_dtor_t dtor) +{ +#if defined(_TTHREAD_WIN32_) + *key = TlsAlloc(); + if (*key == TLS_OUT_OF_INDEXES) + { + return thrd_error; + } + _tinycthread_tss_dtors[*key] = dtor; +#else + if (pthread_key_create(key, dtor) != 0) + { + return thrd_error; + } +#endif + return thrd_success; +} + +void tss_delete(tss_t key) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*) TlsGetValue (key); + struct TinyCThreadTSSData* prev = NULL; + if (data != NULL) + { + if (data == _tinycthread_tss_head) + { + _tinycthread_tss_head = data->next; + } + else + { + prev = _tinycthread_tss_head; + if (prev != NULL) + { + while (prev->next != data) + { + prev = prev->next; + } + } + } + + if (data == _tinycthread_tss_tail) + { + _tinycthread_tss_tail = prev; + } + + free (data); + } + _tinycthread_tss_dtors[key] = NULL; + TlsFree(key); +#else + pthread_key_delete(key); +#endif +} + +void *tss_get(tss_t key) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + return NULL; + } + return data->value; +#else + return pthread_getspecific(key); +#endif +} + +int tss_set(tss_t key, void *val) +{ +#if defined(_TTHREAD_WIN32_) + struct TinyCThreadTSSData* data = (struct TinyCThreadTSSData*)TlsGetValue(key); + if (data == NULL) + { + data = (struct TinyCThreadTSSData*)malloc(sizeof(struct TinyCThreadTSSData)); + if (data == NULL) + { + return thrd_error; + } + + data->value = NULL; + data->key = key; + data->next = NULL; + + if (_tinycthread_tss_tail != NULL) + { + _tinycthread_tss_tail->next = data; + } + else + { + _tinycthread_tss_tail = data; + } + + if (_tinycthread_tss_head == NULL) + { + _tinycthread_tss_head = data; + } + + if (!TlsSetValue(key, data)) + { + free (data); + return thrd_error; + } + } + data->value = val; +#else + if (pthread_setspecific(key, val) != 0) + { + return thrd_error; + } +#endif + return thrd_success; +} + +#if defined(_TTHREAD_EMULATE_TIMESPEC_GET_) +int _tthread_timespec_get(struct timespec *ts, int base) +{ +#if defined(_TTHREAD_WIN32_) + struct _timeb tb; +#elif !defined(CLOCK_REALTIME) + struct timeval tv; +#endif + + if (base != TIME_UTC) + { + return 0; + } + +#if defined(_TTHREAD_WIN32_) + _ftime_s(&tb); + ts->tv_sec = (time_t)tb.time; + ts->tv_nsec = 1000000L * (long)tb.millitm; +#elif defined(CLOCK_REALTIME) + base = (clock_gettime(CLOCK_REALTIME, ts) == 0) ? base : 0; +#else + gettimeofday(&tv, NULL); + ts->tv_sec = (time_t)tv.tv_sec; + ts->tv_nsec = 1000L * (long)tv.tv_usec; +#endif + + return base; +} +#endif /* _TTHREAD_EMULATE_TIMESPEC_GET_ */ + +#if defined(_TTHREAD_WIN32_) +void call_once(once_flag *flag, void (*func)(void)) +{ + /* The idea here is that we use a spin lock (via the + InterlockedCompareExchange function) to restrict access to the + critical section until we have initialized it, then we use the + critical section to block until the callback has completed + execution. */ + while (flag->status < 3) + { + switch (flag->status) + { + case 0: + if (InterlockedCompareExchange (&(flag->status), 1, 0) == 0) { + InitializeCriticalSection(&(flag->lock)); + EnterCriticalSection(&(flag->lock)); + flag->status = 2; + func(); + flag->status = 3; + LeaveCriticalSection(&(flag->lock)); + return; + } + break; + case 1: + break; + case 2: + EnterCriticalSection(&(flag->lock)); + LeaveCriticalSection(&(flag->lock)); + break; + } + } +} +#endif /* defined(_TTHREAD_WIN32_) */ + +#ifdef __cplusplus +} +#endif diff --git a/third_party/flserial/test/lib/flserial_test.dart b/third_party/flserial/test/lib/flserial_test.dart new file mode 100644 index 00000000..1d4af1c8 --- /dev/null +++ b/third_party/flserial/test/lib/flserial_test.dart @@ -0,0 +1,35 @@ +import 'dart:ffi'; +import 'dart:io'; + +import 'package:flserial/flserial_bindings_generated.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + const String libName = 'flserial'; + + /// The dynamic library in which the symbols for [FlserialBindings] can be found. + final DynamicLibrary dylib = () { + if (Platform.isMacOS || Platform.isIOS) { + return DynamicLibrary.open('$libName.framework/$libName'); + } + if (Platform.isAndroid || Platform.isLinux) { + return DynamicLibrary.open('lib$libName.so'); + } + if (Platform.isWindows) { + return DynamicLibrary.open( + './build/windows/x64/runner/Release/$libName.dll', + ); + } + throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}'); + }(); + + /// The bindings to the native functions in [_dylib]. + final FlserialBindings bindings = FlserialBindings(dylib); + //'/home/runner/work/flserial/flserial/build/linux/x64/release/shared/libflserial.so'); + + test('FLSerial status should be closed', () { + bindings.fl_init(10); + + bindings.fl_free(); + }); +} diff --git a/third_party/flserial/windows/.gitignore b/third_party/flserial/windows/.gitignore new file mode 100644 index 00000000..b3eb2be1 --- /dev/null +++ b/third_party/flserial/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/third_party/flserial/windows/CMakeLists.txt b/third_party/flserial/windows/CMakeLists.txt new file mode 100644 index 00000000..cd8d63b1 --- /dev/null +++ b/third_party/flserial/windows/CMakeLists.txt @@ -0,0 +1,23 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "flserial") +project(${PROJECT_NAME} LANGUAGES CXX) + +# Invoke the build for native code shared with the other target platforms. +# This can be changed to accommodate different builds. +add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared") + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(flserial_bundled_libraries + # Defined in ../src/CMakeLists.txt. + # This can be changed to accommodate different builds. + $ + PARENT_SCOPE +) From caad3dd7039f9f74b1f7c76d006d6262e3017f7c Mon Sep 17 00:00:00 2001 From: edouard Date: Fri, 23 Oct 2026 22:36:11 +0200 Subject: [PATCH 06/67] feat: add per-channel notification modes (all/mentions only/muted) - Add ChannelNotificationMode enum with all, mentionsOnly, muted options - Replace mutedChannels Set with channelNotificationModes Map for per-channel settings - Add mention detection for @username in channel messages - Update channels list and chat UI with notification mode selector - Add localization strings for new notification modes - Automatic migration from old mutedChannels to new system - Update user documentation - Preserve backward compatibility with existing mute/unmute API --- documentation/notifications.md | 20 ++-- lib/connector/meshcore_connector.dart | 32 ++++++- lib/l10n/app_en.arb | 4 + lib/l10n/app_fr.arb | 4 + lib/l10n/app_localizations.dart | 24 +++++ lib/l10n/app_localizations_bg.dart | 12 +++ lib/l10n/app_localizations_de.dart | 12 +++ lib/l10n/app_localizations_en.dart | 12 +++ lib/l10n/app_localizations_es.dart | 12 +++ lib/l10n/app_localizations_fr.dart | 12 +++ lib/l10n/app_localizations_hu.dart | 12 +++ lib/l10n/app_localizations_it.dart | 12 +++ lib/l10n/app_localizations_ja.dart | 12 +++ lib/l10n/app_localizations_ko.dart | 12 +++ lib/l10n/app_localizations_nl.dart | 12 +++ lib/l10n/app_localizations_pl.dart | 12 +++ lib/l10n/app_localizations_pt.dart | 12 +++ lib/l10n/app_localizations_ru.dart | 12 +++ lib/l10n/app_localizations_sk.dart | 12 +++ lib/l10n/app_localizations_sl.dart | 12 +++ lib/l10n/app_localizations_sv.dart | 12 +++ lib/l10n/app_localizations_uk.dart | 12 +++ lib/l10n/app_localizations_zh.dart | 12 +++ lib/models/app_settings.dart | 61 +++++++++--- lib/review_mode/review_mode_storage.dart | 25 +++-- lib/screens/channel_chat_screen.dart | 66 +++++++++++-- lib/screens/channels_screen.dart | 116 ++++++++++++++++++----- lib/services/app_settings_service.dart | 31 ++++-- untranslated.json | 114 +++++++++++++++++++++- 29 files changed, 647 insertions(+), 66 deletions(-) diff --git a/documentation/notifications.md b/documentation/notifications.md index 0f08a095..c84c35d7 100644 --- a/documentation/notifications.md +++ b/documentation/notifications.md @@ -99,15 +99,23 @@ Access via **App Settings → Notifications**: | Channel Message Notifications | On | Channel alerts (greyed out if master is off) | | Advertisement Notifications | On | New node alerts (greyed out if master is off) | -### Per-Channel Muting +### Per-Channel Notification Modes -Mute or unmute a channel from any of these places. Muted channels do not generate OS notifications. +Each channel supports three notification modes: -- The bell icon in the channel chat app bar -- Long-press a channel in the channels list → "Mute channel" / "Unmute channel" -- **Mute channel** on a channel notification (Android) +| Mode | Icon | Behavior | +|---|---|---| +| **All messages** | 🔔 | Receive notifications for every message | +| **Mentions only (@)** | @ | Only notify when someone mentions you with "@yourname" | +| **Muted** | 🔇 | No notifications | -There is no per-contact muting. +Set the mode from: + +- The notifications icon in the channel chat app bar (tap to cycle through modes) +- Long-press a channel in the channels list → **Notification settings** → select mode +- Channel notification actions (Android) + +Mentions are detected by looking for "@" followed by your username at word boundaries. The comparison is case-insensitive. ## Rate Limiting diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 03b03944..783d5061 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -38,7 +38,8 @@ import '../services/image_codec_service.dart'; import '../services/received_image_store.dart'; import '../services/message_retry_service.dart'; import '../services/path_history_service.dart'; -import '../services/app_settings_service.dart'; +import '../services/app_settings_service.dart' + show AppSettingsService, ChannelNotificationMode; import '../services/background_service.dart'; import '../services/timeout_prediction_service.dart'; import '../services/translation_service.dart'; @@ -7353,7 +7354,12 @@ class MeshCoreConnector extends ChangeNotifier { } final label = channelName ?? _channelDisplayName(channelIndex); - if (_appSettingsService!.isChannelMuted(label)) return; + final notificationMode = _appSettingsService!.getChannelNotificationMode( + label, + ); + + // Check if channel is muted + if (notificationMode == ChannelNotificationMode.muted) return; // Reuse translation result only if completed and non-empty; else use original text final resolvedText = @@ -7362,6 +7368,12 @@ class MeshCoreConnector extends ChangeNotifier { translationResult.translatedText.trim().isNotEmpty) ? translationResult.translatedText.trim() : message.text.trim(); + + // If mode is mentionsOnly, check if message mentions us + if (notificationMode == ChannelNotificationMode.mentionsOnly) { + if (!_doesMessageMentionUs(resolvedText)) return; + } + unawaited(() async { await _notificationService.showChannelMessageNotification( channelName: label, @@ -7374,6 +7386,22 @@ class MeshCoreConnector extends ChangeNotifier { }()); } + /// Checks if a message text mentions the current user. + /// Looks for "@username" pattern where username matches our self name. + bool _doesMessageMentionUs(String messageText) { + final selfName = _selfName; + if (selfName == null || selfName.isEmpty) return false; + + // Check for @username at word boundaries (start of message or after whitespace) + // Case-insensitive comparison + final lowerSelfName = selfName.toLowerCase(); + final lowerMessage = messageText.toLowerCase(); + final mentionPattern = RegExp( + r'\b@(' + RegExp.escape(lowerSelfName) + r')\b', + ); + return mentionPattern.hasMatch(lowerMessage); + } + /// Handles RESP_CODE_CHANNEL_DATA_RECV (GRP_DATA). Frames whose dataType is /// not 0xAE1C — or that arrive before an [ImageChunkTransport] is installed — /// are ignored without disturbing any other behaviour. diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index f62a038b..820271a3 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -715,6 +715,10 @@ "channels_addSectionCreate": "Create new", "channels_dragToReorder": "Drag to reorder", "channels_editChannel": "Edit channel", + "channels_notificationSettings": "Notification settings", + "channels_notifyAll": "All messages", + "channels_notifyMentionsOnly": "Mentions only (@)", + "channels_notifyNone": "Muted", "channels_muteChannel": "Mute channel", "channels_unmuteChannel": "Unmute channel", "channels_deleteChannel": "Delete channel", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index f42ce6d6..0c37b31b 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -369,6 +369,10 @@ "channels_public": "Public", "channels_private": "Privé", "channels_editChannel": "Modifier le canal", + "channels_notificationSettings": "Paramètres des notifications", + "channels_notifyAll": "Tous les messages", + "channels_notifyMentionsOnly": "Mentions uniquement (@)", + "channels_notifyNone": "Désactivé", "channels_muteChannel": "Désactiver les notifications du canal", "channels_unmuteChannel": "Réactiver les notifications du canal", "channels_deleteChannel": "Supprimer le canal", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index b5e7efc5..3596db1a 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2620,6 +2620,30 @@ abstract class AppLocalizations { /// **'Edit channel'** String get channels_editChannel; + /// No description provided for @channels_notificationSettings. + /// + /// In en, this message translates to: + /// **'Notification settings'** + String get channels_notificationSettings; + + /// No description provided for @channels_notifyAll. + /// + /// In en, this message translates to: + /// **'All messages'** + String get channels_notifyAll; + + /// No description provided for @channels_notifyMentionsOnly. + /// + /// In en, this message translates to: + /// **'Mentions only (@)'** + String get channels_notifyMentionsOnly; + + /// No description provided for @channels_notifyNone. + /// + /// In en, this message translates to: + /// **'Muted'** + String get channels_notifyNone; + /// No description provided for @channels_muteChannel. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index b9f79a6f..6f260891 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1464,6 +1464,18 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_editChannel => 'Редактирай канал'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Заглуши канала'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index d7893ccf..ddf10b8c 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1458,6 +1458,18 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_editChannel => 'Kanal bearbeiten'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Kanal stummschalten'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0265ac8b..4bf9b610 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1438,6 +1438,18 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_editChannel => 'Edit channel'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Mute channel'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 75c2ab0e..2345ac55 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1457,6 +1457,18 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_editChannel => 'Editar canal'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Silenciar canal'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 85de8bbb..bed96b71 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1462,6 +1462,18 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_editChannel => 'Modifier le canal'; + @override + String get channels_notificationSettings => 'Paramètres des notifications'; + + @override + String get channels_notifyAll => 'Tous les messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions uniquement (@)'; + + @override + String get channels_notifyNone => 'Désactivé'; + @override String get channels_muteChannel => 'Désactiver les notifications du canal'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index ef4b3d9b..9e81cf47 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1453,6 +1453,18 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_editChannel => 'Csatorna szerkesztése'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Csatorna némítása'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 50bb49d9..5fec4210 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1461,6 +1461,18 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_editChannel => 'Modifica canale'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Silenzia canale'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 2aabf56e..57da4dfc 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1385,6 +1385,18 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_editChannel => 'チャンネルを編集'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'チャンネルをミュート'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 98a81ac1..1221475f 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1390,6 +1390,18 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_editChannel => '채널 편집'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => '음소거 채널'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 082f2a18..84075f13 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1449,6 +1449,18 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_editChannel => 'Kanaal bewerken'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Kanaal dempen'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 3db02722..71700e5d 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1475,6 +1475,18 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_editChannel => 'Edytuj kanał'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Wycisz kanał'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 9b89ff31..1b9305f1 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1460,6 +1460,18 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_editChannel => 'Editar canal'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Silenciar canal'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index a1686804..57080935 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1464,6 +1464,18 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_editChannel => 'Изменить канал'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Отключить уведомления канала'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 9cd7cc6d..0491a952 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1452,6 +1452,18 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_editChannel => 'Upraviť kanál'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Stlmiť kanál'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 8602eb0d..9b247612 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1450,6 +1450,18 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_editChannel => 'Uredi kanal'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Utišaj kanal'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 1d87483d..ac13e6aa 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1439,6 +1439,18 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_editChannel => 'Redigera kanal'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Tysta kanal'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index ebd6d5eb..c4aa6b8f 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1455,6 +1455,18 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_editChannel => 'Редагувати канал'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => 'Вимкнути сповіщення каналу'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 703a27fe..825f7954 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1367,6 +1367,18 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_editChannel => '编辑频道'; + @override + String get channels_notificationSettings => 'Notification settings'; + + @override + String get channels_notifyAll => 'All messages'; + + @override + String get channels_notifyMentionsOnly => 'Mentions only (@)'; + + @override + String get channels_notifyNone => 'Muted'; + @override String get channels_muteChannel => '静音频道'; diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index b3632585..612905ec 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -3,6 +3,8 @@ import 'translation_support.dart'; enum UnitSystem { metric, imperial } +enum ChannelNotificationMode { all, mentionsOnly, muted } + extension UnitSystemValue on UnitSystem { String get value { switch (this) { @@ -123,7 +125,7 @@ class AppSettings { final Map batteryChemistryByDeviceId; final Map batteryChemistryByRepeaterId; final UnitSystem unitSystem; - final Set mutedChannels; + final Map channelNotificationModes; final bool mapShowDiscoveryContacts; final bool evictDiscoveredContactsEnabled; final String tcpServerAddress; @@ -196,6 +198,12 @@ class AppSettings { return profile.charMap; } + // Backward compatibility: returns true if channel is muted (mode == muted) + bool isChannelMuted(String channelName) { + return channelNotificationModes[channelName] == + ChannelNotificationMode.muted; + } + AppSettings({ this.clearPathOnMaxRetry = false, this.mapShowRepeaters = true, @@ -238,7 +246,7 @@ class AppSettings { Map? batteryChemistryByDeviceId, Map? batteryChemistryByRepeaterId, this.unitSystem = UnitSystem.metric, - Set? mutedChannels, + Map? channelNotificationModes, this.mapShowDiscoveryContacts = true, this.evictDiscoveredContactsEnabled = true, this.tcpServerAddress = '', @@ -264,7 +272,7 @@ class AppSettings { String? selectedCyr2latProfileId, }) : batteryChemistryByDeviceId = batteryChemistryByDeviceId ?? {}, batteryChemistryByRepeaterId = batteryChemistryByRepeaterId ?? {}, - mutedChannels = mutedChannels ?? {}, + channelNotificationModes = channelNotificationModes ?? {}, imageCodecDownloadedModels = imageCodecDownloadedModels ?? const [], translationDownloadedModels = translationDownloadedModels ?? const [], cyr2latProfiles = @@ -322,7 +330,9 @@ class AppSettings { 'battery_chemistry_by_device_id': batteryChemistryByDeviceId, 'battery_chemistry_by_repeater_id': batteryChemistryByRepeaterId, 'unit_system': unitSystem.value, - 'muted_channels': mutedChannels.toList(), + 'channel_notification_modes': channelNotificationModes.map( + (key, value) => MapEntry(key, value.index), + ), 'map_show_discovery_contacts': mapShowDiscoveryContacts, 'evict_discovered_contacts_enabled': evictDiscoveredContactsEnabled, 'tcp_server_address': tcpServerAddress, @@ -363,6 +373,38 @@ class AppSettings { return UnitSystem.metric; } + Map parseChannelNotificationModes( + Map json, + ) { + // Migration from old muted_channels (Set) to new system + final mutedList = json['muted_channels'] as List?; + final newModes = json['channel_notification_modes'] as Map?; + + final result = {}; + + // Migrate old muted channels + if (mutedList != null) { + for (final channelName in mutedList) { + result[channelName.toString()] = ChannelNotificationMode.muted; + } + } + + // Load new modes (overrides old muted channels if present) + if (newModes != null) { + for (final entry in newModes.entries) { + final channelName = entry.key; + final modeIndex = entry.value as int?; + if (modeIndex != null && + modeIndex >= 0 && + modeIndex < ChannelNotificationMode.values.length) { + result[channelName] = ChannelNotificationMode.values[modeIndex]; + } + } + } + + return result; + } + return AppSettings( clearPathOnMaxRetry: json['clear_path_on_max_retry'] as bool? ?? false, mapShowRepeaters: json['map_show_repeaters'] as bool? ?? true, @@ -425,11 +467,7 @@ class AppSettings { ) ?? {}, unitSystem: parseUnitSystem(json['unit_system']), - mutedChannels: - ((json['muted_channels'] as List?) - ?.map((e) => e.toString()) - .toSet()) ?? - {}, + channelNotificationModes: parseChannelNotificationModes(json), mapShowDiscoveryContacts: json['map_show_discovery_contacts'] as bool? ?? true, evictDiscoveredContactsEnabled: @@ -554,7 +592,7 @@ class AppSettings { Map? batteryChemistryByDeviceId, Map? batteryChemistryByRepeaterId, UnitSystem? unitSystem, - Set? mutedChannels, + Map? channelNotificationModes, bool? mapShowDiscoveryContacts, bool? evictDiscoveredContactsEnabled, String? tcpServerAddress, @@ -639,7 +677,8 @@ class AppSettings { batteryChemistryByRepeaterId: batteryChemistryByRepeaterId ?? this.batteryChemistryByRepeaterId, unitSystem: unitSystem ?? this.unitSystem, - mutedChannels: mutedChannels ?? this.mutedChannels, + channelNotificationModes: + channelNotificationModes ?? this.channelNotificationModes, mapShowDiscoveryContacts: mapShowDiscoveryContacts ?? this.mapShowDiscoveryContacts, evictDiscoveredContactsEnabled: diff --git a/lib/review_mode/review_mode_storage.dart b/lib/review_mode/review_mode_storage.dart index 2ccfc569..e0a02bb4 100644 --- a/lib/review_mode/review_mode_storage.dart +++ b/lib/review_mode/review_mode_storage.dart @@ -1,4 +1,5 @@ -import '../services/app_settings_service.dart'; +import '../services/app_settings_service.dart' + show AppSettingsService, ChannelNotificationMode; import '../services/storage_service.dart'; import '../services/timeout_prediction_service.dart'; import '../storage/legacy_key_migration.dart'; @@ -48,10 +49,13 @@ Future beginReviewModeSession(AppSettingsService? settings) async { } // An earlier interrupted session's record holds the real pre-review state. if (settings != null && !prefs.containsKey(_savedMutedChannelsKey)) { - await prefs.setStringList( - _savedMutedChannelsKey, - settings.settings.mutedChannels.toList(), - ); + // Save all channel notification modes + final channelModes = settings.settings.channelNotificationModes; + final mutedChannels = channelModes.entries + .where((e) => e.value == ChannelNotificationMode.muted) + .map((e) => e.key) + .toList(); + await prefs.setStringList(_savedMutedChannelsKey, mutedChannels); } } @@ -75,8 +79,17 @@ Future endReviewModeSession(AppSettingsService? settings) async { } final savedMutes = prefs.getStringList(_savedMutedChannelsKey); if (savedMutes == null || settings == null) return; + final updatedModes = Map.from( + settings.settings.channelNotificationModes, + ); + updatedModes.removeWhere( + (key, value) => value == ChannelNotificationMode.muted, + ); + for (final channelName in savedMutes) { + updatedModes[channelName] = ChannelNotificationMode.muted; + } await settings.updateSettings( - settings.settings.copyWith(mutedChannels: savedMutes.toSet()), + settings.settings.copyWith(channelNotificationModes: updatedModes), ); await prefs.remove(_savedMutedChannelsKey); } diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 358ea298..a71e7cce 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -26,7 +26,8 @@ import '../l10n/l10n.dart'; import '../models/channel.dart'; import '../models/channel_message.dart'; import '../models/image_codec_support.dart' show aeicRatePointForUi; -import '../services/app_settings_service.dart'; +import '../services/app_settings_service.dart' + show AppSettingsService, ChannelNotificationMode; import '../services/chat_text_scale_service.dart'; import '../services/image_chunk_transport.dart'; import '../services/image_codec_service.dart'; @@ -403,19 +404,64 @@ class _ChannelChatScreenState extends State { Consumer( builder: (context, settings, _) { final muteKey = widget.channel.muteKey; - final muted = settings.isChannelMuted(muteKey); - return IconButton( - tooltip: muted - ? context.l10n.channels_unmuteChannel - : context.l10n.channels_muteChannel, + final notificationMode = settings.getChannelNotificationMode( + muteKey, + ); + return PopupMenuButton( + tooltip: context.l10n.channels_notificationSettings, icon: Icon( - muted + notificationMode == ChannelNotificationMode.muted ? Icons.notifications_off_outlined + : notificationMode == ChannelNotificationMode.mentionsOnly + ? Icons.alternate_email : Icons.notifications_outlined, ), - onPressed: () => muted - ? settings.unmuteChannel(muteKey) - : settings.muteChannel(muteKey), + onSelected: (mode) { + settings.setChannelNotificationMode(muteKey, mode); + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: ChannelNotificationMode.all, + child: Row( + children: [ + Icon( + Icons.notifications_active, + color: notificationMode == ChannelNotificationMode.all + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Text(context.l10n.channels_notifyAll), + ], + ), + ), + PopupMenuItem( + value: ChannelNotificationMode.mentionsOnly, + child: Row( + children: [ + const Icon(Icons.alternate_email), + const SizedBox(width: 8), + Text(context.l10n.channels_notifyMentionsOnly), + ], + ), + ), + PopupMenuItem( + value: ChannelNotificationMode.muted, + child: Row( + children: [ + Icon( + Icons.notifications_off, + color: + notificationMode == ChannelNotificationMode.muted + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Text(context.l10n.channels_notifyNone), + ], + ), + ), + ], ); }, ), diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index f0c0bb35..8e03112e 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -10,7 +10,8 @@ import 'package:uuid/uuid.dart'; import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; -import '../services/app_settings_service.dart'; +import '../services/app_settings_service.dart' + show AppSettingsService, ChannelNotificationMode; import '../services/ui_view_state_service.dart'; import '../models/channel.dart'; import '../models/community.dart'; @@ -372,9 +373,9 @@ class _ChannelsScreenState extends State int listIndex = 0, }) { final unreadCount = connector.getUnreadCountForChannel(channel); - final isMuted = context.watch().isChannelMuted( - channel.muteKey, - ); + final notificationMode = context + .watch() + .getChannelNotificationMode(channel.muteKey); final scheme = Theme.of(context).colorScheme; // Determine icon and colors based on channel type @@ -580,9 +581,11 @@ class _ChannelsScreenState extends State Row( mainAxisSize: MainAxisSize.min, children: [ - if (isMuted) ...[ + if (notificationMode != ChannelNotificationMode.all) ...[ Icon( - Icons.notifications_off, + notificationMode == ChannelNotificationMode.muted + ? Icons.notifications_off + : Icons.alternate_email, size: 18, color: scheme.onSurfaceVariant, ), @@ -625,8 +628,6 @@ class _ChannelsScreenState extends State Channel channel, ) { final parentContext = context; - final settingsService = context.read(); - final isMuted = settingsService.isChannelMuted(channel.muteKey); showMeshSheet( parentContext, @@ -645,24 +646,14 @@ class _ChannelsScreenState extends State } }, ), + // Notification mode selection ListTile( - leading: Icon( - isMuted - ? Icons.notifications_outlined - : Icons.notifications_off_outlined, - ), - title: Text( - isMuted - ? sheetContext.l10n.channels_unmuteChannel - : sheetContext.l10n.channels_muteChannel, - ), - onTap: () async { + leading: const Icon(Icons.notifications_outlined), + title: Text(sheetContext.l10n.channels_notificationSettings), + trailing: const Icon(Icons.chevron_right), + onTap: () { Navigator.pop(sheetContext); - if (isMuted) { - await settingsService.unmuteChannel(channel.muteKey); - } else { - await settingsService.muteChannel(channel.muteKey); - } + _showNotificationModeDialog(sheetContext, connector, channel); }, ), ListTile( @@ -690,6 +681,83 @@ class _ChannelsScreenState extends State ); } + void _showNotificationModeDialog( + BuildContext context, + MeshCoreConnector connector, + Channel channel, + ) { + final settingsService = context.read(); + final currentMode = settingsService.getChannelNotificationMode( + channel.muteKey, + ); + + showMeshSheet( + context, + builder: (sheetContext) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // All notifications + ListTile( + leading: Icon( + Icons.notifications_active, + color: currentMode == ChannelNotificationMode.all + ? Theme.of(sheetContext).colorScheme.primary + : Theme.of(sheetContext).colorScheme.onSurfaceVariant, + ), + title: Text(sheetContext.l10n.channels_notifyAll), + trailing: currentMode == ChannelNotificationMode.all + ? const Icon(Icons.check) + : null, + onTap: () async { + Navigator.pop(sheetContext); + await settingsService.setChannelNotificationMode( + channel.muteKey, + ChannelNotificationMode.all, + ); + }, + ), + // Mentions only + ListTile( + leading: const Icon(Icons.alternate_email), + title: Text(sheetContext.l10n.channels_notifyMentionsOnly), + trailing: currentMode == ChannelNotificationMode.mentionsOnly + ? const Icon(Icons.check) + : null, + onTap: () async { + Navigator.pop(sheetContext); + await settingsService.setChannelNotificationMode( + channel.muteKey, + ChannelNotificationMode.mentionsOnly, + ); + }, + ), + // Muted + ListTile( + leading: Icon( + Icons.notifications_off, + color: currentMode == ChannelNotificationMode.muted + ? Theme.of(sheetContext).colorScheme.primary + : Theme.of(sheetContext).colorScheme.onSurfaceVariant, + ), + title: Text(sheetContext.l10n.channels_notifyNone), + trailing: currentMode == ChannelNotificationMode.muted + ? const Icon(Icons.check) + : null, + onTap: () async { + Navigator.pop(sheetContext); + await settingsService.setChannelNotificationMode( + channel.muteKey, + ChannelNotificationMode.muted, + ); + }, + ), + ], + ), + ), + ); + } + void _handleQuickSwitch(int index, BuildContext context) { if (index == 1) return; switch (index) { diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 3cf9e7d9..5bddabae 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -3,6 +3,8 @@ import 'package:flutter/foundation.dart'; import '../models/app_settings.dart'; import '../models/image_codec_support.dart'; import '../models/translation_support.dart'; + +export '../models/app_settings.dart' show ChannelNotificationMode; import '../storage/prefs_manager.dart'; import '../utils/app_logger.dart'; import '../helpers/cyr2lat.dart'; @@ -286,19 +288,36 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(unitSystem: value)); } + // Backward compatibility: delegates to AppSettings.isChannelMuted bool isChannelMuted(String channelName) { - return _settings.mutedChannels.contains(channelName); + return _settings.isChannelMuted(channelName); + } + + ChannelNotificationMode getChannelNotificationMode(String channelName) { + return _settings.channelNotificationModes[channelName] ?? + ChannelNotificationMode.all; + } + + Future setChannelNotificationMode( + String channelName, + ChannelNotificationMode mode, + ) async { + final updated = Map.from( + _settings.channelNotificationModes, + ); + updated[channelName] = mode; + await updateSettings(_settings.copyWith(channelNotificationModes: updated)); } Future muteChannel(String channelName) async { - final updated = Set.from(_settings.mutedChannels)..add(channelName); - await updateSettings(_settings.copyWith(mutedChannels: updated)); + await setChannelNotificationMode( + channelName, + ChannelNotificationMode.muted, + ); } Future unmuteChannel(String channelName) async { - final updated = Set.from(_settings.mutedChannels) - ..remove(channelName); - await updateSettings(_settings.copyWith(mutedChannels: updated)); + await setChannelNotificationMode(channelName, ChannelNotificationMode.all); } Future setTcpServerAddress(String value) async { diff --git a/untranslated.json b/untranslated.json index 9e26dfee..a2f434b5 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,113 @@ -{} \ No newline at end of file +{ + "bg": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "de": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "es": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "hu": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "it": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "ja": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "ko": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "nl": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "pl": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "pt": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "ru": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "sk": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "sl": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "sv": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "uk": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ], + + "zh": [ + "channels_notificationSettings", + "channels_notifyAll", + "channels_notifyMentionsOnly", + "channels_notifyNone" + ] +} From 09e9208108563d843404dc22053b4cd4963ebaf1 Mon Sep 17 00:00:00 2001 From: edouard Date: Fri, 23 Oct 2026 23:31:11 +0200 Subject: [PATCH 07/67] Update notification mode strings with verified translations - Add channels_notifyAll, channels_notifyMentionsOnly, channels_notifyNone to all 18 language ARB files - Add channels_notificationSettings to all ARB files for consistency (was missing in 16 languages) - Remove redundant "(@)" suffix from mentions only mode - All translations verified for accuracy - Special fix: Slovak "Iba spomienky" -> "Iba zmienky" (mentions, not memories) - Update all localization Dart files via flutter gen-l10n - Update documentation table with proper icons - Update untranslated.json --- documentation/notifications.md | 6 +- lib/connector/meshcore_connector.dart | 51 ++++++++---- lib/l10n/app_bg.arb | 4 + lib/l10n/app_de.arb | 4 + lib/l10n/app_en.arb | 2 +- lib/l10n/app_es.arb | 4 + lib/l10n/app_fr.arb | 2 +- lib/l10n/app_hu.arb | 4 + lib/l10n/app_it.arb | 4 + lib/l10n/app_ja.arb | 4 + lib/l10n/app_ko.arb | 4 + lib/l10n/app_localizations.dart | 2 +- lib/l10n/app_localizations_bg.dart | 8 +- lib/l10n/app_localizations_de.dart | 8 +- lib/l10n/app_localizations_en.dart | 2 +- lib/l10n/app_localizations_es.dart | 8 +- lib/l10n/app_localizations_fr.dart | 2 +- lib/l10n/app_localizations_hu.dart | 8 +- lib/l10n/app_localizations_it.dart | 8 +- lib/l10n/app_localizations_ja.dart | 8 +- lib/l10n/app_localizations_ko.dart | 8 +- lib/l10n/app_localizations_nl.dart | 8 +- lib/l10n/app_localizations_pl.dart | 8 +- lib/l10n/app_localizations_pt.dart | 8 +- lib/l10n/app_localizations_ru.dart | 8 +- lib/l10n/app_localizations_sk.dart | 8 +- lib/l10n/app_localizations_sl.dart | 8 +- lib/l10n/app_localizations_sv.dart | 8 +- lib/l10n/app_localizations_uk.dart | 8 +- lib/l10n/app_localizations_zh.dart | 8 +- lib/l10n/app_nl.arb | 4 + lib/l10n/app_pl.arb | 4 + lib/l10n/app_pt.arb | 4 + lib/l10n/app_ru.arb | 4 + lib/l10n/app_sk.arb | 4 + lib/l10n/app_sl.arb | 4 + lib/l10n/app_sv.arb | 4 + lib/l10n/app_uk.arb | 4 + lib/l10n/app_zh.arb | 4 + lib/screens/channel_chat_screen.dart | 4 +- lib/screens/channels_screen.dart | 4 +- untranslated.json | 114 +------------------------- 42 files changed, 178 insertions(+), 203 deletions(-) diff --git a/documentation/notifications.md b/documentation/notifications.md index c84c35d7..d6f3f903 100644 --- a/documentation/notifications.md +++ b/documentation/notifications.md @@ -106,8 +106,8 @@ Each channel supports three notification modes: | Mode | Icon | Behavior | |---|---|---| | **All messages** | 🔔 | Receive notifications for every message | -| **Mentions only (@)** | @ | Only notify when someone mentions you with "@yourname" | -| **Muted** | 🔇 | No notifications | +| **Mentions only** | 🔔 | Only notify when someone mentions you with "@yourname" or replies to your messages | +| **Muted** | 🔕 | No notifications | Set the mode from: @@ -115,7 +115,7 @@ Set the mode from: - Long-press a channel in the channels list → **Notification settings** → select mode - Channel notification actions (Android) -Mentions are detected by looking for "@" followed by your username at word boundaries. The comparison is case-insensitive. +Mentions are detected by looking for "@" followed by your username at word boundaries (case-insensitive), or when someone replies to one of your messages. Reply detection checks if the message is a direct reply to a message you sent. ## Rate Limiting diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 783d5061..7e96a3a3 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -7369,9 +7369,9 @@ class MeshCoreConnector extends ChangeNotifier { ? translationResult.translatedText.trim() : message.text.trim(); - // If mode is mentionsOnly, check if message mentions us + // If mode is mentionsOnly, check if message mentions us or is a reply to us if (notificationMode == ChannelNotificationMode.mentionsOnly) { - if (!_doesMessageMentionUs(resolvedText)) return; + if (!_doesMessageMentionUs(resolvedText, message)) return; } unawaited(() async { @@ -7386,20 +7386,43 @@ class MeshCoreConnector extends ChangeNotifier { }()); } - /// Checks if a message text mentions the current user. - /// Looks for "@username" pattern where username matches our self name. - bool _doesMessageMentionUs(String messageText) { + /// Checks if a message mentions the current user. + /// Detects: @username, @1234 (last 4 hex chars of node ID), or replies to our messages. + bool _doesMessageMentionUs(String messageText, ChannelMessage message) { final selfName = _selfName; - if (selfName == null || selfName.isEmpty) return false; - + final selfPubKeyHex = selfPublicKeyHex; + + // Check if this is a reply to our message + if (message.replyToSenderName != null) { + final lowerSelfName = selfName?.toLowerCase(); + final lowerReplyToSender = message.replyToSenderName!.toLowerCase(); + if (lowerSelfName != null && lowerSelfName.isNotEmpty && + lowerReplyToSender == lowerSelfName) { + return true; + } + } + // Check for @username at word boundaries (start of message or after whitespace) - // Case-insensitive comparison - final lowerSelfName = selfName.toLowerCase(); - final lowerMessage = messageText.toLowerCase(); - final mentionPattern = RegExp( - r'\b@(' + RegExp.escape(lowerSelfName) + r')\b', - ); - return mentionPattern.hasMatch(lowerMessage); + if (selfName != null && selfName.isNotEmpty) { + final lowerSelfName = selfName.toLowerCase(); + final lowerMessage = messageText.toLowerCase(); + final mentionPattern = RegExp( + r'\b@(' + RegExp.escape(lowerSelfName) + r')\b', + ); + if (mentionPattern.hasMatch(lowerMessage)) return true; + } + + // Check for @1234 pattern (last 4 hex chars of public key) + if (selfPubKeyHex.length >= 4) { + final last4Hex = selfPubKeyHex.substring(selfPubKeyHex.length - 4); + final lowerMessage = messageText.toLowerCase(); + final hexMentionPattern = RegExp( + r'\b@(' + RegExp.escape(last4Hex.toLowerCase()) + r')\b', + ); + if (hexMentionPattern.hasMatch(lowerMessage)) return true; + } + + return false; } /// Handles RESP_CODE_CHANNEL_DATA_RECV (GRP_DATA). Frames whose dataType is diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 2c4dde5b..9eaa12e8 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -359,6 +359,10 @@ "channels_public": "Публично", "channels_private": "Частен", "channels_editChannel": "Редактирай канал", + "channels_notificationSettings": "Настройки за известия", + "channels_notifyAll": "Всички съобщения", + "channels_notifyMentionsOnly": "Само споменавания", + "channels_notifyNone": "Заглушено", "channels_muteChannel": "Заглуши канала", "channels_unmuteChannel": "Включи известията на канала", "channels_deleteChannel": "Изтрий канала", diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 1d12ad59..01e6b3b9 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -369,6 +369,10 @@ "channels_public": "Öffentlich", "channels_private": "Privat", "channels_editChannel": "Kanal bearbeiten", + "channels_notificationSettings": "Benachrichtigungseinstellungen", + "channels_notifyAll": "Alle Nachrichten", + "channels_notifyMentionsOnly": "Nur Erwähnungen", + "channels_notifyNone": "Stummgeschaltet", "channels_muteChannel": "Kanal stummschalten", "channels_unmuteChannel": "Kanal Stummschaltung aufheben", "channels_deleteChannel": "Kanal löschen", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 820271a3..2b28c76d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -717,7 +717,7 @@ "channels_editChannel": "Edit channel", "channels_notificationSettings": "Notification settings", "channels_notifyAll": "All messages", - "channels_notifyMentionsOnly": "Mentions only (@)", + "channels_notifyMentionsOnly": "Mentions only", "channels_notifyNone": "Muted", "channels_muteChannel": "Mute channel", "channels_unmuteChannel": "Unmute channel", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 9023e268..7db9569c 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -369,6 +369,10 @@ "channels_public": "Público", "channels_private": "Privado", "channels_editChannel": "Editar canal", + "channels_notificationSettings": "Configuración de notificaciones", + "channels_notifyAll": "Todos los mensajes", + "channels_notifyMentionsOnly": "Solo menciones", + "channels_notifyNone": "Silenciado", "channels_muteChannel": "Silenciar canal", "channels_unmuteChannel": "Activar canal", "channels_deleteChannel": "Eliminar canal", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 0c37b31b..c297db56 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -371,7 +371,7 @@ "channels_editChannel": "Modifier le canal", "channels_notificationSettings": "Paramètres des notifications", "channels_notifyAll": "Tous les messages", - "channels_notifyMentionsOnly": "Mentions uniquement (@)", + "channels_notifyMentionsOnly": "Mentions uniquement", "channels_notifyNone": "Désactivé", "channels_muteChannel": "Désactiver les notifications du canal", "channels_unmuteChannel": "Réactiver les notifications du canal", diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 9f0bfee3..3e26d1b1 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -511,6 +511,10 @@ "channels_public": "Nyilvános", "channels_private": "Magán", "channels_editChannel": "Csatorna szerkesztése", + "channels_notificationSettings": "Értesítési beállítások", + "channels_notifyAll": "Összes üzenet", + "channels_notifyMentionsOnly": "Csak említések", + "channels_notifyNone": "Némít", "channels_muteChannel": "Csatorna némítása", "channels_unmuteChannel": "Csatorna némításának feloldása", "channels_deleteChannel": "Csatorna törlése", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 89a86aad..dcc3e998 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -414,6 +414,10 @@ "channels_public": "Pubblico", "channels_private": "Privato", "channels_editChannel": "Modifica canale", + "channels_notificationSettings": "Impostazioni notifiche", + "channels_notifyAll": "Tutti i messaggi", + "channels_notifyMentionsOnly": "Solo menzioni", + "channels_notifyNone": "Silenziato", "channels_muteChannel": "Silenzia canale", "channels_unmuteChannel": "Attiva notifiche canale", "channels_deleteChannel": "Elimina canale", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 468d0d16..117555c3 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -517,6 +517,10 @@ "channels_public": "公開", "channels_private": "非公開", "channels_editChannel": "チャンネルを編集", + "channels_notificationSettings": "通知設定", + "channels_notifyAll": "すべてのメッセージ", + "channels_notifyMentionsOnly": "メンションのみ", + "channels_notifyNone": "ミュート", "channels_muteChannel": "チャンネルをミュート", "channels_unmuteChannel": "チャンネルのミュートを解除", "channels_deleteChannel": "チャンネルを削除", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 38869f9a..62ab3ad4 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -511,6 +511,10 @@ "channels_public": "대중의", "channels_private": "사립", "channels_editChannel": "채널 편집", + "channels_notificationSettings": "알림 설정", + "channels_notifyAll": "모든 메시지", + "channels_notifyMentionsOnly": "언급만", + "channels_notifyNone": "음소거", "channels_muteChannel": "음소거 채널", "channels_unmuteChannel": "채널 음소거 해제", "channels_deleteChannel": "채널 삭제", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 3596db1a..b4168cc6 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2635,7 +2635,7 @@ abstract class AppLocalizations { /// No description provided for @channels_notifyMentionsOnly. /// /// In en, this message translates to: - /// **'Mentions only (@)'** + /// **'Mentions only'** String get channels_notifyMentionsOnly; /// No description provided for @channels_notifyNone. diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 6f260891..e4fea0e2 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1465,16 +1465,16 @@ class AppLocalizationsBg extends AppLocalizations { String get channels_editChannel => 'Редактирай канал'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Настройки за известия'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Всички съобщения'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Само споменавания'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Заглушено'; @override String get channels_muteChannel => 'Заглуши канала'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index ddf10b8c..9d7a3f43 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1459,16 +1459,16 @@ class AppLocalizationsDe extends AppLocalizations { String get channels_editChannel => 'Kanal bearbeiten'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Benachrichtigungseinstellungen'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Alle Nachrichten'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Nur Erwähnungen'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Stummgeschaltet'; @override String get channels_muteChannel => 'Kanal stummschalten'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 4bf9b610..fb20008b 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1445,7 +1445,7 @@ class AppLocalizationsEn extends AppLocalizations { String get channels_notifyAll => 'All messages'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Mentions only'; @override String get channels_notifyNone => 'Muted'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 2345ac55..e1ad4fa2 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1458,16 +1458,16 @@ class AppLocalizationsEs extends AppLocalizations { String get channels_editChannel => 'Editar canal'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Configuración de notificaciones'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Todos los mensajes'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Solo menciones'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Silenciado'; @override String get channels_muteChannel => 'Silenciar canal'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index bed96b71..f3318265 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1469,7 +1469,7 @@ class AppLocalizationsFr extends AppLocalizations { String get channels_notifyAll => 'Tous les messages'; @override - String get channels_notifyMentionsOnly => 'Mentions uniquement (@)'; + String get channels_notifyMentionsOnly => 'Mentions uniquement'; @override String get channels_notifyNone => 'Désactivé'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 9e81cf47..21d40309 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1454,16 +1454,16 @@ class AppLocalizationsHu extends AppLocalizations { String get channels_editChannel => 'Csatorna szerkesztése'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Értesítési beállítások'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Összes üzenet'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Csak említések'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Némít'; @override String get channels_muteChannel => 'Csatorna némítása'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 5fec4210..fdc44f4a 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1462,16 +1462,16 @@ class AppLocalizationsIt extends AppLocalizations { String get channels_editChannel => 'Modifica canale'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Impostazioni notifiche'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Tutti i messaggi'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Solo menzioni'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Silenziato'; @override String get channels_muteChannel => 'Silenzia canale'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 57da4dfc..80aa0c8d 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1386,16 +1386,16 @@ class AppLocalizationsJa extends AppLocalizations { String get channels_editChannel => 'チャンネルを編集'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => '通知設定'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'すべてのメッセージ'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'メンションのみ'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'ミュート'; @override String get channels_muteChannel => 'チャンネルをミュート'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 1221475f..90181a0c 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1391,16 +1391,16 @@ class AppLocalizationsKo extends AppLocalizations { String get channels_editChannel => '채널 편집'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => '알림 설정'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => '모든 메시지'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => '언급만'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => '음소거'; @override String get channels_muteChannel => '음소거 채널'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 84075f13..b4c40d64 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1450,16 +1450,16 @@ class AppLocalizationsNl extends AppLocalizations { String get channels_editChannel => 'Kanaal bewerken'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Meldingsinstellingen'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Alle berichten'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Alleen vermeldingen'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Gedempt'; @override String get channels_muteChannel => 'Kanaal dempen'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 71700e5d..10fe2d7f 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1476,16 +1476,16 @@ class AppLocalizationsPl extends AppLocalizations { String get channels_editChannel => 'Edytuj kanał'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Ustawienia powiadomień'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Wszystkie wiadomości'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Tylko wzmianki'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Wyciszone'; @override String get channels_muteChannel => 'Wycisz kanał'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 1b9305f1..2a9ceae6 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1461,16 +1461,16 @@ class AppLocalizationsPt extends AppLocalizations { String get channels_editChannel => 'Editar canal'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Configurações de notificação'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Todas as mensagens'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Apenas menções'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Silenciado'; @override String get channels_muteChannel => 'Silenciar canal'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 57080935..f8eb322b 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1465,16 +1465,16 @@ class AppLocalizationsRu extends AppLocalizations { String get channels_editChannel => 'Изменить канал'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Настройки уведомлений'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Все сообщения'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Только упоминания'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Без звука'; @override String get channels_muteChannel => 'Отключить уведомления канала'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0491a952..46b074bd 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1453,16 +1453,16 @@ class AppLocalizationsSk extends AppLocalizations { String get channels_editChannel => 'Upraviť kanál'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Nastavenia notifikácií'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Všetky správy'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Iba zmienky'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Stíšené'; @override String get channels_muteChannel => 'Stlmiť kanál'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 9b247612..696b59f9 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1451,16 +1451,16 @@ class AppLocalizationsSl extends AppLocalizations { String get channels_editChannel => 'Uredi kanal'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Nastavitve obvestil'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Vsa sporočila'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Samo omembe'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Utišano'; @override String get channels_muteChannel => 'Utišaj kanal'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index ac13e6aa..1593d3de 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1440,16 +1440,16 @@ class AppLocalizationsSv extends AppLocalizations { String get channels_editChannel => 'Redigera kanal'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Aviseringsinställningar'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Alla meddelanden'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Endast omnämnanden'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Tyst'; @override String get channels_muteChannel => 'Tysta kanal'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index c4aa6b8f..369dda90 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1456,16 +1456,16 @@ class AppLocalizationsUk extends AppLocalizations { String get channels_editChannel => 'Редагувати канал'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => 'Налаштування сповіщень'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => 'Усі повідомлення'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => 'Лише згадки'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => 'Вимкнено'; @override String get channels_muteChannel => 'Вимкнути сповіщення каналу'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 825f7954..ac397a39 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1368,16 +1368,16 @@ class AppLocalizationsZh extends AppLocalizations { String get channels_editChannel => '编辑频道'; @override - String get channels_notificationSettings => 'Notification settings'; + String get channels_notificationSettings => '通知设置'; @override - String get channels_notifyAll => 'All messages'; + String get channels_notifyAll => '所有消息'; @override - String get channels_notifyMentionsOnly => 'Mentions only (@)'; + String get channels_notifyMentionsOnly => '仅提及'; @override - String get channels_notifyNone => 'Muted'; + String get channels_notifyNone => '静音'; @override String get channels_muteChannel => '静音频道'; diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 4f7d8d61..3cbd275f 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -375,6 +375,10 @@ "channels_addSectionCreate": "Nieuw aanmaken", "channels_dragToReorder": "Sleep om te herschikken", "channels_editChannel": "Kanaal bewerken", + "channels_notificationSettings": "Meldingsinstellingen", + "channels_notifyAll": "Alle berichten", + "channels_notifyMentionsOnly": "Alleen vermeldingen", + "channels_notifyNone": "Gedempt", "channels_muteChannel": "Kanaal dempen", "channels_unmuteChannel": "Kanaal dempen opheffen", "channels_deleteChannel": "Kanaal verwijderen", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index 77ca42b7..eb429796 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -369,6 +369,10 @@ "channels_public": "Publiczny", "channels_private": "Prywatny", "channels_editChannel": "Edytuj kanał", + "channels_notificationSettings": "Ustawienia powiadomień", + "channels_notifyAll": "Wszystkie wiadomości", + "channels_notifyMentionsOnly": "Tylko wzmianki", + "channels_notifyNone": "Wyciszone", "channels_muteChannel": "Wycisz kanał", "channels_unmuteChannel": "Wyłącz wyciszenie kanału", "channels_deleteChannel": "Usuń kanał", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index d211e265..997bd295 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -359,6 +359,10 @@ "channels_public": "Público", "channels_private": "Privado", "channels_editChannel": "Editar canal", + "channels_notificationSettings": "Configurações de notificação", + "channels_notifyAll": "Todas as mensagens", + "channels_notifyMentionsOnly": "Apenas menções", + "channels_notifyNone": "Silenciado", "channels_muteChannel": "Silenciar canal", "channels_unmuteChannel": "Ativar canal", "channels_deleteChannel": "Excluir canal", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index f2d3baeb..d8b9ff79 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -251,6 +251,10 @@ "channels_public": "Публичный", "channels_private": "Приватный", "channels_editChannel": "Изменить канал", + "channels_notificationSettings": "Настройки уведомлений", + "channels_notifyAll": "Все сообщения", + "channels_notifyMentionsOnly": "Только упоминания", + "channels_notifyNone": "Без звука", "channels_muteChannel": "Отключить уведомления канала", "channels_unmuteChannel": "Включить уведомления канала", "channels_deleteChannel": "Удалить канал", diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index d2525a42..58454b8b 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -359,6 +359,10 @@ "channels_public": "Veľké verejné", "channels_private": "Osobné", "channels_editChannel": "Upraviť kanál", + "channels_notificationSettings": "Nastavenia notifikácií", + "channels_notifyAll": "Všetky správy", + "channels_notifyMentionsOnly": "Iba zmienky", + "channels_notifyNone": "Stíšené", "channels_muteChannel": "Stlmiť kanál", "channels_unmuteChannel": "Zrušiť stlmenie kanála", "channels_deleteChannel": "Odstrániť kanál", diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 5bc612a0..2e9fcdc0 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -359,6 +359,10 @@ "channels_public": "Javni", "channels_private": "Zasebni", "channels_editChannel": "Uredi kanal", + "channels_notificationSettings": "Nastavitve obvestil", + "channels_notifyAll": "Vsa sporočila", + "channels_notifyMentionsOnly": "Samo omembe", + "channels_notifyNone": "Utišano", "channels_muteChannel": "Utišaj kanal", "channels_unmuteChannel": "Vklopi obvestila kanala", "channels_deleteChannel": "Pošlji kanal", diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 1857b8a5..a138085a 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -359,6 +359,10 @@ "channels_public": "Publik", "channels_private": "Privat", "channels_editChannel": "Redigera kanal", + "channels_notificationSettings": "Aviseringsinställningar", + "channels_notifyAll": "Alla meddelanden", + "channels_notifyMentionsOnly": "Endast omnämnanden", + "channels_notifyNone": "Tyst", "channels_muteChannel": "Tysta kanal", "channels_unmuteChannel": "Slå på ljud för kanal", "channels_deleteChannel": "Ta bort kanal", diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index d8d3b7db..d7cee3fc 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -362,6 +362,10 @@ "channels_via": "через {path}", "channels_private": "Приватний", "channels_editChannel": "Редагувати канал", + "channels_notificationSettings": "Налаштування сповіщень", + "channels_notifyAll": "Усі повідомлення", + "channels_notifyMentionsOnly": "Лише згадки", + "channels_notifyNone": "Вимкнено", "channels_muteChannel": "Вимкнути сповіщення каналу", "channels_unmuteChannel": "Увімкнути сповіщення каналу", "channels_deleteChannel": "Видалити канал", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 410b3a42..644435c8 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -374,6 +374,10 @@ "channels_public": "公共", "channels_private": "私有", "channels_editChannel": "编辑频道", + "channels_notificationSettings": "通知设置", + "channels_notifyAll": "所有消息", + "channels_notifyMentionsOnly": "仅提及", + "channels_notifyNone": "静音", "channels_muteChannel": "静音频道", "channels_unmuteChannel": "取消静音频道", "channels_deleteChannel": "删除频道", diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index a71e7cce..e39bb5f5 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -413,7 +413,7 @@ class _ChannelChatScreenState extends State { notificationMode == ChannelNotificationMode.muted ? Icons.notifications_off_outlined : notificationMode == ChannelNotificationMode.mentionsOnly - ? Icons.alternate_email + ? Icons.notification_important : Icons.notifications_outlined, ), onSelected: (mode) { @@ -439,7 +439,7 @@ class _ChannelChatScreenState extends State { value: ChannelNotificationMode.mentionsOnly, child: Row( children: [ - const Icon(Icons.alternate_email), + const Icon(Icons.notification_important), const SizedBox(width: 8), Text(context.l10n.channels_notifyMentionsOnly), ], diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 8e03112e..a16be11d 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -585,7 +585,7 @@ class _ChannelsScreenState extends State Icon( notificationMode == ChannelNotificationMode.muted ? Icons.notifications_off - : Icons.alternate_email, + : Icons.notification_important, size: 18, color: scheme.onSurfaceVariant, ), @@ -719,7 +719,7 @@ class _ChannelsScreenState extends State ), // Mentions only ListTile( - leading: const Icon(Icons.alternate_email), + leading: const Icon(Icons.notification_important), title: Text(sheetContext.l10n.channels_notifyMentionsOnly), trailing: currentMode == ChannelNotificationMode.mentionsOnly ? const Icon(Icons.check) diff --git a/untranslated.json b/untranslated.json index a2f434b5..9e26dfee 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1,113 +1 @@ -{ - "bg": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "de": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "es": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "hu": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "it": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "ja": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "ko": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "nl": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "pl": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "pt": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "ru": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "sk": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "sl": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "sv": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "uk": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ], - - "zh": [ - "channels_notificationSettings", - "channels_notifyAll", - "channels_notifyMentionsOnly", - "channels_notifyNone" - ] -} +{} \ No newline at end of file From 363c413717c6690af809bfd9dc71e0e88a51614d Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 04:57:23 +0200 Subject: [PATCH 08/67] Update notification icons for consistency - Use outlined icons for buttons (PopupMenuButton) - Use normal icons for menu items (PopupMenuItem/ListTile) - Ensure icon consistency across all notification mode displays - Verify no regressions in existing functionality --- lib/screens/channel_chat_screen.dart | 4 ++-- lib/screens/channels_screen.dart | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index e39bb5f5..7da13af4 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -413,7 +413,7 @@ class _ChannelChatScreenState extends State { notificationMode == ChannelNotificationMode.muted ? Icons.notifications_off_outlined : notificationMode == ChannelNotificationMode.mentionsOnly - ? Icons.notification_important + ? Icons.notification_important_outlined : Icons.notifications_outlined, ), onSelected: (mode) { @@ -425,7 +425,7 @@ class _ChannelChatScreenState extends State { child: Row( children: [ Icon( - Icons.notifications_active, + Icons.notifications, color: notificationMode == ChannelNotificationMode.all ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.onSurfaceVariant, diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index a16be11d..beaac2cc 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -700,7 +700,7 @@ class _ChannelsScreenState extends State // All notifications ListTile( leading: Icon( - Icons.notifications_active, + Icons.notifications, color: currentMode == ChannelNotificationMode.all ? Theme.of(sheetContext).colorScheme.primary : Theme.of(sheetContext).colorScheme.onSurfaceVariant, From 14230952c95a5be0f4f8340a3c30fa308af834c9 Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 05:07:28 +0200 Subject: [PATCH 09/67] Update notifications icons for better clarity and interface look and coherence --- lib/screens/channel_chat_screen.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 7da13af4..647c5508 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -411,10 +411,10 @@ class _ChannelChatScreenState extends State { tooltip: context.l10n.channels_notificationSettings, icon: Icon( notificationMode == ChannelNotificationMode.muted - ? Icons.notifications_off_outlined + ? Icons.notifications_off : notificationMode == ChannelNotificationMode.mentionsOnly - ? Icons.notification_important_outlined - : Icons.notifications_outlined, + ? Icons.notification_important + : Icons.notifications, ), onSelected: (mode) { settings.setChannelNotificationMode(muteKey, mode); From f77c959e4ad4f7183e2a6f298929cf28a622cd02 Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 06:14:18 +0200 Subject: [PATCH 10/67] UI: Replace notification menu with toggle button in channel chat --- lib/screens/channel_chat_screen.dart | 58 ++++++---------------------- 1 file changed, 12 insertions(+), 46 deletions(-) diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 647c5508..80818747 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -407,7 +407,7 @@ class _ChannelChatScreenState extends State { final notificationMode = settings.getChannelNotificationMode( muteKey, ); - return PopupMenuButton( + return IconButton( tooltip: context.l10n.channels_notificationSettings, icon: Icon( notificationMode == ChannelNotificationMode.muted @@ -416,52 +416,18 @@ class _ChannelChatScreenState extends State { ? Icons.notification_important : Icons.notifications, ), - onSelected: (mode) { - settings.setChannelNotificationMode(muteKey, mode); + onPressed: () { + final currentMode = settings.getChannelNotificationMode(muteKey); + ChannelNotificationMode newMode; + if (currentMode == ChannelNotificationMode.all) { + newMode = ChannelNotificationMode.mentionsOnly; + } else if (currentMode == ChannelNotificationMode.mentionsOnly) { + newMode = ChannelNotificationMode.muted; + } else { + newMode = ChannelNotificationMode.all; + } + settings.setChannelNotificationMode(muteKey, newMode); }, - itemBuilder: (context) => [ - PopupMenuItem( - value: ChannelNotificationMode.all, - child: Row( - children: [ - Icon( - Icons.notifications, - color: notificationMode == ChannelNotificationMode.all - ? Theme.of(context).colorScheme.primary - : Theme.of(context).colorScheme.onSurfaceVariant, - ), - const SizedBox(width: 8), - Text(context.l10n.channels_notifyAll), - ], - ), - ), - PopupMenuItem( - value: ChannelNotificationMode.mentionsOnly, - child: Row( - children: [ - const Icon(Icons.notification_important), - const SizedBox(width: 8), - Text(context.l10n.channels_notifyMentionsOnly), - ], - ), - ), - PopupMenuItem( - value: ChannelNotificationMode.muted, - child: Row( - children: [ - Icon( - Icons.notifications_off, - color: - notificationMode == ChannelNotificationMode.muted - ? Theme.of(context).colorScheme.primary - : Theme.of(context).colorScheme.onSurfaceVariant, - ), - const SizedBox(width: 8), - Text(context.l10n.channels_notifyNone), - ], - ), - ), - ], ); }, ), From 401b81475a2d209851abc2a5f1088a2ae357c525 Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 06:14:36 +0200 Subject: [PATCH 11/67] =?UTF-8?q?Fix=20documentation=20table=20to=20use=20?= =?UTF-8?q?distinct=20icons=20(=F0=9F=94=94/=F0=9F=94=94!/=F0=9F=94=95)=20?= =?UTF-8?q?for=20the=203=20modes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- documentation/notifications.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation/notifications.md b/documentation/notifications.md index d6f3f903..ee2aca91 100644 --- a/documentation/notifications.md +++ b/documentation/notifications.md @@ -106,7 +106,7 @@ Each channel supports three notification modes: | Mode | Icon | Behavior | |---|---|---| | **All messages** | 🔔 | Receive notifications for every message | -| **Mentions only** | 🔔 | Only notify when someone mentions you with "@yourname" or replies to your messages | +| **Mentions only** | 🔔! | Only notify when someone mentions you with "@yourname" or replies to your messages | | **Muted** | 🔕 | No notifications | Set the mode from: From 1c3fc7c2ecb7853f83ad92d0603effcf08105021 Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 08:34:46 +0200 Subject: [PATCH 12/67] fix mention detection to match @[pseudo] --- lib/connector/meshcore_connector.dart | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 7e96a3a3..2432b31a 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -7387,10 +7387,9 @@ class MeshCoreConnector extends ChangeNotifier { } /// Checks if a message mentions the current user. - /// Detects: @username, @1234 (last 4 hex chars of node ID), or replies to our messages. + /// Detects: @[username] format only. bool _doesMessageMentionUs(String messageText, ChannelMessage message) { final selfName = _selfName; - final selfPubKeyHex = selfPublicKeyHex; // Check if this is a reply to our message if (message.replyToSenderName != null) { @@ -7402,24 +7401,15 @@ class MeshCoreConnector extends ChangeNotifier { } } - // Check for @username at word boundaries (start of message or after whitespace) + final lowerMessage = messageText.toLowerCase(); + + // Check for @[username] pattern (bracketed mention format) if (selfName != null && selfName.isNotEmpty) { final lowerSelfName = selfName.toLowerCase(); - final lowerMessage = messageText.toLowerCase(); - final mentionPattern = RegExp( - r'\b@(' + RegExp.escape(lowerSelfName) + r')\b', + final bracketedMentionPattern = RegExp( + r'@\[(' + RegExp.escape(lowerSelfName) + r')\]', ); - if (mentionPattern.hasMatch(lowerMessage)) return true; - } - - // Check for @1234 pattern (last 4 hex chars of public key) - if (selfPubKeyHex.length >= 4) { - final last4Hex = selfPubKeyHex.substring(selfPubKeyHex.length - 4); - final lowerMessage = messageText.toLowerCase(); - final hexMentionPattern = RegExp( - r'\b@(' + RegExp.escape(last4Hex.toLowerCase()) + r')\b', - ); - if (hexMentionPattern.hasMatch(lowerMessage)) return true; + if (bracketedMentionPattern.hasMatch(lowerMessage)) return true; } return false; From e0ce8dc6b801056cca070d66139c2bc23310e79f Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 08:35:31 +0200 Subject: [PATCH 13/67] update mention detection pattern --- documentation/notifications.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/documentation/notifications.md b/documentation/notifications.md index ee2aca91..47447f5a 100644 --- a/documentation/notifications.md +++ b/documentation/notifications.md @@ -106,7 +106,7 @@ Each channel supports three notification modes: | Mode | Icon | Behavior | |---|---|---| | **All messages** | 🔔 | Receive notifications for every message | -| **Mentions only** | 🔔! | Only notify when someone mentions you with "@yourname" or replies to your messages | +| **Mentions only** | 🔔! | Only notify when someone mentions you with "@[yourname]" or replies to your messages | | **Muted** | 🔕 | No notifications | Set the mode from: @@ -115,7 +115,7 @@ Set the mode from: - Long-press a channel in the channels list → **Notification settings** → select mode - Channel notification actions (Android) -Mentions are detected by looking for "@" followed by your username at word boundaries (case-insensitive), or when someone replies to one of your messages. Reply detection checks if the message is a direct reply to a message you sent. +Mentions are detected by looking for "@[yourname]" (username in brackets, case-insensitive), or when someone replies to one of your messages. Reply detection checks if the message is a direct reply to a message you sent. ## Rate Limiting From 2e1c871ef1beb45336c3a2616b1da6a1fc9adb92 Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 15:20:27 +0200 Subject: [PATCH 14/67] remove useless reply detection pattern becose both app @[pseudo] by default on reply --- lib/connector/meshcore_connector.dart | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 2432b31a..9e9bbdfe 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -7369,7 +7369,7 @@ class MeshCoreConnector extends ChangeNotifier { ? translationResult.translatedText.trim() : message.text.trim(); - // If mode is mentionsOnly, check if message mentions us or is a reply to us + // If mode is mentionsOnly, check if message mentions us if (notificationMode == ChannelNotificationMode.mentionsOnly) { if (!_doesMessageMentionUs(resolvedText, message)) return; } @@ -7390,17 +7390,6 @@ class MeshCoreConnector extends ChangeNotifier { /// Detects: @[username] format only. bool _doesMessageMentionUs(String messageText, ChannelMessage message) { final selfName = _selfName; - - // Check if this is a reply to our message - if (message.replyToSenderName != null) { - final lowerSelfName = selfName?.toLowerCase(); - final lowerReplyToSender = message.replyToSenderName!.toLowerCase(); - if (lowerSelfName != null && lowerSelfName.isNotEmpty && - lowerReplyToSender == lowerSelfName) { - return true; - } - } - final lowerMessage = messageText.toLowerCase(); // Check for @[username] pattern (bracketed mention format) From 9f358461e79d44becb7c827b99bb84bef1a5645c Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 15:23:52 +0200 Subject: [PATCH 15/67] update notif docs becose of deleted specific ans redundant reply detection --- documentation/notifications.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/documentation/notifications.md b/documentation/notifications.md index 47447f5a..8bdc5d6c 100644 --- a/documentation/notifications.md +++ b/documentation/notifications.md @@ -106,7 +106,7 @@ Each channel supports three notification modes: | Mode | Icon | Behavior | |---|---|---| | **All messages** | 🔔 | Receive notifications for every message | -| **Mentions only** | 🔔! | Only notify when someone mentions you with "@[yourname]" or replies to your messages | +| **Mentions only** | 🔔! | Only notify when someone mentions you with "@[yourname]" | | **Muted** | 🔕 | No notifications | Set the mode from: @@ -115,7 +115,7 @@ Set the mode from: - Long-press a channel in the channels list → **Notification settings** → select mode - Channel notification actions (Android) -Mentions are detected by looking for "@[yourname]" (username in brackets, case-insensitive), or when someone replies to one of your messages. Reply detection checks if the message is a direct reply to a message you sent. +Mentions are detected by looking for "@[yourname]" (username in brackets, case-insensitive). ## Rate Limiting From 705bff2f1553d558285d60767612363c857cb3b7 Mon Sep 17 00:00:00 2001 From: edouard Date: Sat, 24 Oct 2026 15:26:43 +0200 Subject: [PATCH 16/67] format code --- lib/connector/meshcore_connector.dart | 4 ++-- lib/screens/channel_chat_screen.dart | 7 +++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 9e9bbdfe..7777d60f 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -7391,7 +7391,7 @@ class MeshCoreConnector extends ChangeNotifier { bool _doesMessageMentionUs(String messageText, ChannelMessage message) { final selfName = _selfName; final lowerMessage = messageText.toLowerCase(); - + // Check for @[username] pattern (bracketed mention format) if (selfName != null && selfName.isNotEmpty) { final lowerSelfName = selfName.toLowerCase(); @@ -7400,7 +7400,7 @@ class MeshCoreConnector extends ChangeNotifier { ); if (bracketedMentionPattern.hasMatch(lowerMessage)) return true; } - + return false; } diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 80818747..0a8238b8 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -417,11 +417,14 @@ class _ChannelChatScreenState extends State { : Icons.notifications, ), onPressed: () { - final currentMode = settings.getChannelNotificationMode(muteKey); + final currentMode = settings.getChannelNotificationMode( + muteKey, + ); ChannelNotificationMode newMode; if (currentMode == ChannelNotificationMode.all) { newMode = ChannelNotificationMode.mentionsOnly; - } else if (currentMode == ChannelNotificationMode.mentionsOnly) { + } else if (currentMode == + ChannelNotificationMode.mentionsOnly) { newMode = ChannelNotificationMode.muted; } else { newMode = ChannelNotificationMode.all; From 050016f599da89edd0ea83db67c68f38eec43728 Mon Sep 17 00:00:00 2001 From: ericz Date: Sat, 24 Oct 2026 16:46:32 +0200 Subject: [PATCH 17/67] ai fix tcp reconnect test fail --- test/connector/tcp_auto_reconnect_test.dart | 46 ++++++++++----------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/test/connector/tcp_auto_reconnect_test.dart b/test/connector/tcp_auto_reconnect_test.dart index 5c258cfe..9d63ab17 100644 --- a/test/connector/tcp_auto_reconnect_test.dart +++ b/test/connector/tcp_auto_reconnect_test.dart @@ -12,11 +12,15 @@ import 'package:meshcore_open/services/usb_serial_frame_codec.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; -Future _waitFor(bool Function() condition, {int seconds = 10}) async { +Future _waitFor( + bool Function() condition, { + int seconds = 10, + Duration pollInterval = const Duration(milliseconds: 25), +}) async { final end = DateTime.now().add(Duration(seconds: seconds)); while (!condition()) { if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition'); - await Future.delayed(const Duration(milliseconds: 25)); + await Future.delayed(pollInterval); } } @@ -198,27 +202,23 @@ void main() { expect(_connector.isTcpTransportConnected, isTrue); // The companion goes away entirely: attempts fail and are rescheduled. - var sawRetryAttempt = false; - void observeRetryAttempt() { - if (_connector.state == MeshCoreConnectionState.connecting) { - sawRetryAttempt = true; - } - } - - _connector.addListener(observeRetryAttempt); - try { - await companion.close(); - // Wait for a retry to start and fail, then verify another backoff is - // scheduled. A fixed delay can observe the connector mid-attempt. - await _waitFor( - () => - sawRetryAttempt && - _connector.state == MeshCoreConnectionState.disconnected && - _connector.isAutoReconnectScheduled, - ); - } finally { - _connector.removeListener(observeRetryAttempt); - } + await companion.close(); + await _waitFor( + () => + _connector.state == MeshCoreConnectionState.disconnected && + _connector.isAutoReconnectScheduled, + ); + await _waitFor( + () => !_connector.isAutoReconnectScheduled, + pollInterval: const Duration(milliseconds: 1), + ); + // The timer firing proves an attempt started; wait for its failure to + // finish and the next backoff to become active. + await _waitFor( + () => + _connector.state == MeshCoreConnectionState.disconnected && + _connector.isAutoReconnectScheduled, + ); expect(_connector.isTcpTransportConnected, isFalse); }, ); From fe7e72a4218cf314f2ca106e83041d400f9b6a20 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 20:22:12 -0700 Subject: [PATCH 18/67] Make Android Auto an opt-in build flag Android Auto support is now merged into the app only when building with -PandroidAuto=true (flutter build apk --android-project-arg=androidAuto=true). The car application meta-data and automotive_app_desc.xml move to android/app/src/androidAuto/, so default builds no longer declare Android Auto. Notification replies from the shade and watches are unchanged. --- README.md | 6 +++--- android/app/build.gradle.kts | 18 ++++++++++++++++++ .../app/src/androidAuto/AndroidManifest.xml | 9 +++++++++ .../res/xml/automotive_app_desc.xml | 0 android/app/src/main/AndroidManifest.xml | 4 ---- documentation/notifications.md | 8 ++++++++ 6 files changed, 38 insertions(+), 7 deletions(-) create mode 100644 android/app/src/androidAuto/AndroidManifest.xml rename android/app/src/{main => androidAuto}/res/xml/automotive_app_desc.xml (100%) diff --git a/README.md b/README.md index 92d60fe4..1ca9ba29 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ See the [user documentation](documentation/README.md), [connection guide](docume - **Contact Groups**: Create custom groups to organize your mesh network contacts - **Message Reactions**: React to messages with emoji responses - **Message Replies**: Thread conversations with inline reply functionality -- **Android Auto & Watches**: Hear messages and reply by voice in Android Auto, or reply from the notification shade and Wear OS/Galaxy watches ([guide](documentation/notifications.md#android-auto)) +- **Android Auto & Watches**: Reply from the notification shade and Wear OS/Galaxy watches, or hear messages and reply by voice in Android Auto (optional build flag) ([guide](documentation/notifications.md#android-auto)) - **Channel Muting**: Mute a channel from its chat screen, the channel list, or its notification ### Mesh Network @@ -103,7 +103,7 @@ See the [user documentation](documentation/README.md), [connection guide](docume | Map & Location | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Device Management | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Repeater Hub | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| Notification replies | ✅
(incl. Android Auto, watches) | ❌ | ❌ | ❌ | ❌ | ❌ | +| Notification replies | ✅
(incl. watches; Android Auto optional) | ❌ | ❌ | ❌ | ❌ | ❌ | The matrix describes implemented functionality, not a guarantee that every feature has been tested on every device. Web device connections use Web Serial and require Chrome and a secure origin. Image inference and translation require native runtimes and are unavailable on web. Android APKs currently include only `arm64-v8a`; the minimum Android API follows the Flutter SDK used to build. @@ -228,7 +228,7 @@ Messages are transmitted as binary frames using a custom protocol optimized for - **Theme**: System default, light, or dark mode - **Language**: Use one of 18 languages (English, Chinese, French, Spanish, Portuguese, German, Dutch, Polish, Swedish, Italian, Slovak, Slovenian, Bulgarian, Russian, Ukrainian, Hungarian, Japanese, Korean) -- **Notifications**: Configurable for messages, channels, and node advertisements; per-channel muting; reply, mark-as-read, and mute actions on Android notifications and watches (reply and mark-as-read in Android Auto) +- **Notifications**: Configurable for messages, channels, and node advertisements; per-channel muting; reply, mark-as-read, and mute actions on Android notifications and watches (reply and mark-as-read in Android Auto when built with `--android-project-arg=androidAuto=true`) - **Battery Chemistry**: Support for NMC, LiFePO4, LiPo, and LiPo HV battery types - **Message Retry**: Automatic retry with configurable path clearing diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 8aa73ce6..24b5883c 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -98,6 +98,24 @@ android { // } } +// Android Auto (notification read-aloud and voice reply) is opt-in, because +// declaring it puts the app through Play's separate Android Auto review. +// Enable it with `flutter build apk --android-project-arg=androidAuto=true` +// or `./gradlew -PandroidAuto=true ...`. +val androidAutoEnabled = (findProperty("androidAuto") as String?)?.toBoolean() == true + +if (androidAutoEnabled) { + android.sourceSets.getByName("main").res.srcDir("src/androidAuto/res") +} + +androidComponents { + onVariants { variant -> + if (androidAutoEnabled) { + variant.sources.manifests.addStaticManifestFile("src/androidAuto/AndroidManifest.xml") + } + } +} + flutter { source = "../.." } diff --git a/android/app/src/androidAuto/AndroidManifest.xml b/android/app/src/androidAuto/AndroidManifest.xml new file mode 100644 index 00000000..4c5db2aa --- /dev/null +++ b/android/app/src/androidAuto/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/android/app/src/main/res/xml/automotive_app_desc.xml b/android/app/src/androidAuto/res/xml/automotive_app_desc.xml similarity index 100% rename from android/app/src/main/res/xml/automotive_app_desc.xml rename to android/app/src/androidAuto/res/xml/automotive_app_desc.xml diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 3bb75c69..27d9692a 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -34,10 +34,6 @@ - - Date: Sat, 24 Oct 2026 20:43:00 -0700 Subject: [PATCH 19/67] Fix review findings in radio settings path hash size - Presets no longer reset the path hash size; the unused preset field is gone - Confirm the new path hash size from the refreshed DEVICE_INFO and show a specific error when the radio does not apply it - Log path hash size with the other radio settings and on manual edits - Add MeshCoreConnector.supportsPathHashMode and use it in both screens - Use the same 0-2 mode values and helper text as the other selectors --- lib/connector/meshcore_connector.dart | 3 ++ lib/l10n/app_en.arb | 1 + lib/l10n/app_localizations.dart | 6 +++ lib/l10n/app_localizations_bg.dart | 4 ++ lib/l10n/app_localizations_de.dart | 4 ++ lib/l10n/app_localizations_en.dart | 4 ++ lib/l10n/app_localizations_es.dart | 4 ++ lib/l10n/app_localizations_fr.dart | 4 ++ lib/l10n/app_localizations_hu.dart | 4 ++ lib/l10n/app_localizations_it.dart | 4 ++ lib/l10n/app_localizations_ja.dart | 4 ++ lib/l10n/app_localizations_ko.dart | 4 ++ lib/l10n/app_localizations_nl.dart | 4 ++ lib/l10n/app_localizations_pl.dart | 4 ++ lib/l10n/app_localizations_pt.dart | 4 ++ lib/l10n/app_localizations_ru.dart | 4 ++ lib/l10n/app_localizations_sk.dart | 4 ++ lib/l10n/app_localizations_sl.dart | 4 ++ lib/l10n/app_localizations_sv.dart | 4 ++ lib/l10n/app_localizations_uk.dart | 4 ++ lib/l10n/app_localizations_zh.dart | 4 ++ lib/models/radio_settings.dart | 2 - lib/screens/settings_screen.dart | 11 +--- lib/widgets/radio_settings_dialog.dart | 72 +++++++++++++++++++------- untranslated.json | 70 ++++++++++++++++++++++++- 25 files changed, 205 insertions(+), 32 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 03b03944..1d7dfa0a 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -681,6 +681,9 @@ class MeshCoreConnector extends ChangeNotifier { /// from ver code 8. bool get supportsNodeDiscover => (_firmwareVerCode ?? 0) >= 8; + /// CMD_SET_PATH_HASH_MODE exists from ver code 10 (v1.14.0). + bool get supportsPathHashMode => (_firmwareVerCode ?? 0) >= 10; + /// CMD_GET/SET_DEFAULT_FLOOD_SCOPE exist from ver code 11 (v1.15.0). bool get supportsDefaultFloodScope => (_firmwareVerCode ?? 0) >= 11; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index f62a038b..6d29965a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -198,6 +198,7 @@ "settings_radioSettingsSubtitle": "Frequency, power, spreading factor", "settings_radioSettingsUpdated": "Radio settings updated", "settings_radioSettingsNotApplied": "The radio did not apply these settings", + "settings_pathHashModeNotApplied": "Radio settings were applied, but the radio did not confirm the new path hash size", "settings_regionSettings": "Regions", "settings_regionSettingsSubtitle": "Limit channel floods to an area", "settings_regionEmptyExplanation": "Regions limit flood messages to repeaters in an area. Fetch them from nearby repeaters or add one by name.", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index b5e7efc5..b7d98c28 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -862,6 +862,12 @@ abstract class AppLocalizations { /// **'The radio did not apply these settings'** String get settings_radioSettingsNotApplied; + /// No description provided for @settings_pathHashModeNotApplied. + /// + /// In en, this message translates to: + /// **'Radio settings were applied, but the radio did not confirm the new path hash size'** + String get settings_pathHashModeNotApplied; + /// No description provided for @settings_regionSettings. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index b9f79a6f..62a52ade 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -425,6 +425,10 @@ class AppLocalizationsBg extends AppLocalizations { String get settings_radioSettingsNotApplied => 'Радиото не приложи тези настройки'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Региони'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index d7893ccf..3b45ccb5 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -427,6 +427,10 @@ class AppLocalizationsDe extends AppLocalizations { String get settings_radioSettingsNotApplied => 'Das Funkgerät hat diese Einstellungen nicht übernommen'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regionen'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0265ac8b..da8144d5 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -421,6 +421,10 @@ class AppLocalizationsEn extends AppLocalizations { String get settings_radioSettingsNotApplied => 'The radio did not apply these settings'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regions'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 75c2ab0e..e40f0fa2 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -425,6 +425,10 @@ class AppLocalizationsEs extends AppLocalizations { String get settings_radioSettingsNotApplied => 'La radio no aplicó esta configuración'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regiones'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 85de8bbb..3c6ee155 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -427,6 +427,10 @@ class AppLocalizationsFr extends AppLocalizations { String get settings_radioSettingsNotApplied => 'La radio n\'a pas appliqué ces paramètres'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Régions'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index ef4b3d9b..5bf2522a 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -423,6 +423,10 @@ class AppLocalizationsHu extends AppLocalizations { String get settings_radioSettingsNotApplied => 'A rádió nem alkalmazta ezeket a beállításokat'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Tájak'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 50bb49d9..bcb282ef 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -427,6 +427,10 @@ class AppLocalizationsIt extends AppLocalizations { String get settings_radioSettingsNotApplied => 'La radio non ha applicato queste impostazioni'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regioni'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 2aabf56e..7d98b2a7 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -407,6 +407,10 @@ class AppLocalizationsJa extends AppLocalizations { @override String get settings_radioSettingsNotApplied => 'ラジオがこれらの設定を適用しませんでした'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => '地域'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 98a81ac1..c2a268f9 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -407,6 +407,10 @@ class AppLocalizationsKo extends AppLocalizations { @override String get settings_radioSettingsNotApplied => '라디오가 이 설정을 적용하지 않았습니다'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => '지역'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 082f2a18..edadc900 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -423,6 +423,10 @@ class AppLocalizationsNl extends AppLocalizations { String get settings_radioSettingsNotApplied => 'De radio heeft deze instellingen niet toegepast'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regio\'s'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 3db02722..6662f4e0 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -431,6 +431,10 @@ class AppLocalizationsPl extends AppLocalizations { String get settings_radioSettingsNotApplied => 'Radio nie zastosowało tych ustawień'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regiony'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 9b89ff31..f1943007 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -427,6 +427,10 @@ class AppLocalizationsPt extends AppLocalizations { String get settings_radioSettingsNotApplied => 'O rádio não aplicou estas configurações'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regiões'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index a1686804..c1a8ed10 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -426,6 +426,10 @@ class AppLocalizationsRu extends AppLocalizations { String get settings_radioSettingsNotApplied => 'Радиомодуль не применил эти настройки'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Регионы'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 9cd7cc6d..a8d0887b 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -426,6 +426,10 @@ class AppLocalizationsSk extends AppLocalizations { String get settings_radioSettingsNotApplied => 'Rádio tieto nastavenia neuplatnilo'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regiony'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 8602eb0d..2fd1903a 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -425,6 +425,10 @@ class AppLocalizationsSl extends AppLocalizations { String get settings_radioSettingsNotApplied => 'Radio teh nastavitev ni uveljavil'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regioni'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 1d87483d..face6140 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -423,6 +423,10 @@ class AppLocalizationsSv extends AppLocalizations { String get settings_radioSettingsNotApplied => 'Radion tillämpade inte dessa inställningar'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Regioner'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index ebd6d5eb..47888b9e 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -425,6 +425,10 @@ class AppLocalizationsUk extends AppLocalizations { String get settings_radioSettingsNotApplied => 'Радіомодуль не застосував ці налаштування'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => 'Ріси'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 703a27fe..1ab063c1 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -401,6 +401,10 @@ class AppLocalizationsZh extends AppLocalizations { @override String get settings_radioSettingsNotApplied => '收音机未应用这些设置'; + @override + String get settings_pathHashModeNotApplied => + 'Radio settings were applied, but the radio did not confirm the new path hash size'; + @override String get settings_regionSettings => '地区'; diff --git a/lib/models/radio_settings.dart b/lib/models/radio_settings.dart index 6b3eee84..f7c4709c 100644 --- a/lib/models/radio_settings.dart +++ b/lib/models/radio_settings.dart @@ -50,7 +50,6 @@ class RadioSettings { final LoRaSpreadingFactor spreadingFactor; final LoRaCodingRate codingRate; final int txPowerDbm; - final int pathHashByteWidth; RadioSettings({ required this.frequencyMHz, @@ -58,7 +57,6 @@ class RadioSettings { required this.spreadingFactor, required this.codingRate, required this.txPowerDbm, - this.pathHashByteWidth = 1, // app default; presets override if needed }); // Regional preset configurations diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index dff41c0b..74ca3e2c 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -25,9 +25,6 @@ import '../widgets/sync_progress_overlay.dart'; import 'region_management_screen.dart'; import '../utils/share_origin.dart'; -/// Companion firmware version that added CMD_SET_PATH_HASH_MODE (v1.14.0). -const int _minFirmwareVerCodeForPathHashMode = 10; - class SettingsScreen extends StatefulWidget { const SettingsScreen({super.key}); @@ -566,14 +563,10 @@ class _SettingsScreenState extends State { title: l10n.repeater_pathHashMode, subtitle: !connected ? offline - : (connector.firmwareVerCode ?? 0) < - _minFirmwareVerCodeForPathHashMode + : !connector.supportsPathHashMode ? l10n.settings_requiresFirmware('v1.14') : _pathHashModeSubtitle(context, connector.pathHashByteWidth), - onTap: - connector.isConnected && - (connector.firmwareVerCode ?? 0) >= - _minFirmwareVerCodeForPathHashMode + onTap: connector.isConnected && connector.supportsPathHashMode ? () => _editPathHashMode(context, connector) : null, ), diff --git a/lib/widgets/radio_settings_dialog.dart b/lib/widgets/radio_settings_dialog.dart index 7f9834ab..aa00e3d9 100644 --- a/lib/widgets/radio_settings_dialog.dart +++ b/lib/widgets/radio_settings_dialog.dart @@ -30,12 +30,9 @@ bool _isAllowedRepeatFreqKHz(MeshCoreConnector connector, int freqKHz) { /// Lowest TX power companion firmware accepts (CMD_SET_RADIO_TX_POWER). const int _minTxPowerDbm = -9; -/// Companion firmware version that added CMD_SET_PATH_HASH_MODE (v1.14.0). -const int _minFirmwareVerCodeForPathHashMode = 10; - -/// Radio parameter editor (preset, frequency, bandwidth, SF, CR, TX power and -/// off-grid client repeat). Stays open when the radio rejects or fails to -/// apply the settings so the user's edits are not lost. +/// Radio parameter editor (preset, frequency, bandwidth, SF, CR, TX power, +/// path-hash size and off-grid client repeat). Stays open when the radio +/// rejects or fails to apply the settings so the user's edits are not lost. class RadioSettingsDialog extends StatefulWidget { final MeshCoreConnector connector; @@ -58,9 +55,7 @@ class _RadioSettingsDialogState extends State { String? _frequencyError; String? _txPowerError; - bool get _supportsPathHashMode => - (widget.connector.firmwareVerCode ?? 0) >= - _minFirmwareVerCodeForPathHashMode; + bool get _supportsPathHashMode => widget.connector.supportsPathHashMode; AppDebugLogService get _appLog => Provider.of(context, listen: false); @@ -284,7 +279,6 @@ class _RadioSettingsDialogState extends State { _spreadingFactor = preset.spreadingFactor; _codingRate = preset.codingRate; _txPowerController.text = preset.txPowerDbm.toString(); - _pathHashByteWidth = preset.pathHashByteWidth; _selectedPresetIndex = index; _lastNonRepeatSnapshot = baseSnapshot; // Programmatic writes skip TextField.onChanged, so clear any stale @@ -449,15 +443,34 @@ class _RadioSettingsDialogState extends State { return; } await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower)); - if (_supportsPathHashMode && - _pathHashByteWidth != widget.connector.pathHashByteWidth) { - await widget.connector.setPathHashMode(_pathHashByteWidth - 1); + // setPathHashMode updates the local width optimistically; the refreshed + // DEVICE_INFO below overwrites it with what the radio actually stored. + final requestedPathHashWidth = + _supportsPathHashMode && + _pathHashByteWidth != widget.connector.pathHashByteWidth + ? _pathHashByteWidth + : null; + if (requestedPathHashWidth != null) { + await widget.connector.setPathHashMode(requestedPathHashWidth - 1); } final selfInfo = widget.connector.receivedFrames .firstWhere((f) => f.isNotEmpty && f[0] == respCodeSelfInfo) .timeout(const Duration(seconds: 5)); + final deviceInfo = requestedPathHashWidth == null + ? null + : widget.connector.receivedFrames + .firstWhere((f) => f.isNotEmpty && f[0] == respCodeDeviceInfo) + .timeout(const Duration(seconds: 5)); await widget.connector.refreshDeviceInfo(); - final applied = await selfInfo.then( + // Without a refreshed DEVICE_INFO the path hash change is unconfirmed + // (this also covers setPathHashMode skipping a disconnected radio). + final pathHashApplied = + deviceInfo == null || + await deviceInfo.then( + (_) => widget.connector.pathHashByteWidth == requestedPathHashWidth, + onError: (_) => false, + ); + final radioApplied = await selfInfo.then( (_) => _deviceMatches( freqHz: freqHz, bwHz: bwHz, @@ -468,7 +481,7 @@ class _RadioSettingsDialogState extends State { ), onError: (_) => true, ); - if (!applied) { + if (!radioApplied) { _logRadioSettingsState('Radio did not apply requested settings'); if (!mounted) return; showDismissibleSnackBar( @@ -477,6 +490,17 @@ class _RadioSettingsDialogState extends State { ); return; } + if (!pathHashApplied) { + // Radio params and TX power were already applied; only the path + // hash size is outstanding, so say that rather than a generic error. + _logRadioSettingsState('Radio did not apply requested path hash size'); + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.settings_pathHashModeNotApplied), + ); + return; + } final rememberedSnapshot = _clientRepeat ? _lastNonRepeatSnapshot : _currentSnapshot(); @@ -553,6 +577,7 @@ class _RadioSettingsDialogState extends State { 'sf=${_spreadingFactor.label} ' 'cr=${_codingRate.label} ' 'tx=${_txPowerController.text}dBm ' + 'pathHash=${_pathHashByteWidth}B ' 'repeat=$_clientRepeat ' 'preset=${_presetLabel(_selectedPresetIndex)} ' 'lastNonRepeat=${_formatSnapshot(_lastNonRepeatSnapshot)}', @@ -688,29 +713,36 @@ class _RadioSettingsDialogState extends State { ), const SizedBox(height: 16), if (_supportsPathHashMode) ...[ + // Values are path hash modes (0-2, byte width - 1), matching + // the selectors in settings_screen and repeater_settings_screen. DropdownButtonFormField( - initialValue: _pathHashByteWidth, + initialValue: (_pathHashByteWidth - 1).clamp(0, 2).toInt(), decoration: InputDecoration( labelText: l10n.repeater_pathHashMode, + helperText: l10n.settings_pathHashModeHelper, + helperMaxLines: 5, border: const OutlineInputBorder(), ), items: [ DropdownMenuItem( - value: 1, + value: 0, child: Text(l10n.repeater_pathHashModeOption0), ), DropdownMenuItem( - value: 2, + value: 1, child: Text(l10n.repeater_pathHashModeOption1), ), DropdownMenuItem( - value: 3, + value: 2, child: Text(l10n.repeater_pathHashModeOption2), ), ], onChanged: (value) { if (value == null) return; - setState(() => _pathHashByteWidth = value); + setState(() => _pathHashByteWidth = value + 1); + _logRadioSettingsState( + 'Manual settings edit: path hash size', + ); }, ), const SizedBox(height: 16), diff --git a/untranslated.json b/untranslated.json index 9e26dfee..648cd980 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,69 @@ -{} \ No newline at end of file +{ + "bg": [ + "settings_pathHashModeNotApplied" + ], + + "de": [ + "settings_pathHashModeNotApplied" + ], + + "es": [ + "settings_pathHashModeNotApplied" + ], + + "fr": [ + "settings_pathHashModeNotApplied" + ], + + "hu": [ + "settings_pathHashModeNotApplied" + ], + + "it": [ + "settings_pathHashModeNotApplied" + ], + + "ja": [ + "settings_pathHashModeNotApplied" + ], + + "ko": [ + "settings_pathHashModeNotApplied" + ], + + "nl": [ + "settings_pathHashModeNotApplied" + ], + + "pl": [ + "settings_pathHashModeNotApplied" + ], + + "pt": [ + "settings_pathHashModeNotApplied" + ], + + "ru": [ + "settings_pathHashModeNotApplied" + ], + + "sk": [ + "settings_pathHashModeNotApplied" + ], + + "sl": [ + "settings_pathHashModeNotApplied" + ], + + "sv": [ + "settings_pathHashModeNotApplied" + ], + + "uk": [ + "settings_pathHashModeNotApplied" + ], + + "zh": [ + "settings_pathHashModeNotApplied" + ] +} From b6c1d73bf0f8830cdac97db71d22feedf7d0c31a Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 20:45:14 -0700 Subject: [PATCH 20/67] Fix review findings in low battery alerts - Respect the notifications-enabled setting - Notify only the lowest newly crossed threshold - Ignore implausible readings (boards without a battery sensor report 0 mV) - Wait for the device identity so the saved chemistry is used - Require two consecutive low readings before alerting - Re-arm and clear alerts on any link reset, not just explicit disconnect - Cancel stale notifications on re-arm and link reset - Scope notification ids per device and name the device in the body - Use the connector's shared NotificationService --- lib/connector/meshcore_connector.dart | 72 +++++++++++++++++++++++--- lib/l10n/app_en.arb | 7 ++- lib/l10n/app_localizations.dart | 6 +-- lib/l10n/app_localizations_bg.dart | 4 +- lib/l10n/app_localizations_de.dart | 4 +- lib/l10n/app_localizations_en.dart | 4 +- lib/l10n/app_localizations_es.dart | 4 +- lib/l10n/app_localizations_fr.dart | 4 +- lib/l10n/app_localizations_hu.dart | 4 +- lib/l10n/app_localizations_it.dart | 4 +- lib/l10n/app_localizations_ja.dart | 4 +- lib/l10n/app_localizations_ko.dart | 4 +- lib/l10n/app_localizations_nl.dart | 4 +- lib/l10n/app_localizations_pl.dart | 4 +- lib/l10n/app_localizations_pt.dart | 4 +- lib/l10n/app_localizations_ru.dart | 4 +- lib/l10n/app_localizations_sk.dart | 4 +- lib/l10n/app_localizations_sl.dart | 4 +- lib/l10n/app_localizations_sv.dart | 4 +- lib/l10n/app_localizations_uk.dart | 4 +- lib/l10n/app_localizations_zh.dart | 4 +- lib/services/notification_service.dart | 33 ++++++++++-- 22 files changed, 138 insertions(+), 52 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 4a09067b..fbdd914c 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -302,6 +302,18 @@ class MeshCoreConnector extends ChangeNotifier { // crossing, re-arming 5 points above the threshold after recharge. static const List _lowBatteryThresholds = [25, 10]; final Set _batteryAlertedThresholds = {}; + // Consecutive readings that newly crossed a threshold. Alerts need + // [_lowBatteryConfirmReadings] in a row so a single TX-load voltage sag + // doesn't notify. + int _lowBatteryReadingStreak = 0; + // Device key the posted low-battery notifications were scoped to, kept so + // they can still be cancelled after the session's identity is cleared. + String? _lowBatteryAlertDeviceKey; + static const int _lowBatteryConfirmReadings = 2; + // Readings below this are treated as "no battery sensor" (boards without + // one report 0 mV). Any single Li cell, including LiFePO4 (2600 mV empty), + // is protection-cut well above 2 V, so lower values are not real readings. + static const int _minPlausibleBatteryMillivolts = 2000; double? _selfLatitude; double? _selfLongitude; final List _directRepeaters = List.empty(growable: true); @@ -3722,7 +3734,6 @@ class MeshCoreConnector extends ChangeNotifier { _allowedRepeatFreqRanges = null; _autoAddMaxHops = null; _contactsStorageFull = false; - _batteryAlertedThresholds.clear(); _repeaterBatterySnapshots.clear(); _activeTransport = MeshCoreTransportType.bluetooth; @@ -6492,24 +6503,61 @@ class MeshCoreConnector extends ChangeNotifier { } void _checkLowBatteryThresholds() { + final millivolts = _batteryMillivolts; + if (millivolts == null || millivolts < _minPlausibleBatteryMillivolts) { + return; + } + // Until the device identity (and so its saved chemistry) is known, the + // percentage falls back to NMC and can read low for e.g. LiFePO4 packs. + // Skip evaluation; the next battery poll re-checks once identity is set. + if (batteryDeviceKey == null || _appSettingsService == null) return; final percent = batteryPercent; if (percent == null) return; + // Only the lowest newly crossed threshold notifies; higher ones crossed + // in the same reading are marked as alerted silently. + final newlyCrossed = []; for (final threshold in _lowBatteryThresholds) { if (percent <= threshold && !_batteryAlertedThresholds.contains(threshold)) { - _batteryAlertedThresholds.add(threshold); - NotificationService().showLowBatteryNotification( - batteryPercent: percent, - threshold: threshold, - ); + newlyCrossed.add(threshold); } else if (percent > threshold + 5 && _batteryAlertedThresholds.contains(threshold)) { // Re-arm once the battery recovers 5 points above the threshold, // so a recharge + discharge cycle alerts again without flapping. _batteryAlertedThresholds.remove(threshold); + final alertDeviceKey = _lowBatteryAlertDeviceKey; + if (alertDeviceKey != null) { + unawaited( + _notificationService.clearLowBatteryNotifications(alertDeviceKey, [ + threshold, + ]), + ); + } } } + if (newlyCrossed.isEmpty) { + _lowBatteryReadingStreak = 0; + return; + } + // Debounce: wait for consecutive low readings before alerting. + if (++_lowBatteryReadingStreak < _lowBatteryConfirmReadings) return; + _lowBatteryReadingStreak = 0; + _batteryAlertedThresholds.addAll(newlyCrossed); + final deviceKey = batteryDeviceKey!; + _lowBatteryAlertDeviceKey = deviceKey; + final lowestNewlyCrossed = newlyCrossed.reduce((a, b) => a < b ? a : b); + if (!(_appSettingsService?.settings.notificationsEnabled ?? false)) { + return; + } + unawaited( + _notificationService.showLowBatteryNotification( + deviceKey: deviceKey, + deviceName: deviceDisplayName, + batteryPercent: percent, + threshold: lowestNewlyCrossed, + ), + ); } void _checkManualAddContacts() async { @@ -8595,6 +8643,18 @@ class MeshCoreConnector extends ChangeNotifier { _hasReceivedDeviceInfo = false; _batteryMillivolts = null; _batteryRequested = false; + final alertDeviceKey = _lowBatteryAlertDeviceKey; + if (alertDeviceKey != null && _batteryAlertedThresholds.isNotEmpty) { + unawaited( + _notificationService.clearLowBatteryNotifications( + alertDeviceKey, + _batteryAlertedThresholds.toList(), + ), + ); + } + _batteryAlertedThresholds.clear(); + _lowBatteryAlertDeviceKey = null; + _lowBatteryReadingStreak = 0; _pathHashByteWidth = 1; _maxContacts = _defaultMaxContacts; _maxChannels = _defaultMaxChannels; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 96ee02c8..8e949cab 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2682,10 +2682,13 @@ "@notification_lowBatteryTitle": { "description": "Title of the low battery notification" }, - "notification_lowBatteryBody": "Device battery is at {percent}%", + "notification_lowBatteryBody": "{deviceName} battery is at {percent}%", "@notification_lowBatteryBody": { - "description": "Body of the low battery notification", + "description": "Body of the low battery notification; deviceName is the connected radio's node name", "placeholders": { + "deviceName": { + "type": "String" + }, "percent": { "type": "int" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index cfcb4347..58630f96 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -8114,11 +8114,11 @@ abstract class AppLocalizations { /// **'Low battery'** String get notification_lowBatteryTitle; - /// Body of the low battery notification + /// Body of the low battery notification; deviceName is the connected radio's node name /// /// In en, this message translates to: - /// **'Device battery is at {percent}%'** - String notification_lowBatteryBody(int percent); + /// **'{deviceName} battery is at {percent}%'** + String notification_lowBatteryBody(String deviceName, int percent); /// No description provided for @notification_messagesCount. /// diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index b0f3efc8..d8bec52f 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -4731,8 +4731,8 @@ class AppLocalizationsBg extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index fa451134..a03829e6 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -4742,8 +4742,8 @@ class AppLocalizationsDe extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 61785365..8a4cea69 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -4666,8 +4666,8 @@ class AppLocalizationsEn extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 11483e01..dc0b28be 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -4733,8 +4733,8 @@ class AppLocalizationsEs extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 4430c9b1..f55984f5 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -4752,8 +4752,8 @@ class AppLocalizationsFr extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 0da9db3e..e35c1981 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -4730,8 +4730,8 @@ class AppLocalizationsHu extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 11c3a4df..c4a97a49 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -4739,8 +4739,8 @@ class AppLocalizationsIt extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index e409ad80..8066f4ec 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -4502,8 +4502,8 @@ class AppLocalizationsJa extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 82667ffe..db66d010 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -4513,8 +4513,8 @@ class AppLocalizationsKo extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index c31460d2..470c6646 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -4708,8 +4708,8 @@ class AppLocalizationsNl extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 27ef631c..96f15d50 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -4759,8 +4759,8 @@ class AppLocalizationsPl extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index f51d5bb3..9358590b 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -4735,8 +4735,8 @@ class AppLocalizationsPt extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b1e9018c..f808604f 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -4743,8 +4743,8 @@ class AppLocalizationsRu extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 00202f9c..12977b44 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -4716,8 +4716,8 @@ class AppLocalizationsSk extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 8956df64..9b629d4a 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -4714,8 +4714,8 @@ class AppLocalizationsSl extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 4f8d8f1f..129ddf72 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -4690,8 +4690,8 @@ class AppLocalizationsSv extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 84d0c651..1d425252 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -4742,8 +4742,8 @@ class AppLocalizationsUk extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index d0eb24b2..fa67ef7d 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -4410,8 +4410,8 @@ class AppLocalizationsZh extends AppLocalizations { String get notification_lowBatteryTitle => 'Low battery'; @override - String notification_lowBatteryBody(int percent) { - return 'Device battery is at $percent%'; + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; } @override diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 62802917..334240c6 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -600,10 +600,13 @@ class NotificationService { /// Posts a low-battery alert for the connected device. /// - /// Uses a per-threshold notification id so each alert level updates its own - /// notification instead of stacking. Bypasses the rate-limit queue, which - /// only handles message and advert notifications. + /// Uses a per-device, per-threshold notification id so each alert level + /// updates its own notification instead of stacking, and alerts for + /// different radios don't overwrite each other. Bypasses the rate-limit + /// queue, which only handles message and advert notifications. Future showLowBatteryNotification({ + required String deviceKey, + required String deviceName, required int batteryPercent, required int threshold, }) async { @@ -632,9 +635,9 @@ class NotificationService { try { await _notifications.show( - id: 'low_battery:$threshold'.hashCode, + id: _lowBatteryNotificationId(deviceKey, threshold), title: _l10n.notification_lowBatteryTitle, - body: _l10n.notification_lowBatteryBody(batteryPercent), + body: _l10n.notification_lowBatteryBody(deviceName, batteryPercent), notificationDetails: notificationDetails, payload: 'low_battery', ); @@ -699,6 +702,26 @@ class NotificationService { await _updateBadge(totalUnreadCount); } + static int _lowBatteryNotificationId(String deviceKey, int threshold) => + 'low_battery:$deviceKey:$threshold'.hashCode; + + /// Cancel a device's low-battery notifications for the given thresholds. + Future clearLowBatteryNotifications( + String deviceKey, + Iterable thresholds, + ) async { + if (!await _ensureInitialized()) return; + for (final threshold in thresholds) { + try { + await _notifications.cancel( + id: _lowBatteryNotificationId(deviceKey, threshold), + ); + } catch (e) { + debugPrint('Failed to clear low battery notification: $e'); + } + } + } + /// Cancel advert notifications for the given contact public key hexes. Future clearAdvertNotifications(List contactIds) async { if (!await _ensureInitialized()) return; From f66732060888b1baa38346cf8c2cdd6a7d2eac88 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 20:46:49 -0700 Subject: [PATCH 21/67] Fix review findings in channel notification modes - Detect mentions on the original text, as @[name] or a whole-word @name - Save and restore the full mode map in review mode - Open the mode picker from the chat bell and show the mode in its tooltip - Share one mode picker sheet; fix the stale sheet context - Persist modes by name and skip unknown entries - Keep writing muted_channels so older builds keep the user's mutes - Remove the muteChannel/unmuteChannel/isChannelMuted shims - Update notifications docs to match the behaviour --- documentation/notifications.md | 11 +- lib/connector/meshcore_connector.dart | 39 +++--- lib/l10n/app_en.arb | 8 ++ lib/l10n/app_localizations.dart | 6 + lib/l10n/app_localizations_bg.dart | 5 + lib/l10n/app_localizations_de.dart | 5 + lib/l10n/app_localizations_en.dart | 5 + lib/l10n/app_localizations_es.dart | 5 + lib/l10n/app_localizations_fr.dart | 5 + lib/l10n/app_localizations_hu.dart | 5 + lib/l10n/app_localizations_it.dart | 5 + lib/l10n/app_localizations_ja.dart | 5 + lib/l10n/app_localizations_ko.dart | 5 + lib/l10n/app_localizations_nl.dart | 5 + lib/l10n/app_localizations_pl.dart | 5 + lib/l10n/app_localizations_pt.dart | 5 + lib/l10n/app_localizations_ru.dart | 5 + lib/l10n/app_localizations_sk.dart | 5 + lib/l10n/app_localizations_sl.dart | 5 + lib/l10n/app_localizations_sv.dart | 5 + lib/l10n/app_localizations_uk.dart | 5 + lib/l10n/app_localizations_zh.dart | 5 + lib/models/app_settings.dart | 24 ++-- lib/review_mode/review_mode_storage.dart | 59 ++++----- lib/screens/channel_chat_screen.dart | 22 +--- lib/screens/channels_screen.dart | 92 ++------------ lib/services/app_settings_service.dart | 22 +--- .../channel_notification_mode_sheet.dart | 65 ++++++++++ test/connector/mention_detection_test.dart | 33 +++++ .../channel_notification_modes_json_test.dart | 37 ++++++ .../review_mode_settings_revert_test.dart | 120 ++++++++++++++++-- untranslated.json | 70 +++++++++- 32 files changed, 502 insertions(+), 196 deletions(-) create mode 100644 lib/widgets/channel_notification_mode_sheet.dart create mode 100644 test/connector/mention_detection_test.dart create mode 100644 test/models/channel_notification_modes_json_test.dart diff --git a/documentation/notifications.md b/documentation/notifications.md index 8bdc5d6c..12c44f6c 100644 --- a/documentation/notifications.md +++ b/documentation/notifications.md @@ -42,7 +42,7 @@ Message notifications can be answered without opening the app, from the notifica - **Reply** sends through the connected radio exactly like the chat screen: same length limits, SMAZ and Cyr2Lat handling, and retries. Your reply is then added to the notification. - **Replies over the message limit** are split at word boundaries into up to 3 messages. Longer replies are not sent; a "Reply not sent" notification asks you to open the app. - **Mark as read** clears the unread count on the phone only. MeshCore has no read receipts, so nothing is sent over the mesh. -- **Mute channel** (phone and watch) mutes that channel, the same as the bell icon in the channel chat. +- **Mute channel** (phone and watch) sets that channel to **Muted**, the same as choosing Muted from the bell icon in the channel chat. - If the radio is disconnected, the conversation is no longer on the radio, the radio reports a send error, or the app isn't running, a "Reply not sent" notification explains why. The reply is not queued. If a split reply fails partway, earlier parts may already have been sent. - Replies are sent as typed; composer translation is not applied. @@ -106,16 +106,17 @@ Each channel supports three notification modes: | Mode | Icon | Behavior | |---|---|---| | **All messages** | 🔔 | Receive notifications for every message | -| **Mentions only** | 🔔! | Only notify when someone mentions you with "@[yourname]" | +| **Mentions only** | 🔔! | Only notify when a message mentions your name (see below) | | **Muted** | 🔕 | No notifications | Set the mode from: -- The notifications icon in the channel chat app bar (tap to cycle through modes) +- The notifications icon in the channel chat app bar (tap to open the mode picker) - Long-press a channel in the channels list → **Notification settings** → select mode -- Channel notification actions (Android) -Mentions are detected by looking for "@[yourname]" (username in brackets, case-insensitive). +The Android **Mute channel** notification action sets the channel to **Muted**; it cannot choose another mode. + +A message mentions you if it contains `@[yourname]` or `@yourname`, case-insensitively. The plain `@yourname` form must stand alone as a word, so `@bobby` does not mention `bob` and `x@bob.com` is not a mention; names with spaces must be written in full. Detection (`MeshCoreConnector.textMentionsName`) runs on the original text, before any automatic translation. ## Rate Limiting diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 7777d60f..e17864b3 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -1247,8 +1247,9 @@ class MeshCoreConnector extends ChangeNotifier { /// (notification shade, watch, or Android Auto). Future handleNotificationReply(NotificationReply reply) async { if (reply.action == NotificationReplyAction.mute) { - await _appSettingsService?.muteChannel( + await _appSettingsService?.setChannelNotificationMode( _channelDisplayName(reply.channelIndex!), + ChannelNotificationMode.muted, ); await _notificationService.clearChannelNotification( reply.channelIndex!, @@ -7369,9 +7370,11 @@ class MeshCoreConnector extends ChangeNotifier { ? translationResult.translatedText.trim() : message.text.trim(); - // If mode is mentionsOnly, check if message mentions us + // Mentions are matched on the untranslated text. if (notificationMode == ChannelNotificationMode.mentionsOnly) { - if (!_doesMessageMentionUs(resolvedText, message)) return; + if (!textMentionsName(message.originalText ?? message.text, _selfName)) { + return; + } } unawaited(() async { @@ -7386,22 +7389,20 @@ class MeshCoreConnector extends ChangeNotifier { }()); } - /// Checks if a message mentions the current user. - /// Detects: @[username] format only. - bool _doesMessageMentionUs(String messageText, ChannelMessage message) { - final selfName = _selfName; - final lowerMessage = messageText.toLowerCase(); - - // Check for @[username] pattern (bracketed mention format) - if (selfName != null && selfName.isNotEmpty) { - final lowerSelfName = selfName.toLowerCase(); - final bracketedMentionPattern = RegExp( - r'@\[(' + RegExp.escape(lowerSelfName) + r')\]', - ); - if (bracketedMentionPattern.hasMatch(lowerMessage)) return true; - } - - return false; + /// Whether [text] mentions [name], case-insensitively, as either + /// `@[name]` (the reply/mention prefix the app sends) or a plain `@name`. + /// The plain form needs a word boundary on both sides, so `@bobby` does + /// not mention `bob` and `x@bob.com` is not a mention. Names containing + /// spaces must be written out in full. + @visibleForTesting + static bool textMentionsName(String text, String? name) { + if (name == null || name.isEmpty) return false; + final escaped = RegExp.escape(name); + return RegExp( + '@\\[$escaped\\]|(? 'Заглушено'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Заглуши канала'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 9d7a3f43..c4f916bc 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1470,6 +1470,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_notifyNone => 'Stummgeschaltet'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Kanal stummschalten'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index fb20008b..d025517b 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1450,6 +1450,11 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_notifyNone => 'Muted'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Mute channel'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index e1ad4fa2..dc83cb6d 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1469,6 +1469,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_notifyNone => 'Silenciado'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Silenciar canal'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index f3318265..5b58c565 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1474,6 +1474,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_notifyNone => 'Désactivé'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Désactiver les notifications du canal'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 21d40309..e5860865 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1465,6 +1465,11 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_notifyNone => 'Némít'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Csatorna némítása'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index fdc44f4a..1f69f454 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1473,6 +1473,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_notifyNone => 'Silenziato'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Silenzia canale'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 80aa0c8d..ec3494d3 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1397,6 +1397,11 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_notifyNone => 'ミュート'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'チャンネルをミュート'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 90181a0c..b7dc254d 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1402,6 +1402,11 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_notifyNone => '음소거'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => '음소거 채널'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index b4c40d64..aed45fff 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1461,6 +1461,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_notifyNone => 'Gedempt'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Kanaal dempen'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 10fe2d7f..02747e57 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1487,6 +1487,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_notifyNone => 'Wyciszone'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Wycisz kanał'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 2a9ceae6..b248889c 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1472,6 +1472,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_notifyNone => 'Silenciado'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Silenciar canal'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index f8eb322b..1f53e6f7 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1476,6 +1476,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_notifyNone => 'Без звука'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Отключить уведомления канала'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 46b074bd..159f6751 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1464,6 +1464,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_notifyNone => 'Stíšené'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Stlmiť kanál'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 696b59f9..2dc95d5d 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1462,6 +1462,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_notifyNone => 'Utišano'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Utišaj kanal'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 1593d3de..7e18cea8 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1451,6 +1451,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_notifyNone => 'Tyst'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Tysta kanal'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 369dda90..4eef0bb5 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1467,6 +1467,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_notifyNone => 'Вимкнено'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => 'Вимкнути сповіщення каналу'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index ac397a39..b2b407f6 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1379,6 +1379,11 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_notifyNone => '静音'; + @override + String channels_notificationModeTooltip(String mode) { + return 'Notifications: $mode'; + } + @override String get channels_muteChannel => '静音频道'; diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 612905ec..f664f083 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -198,12 +198,6 @@ class AppSettings { return profile.charMap; } - // Backward compatibility: returns true if channel is muted (mode == muted) - bool isChannelMuted(String channelName) { - return channelNotificationModes[channelName] == - ChannelNotificationMode.muted; - } - AppSettings({ this.clearPathOnMaxRetry = false, this.mapShowRepeaters = true, @@ -330,8 +324,13 @@ class AppSettings { 'battery_chemistry_by_device_id': batteryChemistryByDeviceId, 'battery_chemistry_by_repeater_id': batteryChemistryByRepeaterId, 'unit_system': unitSystem.value, + // Written for older builds that only read the muted set. + 'muted_channels': [ + for (final entry in channelNotificationModes.entries) + if (entry.value == ChannelNotificationMode.muted) entry.key, + ], 'channel_notification_modes': channelNotificationModes.map( - (key, value) => MapEntry(key, value.index), + (key, value) => MapEntry(key, value.name), ), 'map_show_discovery_contacts': mapShowDiscoveryContacts, 'evict_discovered_contacts_enabled': evictDiscoveredContactsEnabled, @@ -392,13 +391,10 @@ class AppSettings { // Load new modes (overrides old muted channels if present) if (newModes != null) { for (final entry in newModes.entries) { - final channelName = entry.key; - final modeIndex = entry.value as int?; - if (modeIndex != null && - modeIndex >= 0 && - modeIndex < ChannelNotificationMode.values.length) { - result[channelName] = ChannelNotificationMode.values[modeIndex]; - } + final value = entry.value; + if (value is! String) continue; + final mode = ChannelNotificationMode.values.asNameMap()[value]; + if (mode != null) result[entry.key.toString()] = mode; } } diff --git a/lib/review_mode/review_mode_storage.dart b/lib/review_mode/review_mode_storage.dart index e0a02bb4..de787edb 100644 --- a/lib/review_mode/review_mode_storage.dart +++ b/lib/review_mode/review_mode_storage.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import '../services/app_settings_service.dart' show AppSettingsService, ChannelNotificationMode; import '../services/storage_service.dart'; @@ -6,9 +8,10 @@ import '../storage/legacy_key_migration.dart'; import '../storage/prefs_manager.dart'; import 'review_radio.dart'; -/// Muted channel names as they were when review mode started. Persisted so an -/// interrupted session (crash, app killed) is still undone on the next launch. -const _savedMutedChannelsKey = 'review_mode_saved_muted_channels'; +/// Channel notification modes (JSON map of channel name to mode name) as they +/// were when review mode started. Persisted so an interrupted session (crash, +/// app killed) is still undone on the next launch. +const _savedChannelModesKey = 'review_mode_saved_channel_modes'; /// Prefix for snapshots of app-wide repeater keys (saved passwords, clock sync /// toggles) taken when review mode starts. An empty snapshot means the key did @@ -32,10 +35,11 @@ Future clearReviewModeData() async { /// Starts a review session from a clean slate. /// /// The simulated radio's scope never adopts legacy unscoped keys, so real -/// radio data cannot be pulled into it. Channel mutes are app-wide and keyed -/// by channel name (muting the simulated "Public" would mute the real one), -/// so the current mutes are saved for [endReviewModeSession] to put back, as -/// are the app-wide repeater keys. Delivery timing is not recorded meanwhile. +/// radio data cannot be pulled into it. Channel notification modes are +/// app-wide and keyed by channel name (muting the simulated "Public" would +/// mute the real one), so the current modes are saved for +/// [endReviewModeSession] to put back, as are the app-wide repeater keys. +/// Delivery timing is not recorded meanwhile. Future beginReviewModeSession(AppSettingsService? settings) async { scopesWithoutLegacyMigration.add(ReviewRadio.storagePrefix); TimeoutPredictionService.recordingSuspended = true; @@ -48,19 +52,16 @@ Future beginReviewModeSession(AppSettingsService? settings) async { await prefs.setString(savedKey, prefs.getString(key) ?? ''); } // An earlier interrupted session's record holds the real pre-review state. - if (settings != null && !prefs.containsKey(_savedMutedChannelsKey)) { - // Save all channel notification modes - final channelModes = settings.settings.channelNotificationModes; - final mutedChannels = channelModes.entries - .where((e) => e.value == ChannelNotificationMode.muted) - .map((e) => e.key) - .toList(); - await prefs.setStringList(_savedMutedChannelsKey, mutedChannels); + if (settings != null && !prefs.containsKey(_savedChannelModesKey)) { + final modes = settings.settings.channelNotificationModes.map( + (channel, mode) => MapEntry(channel, mode.name), + ); + await prefs.setString(_savedChannelModesKey, jsonEncode(modes)); } } -/// Deletes the review session's data and restores the channel mutes and -/// repeater keys saved by [beginReviewModeSession]. Also called at startup to finish a session that +/// Deletes the review session's data and restores the channel notification +/// modes and repeater keys saved by [beginReviewModeSession]. Also called at startup to finish a session that /// was interrupted; it does nothing when no session was left behind. Future endReviewModeSession(AppSettingsService? settings) async { TimeoutPredictionService.recordingSuspended = false; @@ -77,19 +78,19 @@ Future endReviewModeSession(AppSettingsService? settings) async { } await prefs.remove(savedKey); } - final savedMutes = prefs.getStringList(_savedMutedChannelsKey); - if (savedMutes == null || settings == null) return; - final updatedModes = Map.from( - settings.settings.channelNotificationModes, - ); - updatedModes.removeWhere( - (key, value) => value == ChannelNotificationMode.muted, - ); - for (final channelName in savedMutes) { - updatedModes[channelName] = ChannelNotificationMode.muted; + final savedModes = prefs.getString(_savedChannelModesKey); + if (savedModes == null || settings == null) return; + final restored = {}; + final decoded = jsonDecode(savedModes); + if (decoded is Map) { + final byName = ChannelNotificationMode.values.asNameMap(); + for (final entry in decoded.entries) { + final mode = byName[entry.value]; + if (mode != null) restored[entry.key.toString()] = mode; + } } await settings.updateSettings( - settings.settings.copyWith(channelNotificationModes: updatedModes), + settings.settings.copyWith(channelNotificationModes: restored), ); - await prefs.remove(_savedMutedChannelsKey); + await prefs.remove(_savedChannelModesKey); } diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 0a8238b8..7f5049dd 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -37,6 +37,7 @@ import '../utils/image_save.dart'; import '../utils/lora_airtime.dart'; import '../widgets/marker_label_dialog.dart'; import '../widgets/received_image_message.dart'; +import '../widgets/channel_notification_mode_sheet.dart'; import '../widgets/chat_day_separator.dart'; import '../widgets/empty_state.dart'; @@ -408,7 +409,9 @@ class _ChannelChatScreenState extends State { muteKey, ); return IconButton( - tooltip: context.l10n.channels_notificationSettings, + tooltip: context.l10n.channels_notificationModeTooltip( + channelNotificationModeLabel(context, notificationMode), + ), icon: Icon( notificationMode == ChannelNotificationMode.muted ? Icons.notifications_off @@ -416,21 +419,8 @@ class _ChannelChatScreenState extends State { ? Icons.notification_important : Icons.notifications, ), - onPressed: () { - final currentMode = settings.getChannelNotificationMode( - muteKey, - ); - ChannelNotificationMode newMode; - if (currentMode == ChannelNotificationMode.all) { - newMode = ChannelNotificationMode.mentionsOnly; - } else if (currentMode == - ChannelNotificationMode.mentionsOnly) { - newMode = ChannelNotificationMode.muted; - } else { - newMode = ChannelNotificationMode.all; - } - settings.setChannelNotificationMode(muteKey, newMode); - }, + onPressed: () => + showChannelNotificationModeSheet(context, muteKey), ); }, ), diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index beaac2cc..53d561ac 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -20,6 +20,7 @@ import '../theme/mesh_theme.dart'; import '../utils/dialog_utils.dart'; import '../utils/disconnect_navigation_mixin.dart'; import '../utils/route_transitions.dart'; +import '../widgets/channel_notification_mode_sheet.dart'; import '../widgets/list_filter_widget.dart'; import '../widgets/empty_state.dart'; import '../widgets/mesh_ui.dart'; @@ -583,9 +584,7 @@ class _ChannelsScreenState extends State children: [ if (notificationMode != ChannelNotificationMode.all) ...[ Icon( - notificationMode == ChannelNotificationMode.muted - ? Icons.notifications_off - : Icons.notification_important, + channelNotificationModeIcon(notificationMode), size: 18, color: scheme.onSurfaceVariant, ), @@ -651,9 +650,15 @@ class _ChannelsScreenState extends State leading: const Icon(Icons.notifications_outlined), title: Text(sheetContext.l10n.channels_notificationSettings), trailing: const Icon(Icons.chevron_right), - onTap: () { + onTap: () async { Navigator.pop(sheetContext); - _showNotificationModeDialog(sheetContext, connector, channel); + await Future.delayed(const Duration(milliseconds: 100)); + if (parentContext.mounted) { + showChannelNotificationModeSheet( + parentContext, + channel.muteKey, + ); + } }, ), ListTile( @@ -681,83 +686,6 @@ class _ChannelsScreenState extends State ); } - void _showNotificationModeDialog( - BuildContext context, - MeshCoreConnector connector, - Channel channel, - ) { - final settingsService = context.read(); - final currentMode = settingsService.getChannelNotificationMode( - channel.muteKey, - ); - - showMeshSheet( - context, - builder: (sheetContext) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // All notifications - ListTile( - leading: Icon( - Icons.notifications, - color: currentMode == ChannelNotificationMode.all - ? Theme.of(sheetContext).colorScheme.primary - : Theme.of(sheetContext).colorScheme.onSurfaceVariant, - ), - title: Text(sheetContext.l10n.channels_notifyAll), - trailing: currentMode == ChannelNotificationMode.all - ? const Icon(Icons.check) - : null, - onTap: () async { - Navigator.pop(sheetContext); - await settingsService.setChannelNotificationMode( - channel.muteKey, - ChannelNotificationMode.all, - ); - }, - ), - // Mentions only - ListTile( - leading: const Icon(Icons.notification_important), - title: Text(sheetContext.l10n.channels_notifyMentionsOnly), - trailing: currentMode == ChannelNotificationMode.mentionsOnly - ? const Icon(Icons.check) - : null, - onTap: () async { - Navigator.pop(sheetContext); - await settingsService.setChannelNotificationMode( - channel.muteKey, - ChannelNotificationMode.mentionsOnly, - ); - }, - ), - // Muted - ListTile( - leading: Icon( - Icons.notifications_off, - color: currentMode == ChannelNotificationMode.muted - ? Theme.of(sheetContext).colorScheme.primary - : Theme.of(sheetContext).colorScheme.onSurfaceVariant, - ), - title: Text(sheetContext.l10n.channels_notifyNone), - trailing: currentMode == ChannelNotificationMode.muted - ? const Icon(Icons.check) - : null, - onTap: () async { - Navigator.pop(sheetContext); - await settingsService.setChannelNotificationMode( - channel.muteKey, - ChannelNotificationMode.muted, - ); - }, - ), - ], - ), - ), - ); - } - void _handleQuickSwitch(int index, BuildContext context) { if (index == 1) return; switch (index) { diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 5bddabae..d5d4b433 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -288,11 +288,6 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(unitSystem: value)); } - // Backward compatibility: delegates to AppSettings.isChannelMuted - bool isChannelMuted(String channelName) { - return _settings.isChannelMuted(channelName); - } - ChannelNotificationMode getChannelNotificationMode(String channelName) { return _settings.channelNotificationModes[channelName] ?? ChannelNotificationMode.all; @@ -305,21 +300,14 @@ class AppSettingsService extends ChangeNotifier { final updated = Map.from( _settings.channelNotificationModes, ); - updated[channelName] = mode; + if (mode == ChannelNotificationMode.all) { + updated.remove(channelName); + } else { + updated[channelName] = mode; + } await updateSettings(_settings.copyWith(channelNotificationModes: updated)); } - Future muteChannel(String channelName) async { - await setChannelNotificationMode( - channelName, - ChannelNotificationMode.muted, - ); - } - - Future unmuteChannel(String channelName) async { - await setChannelNotificationMode(channelName, ChannelNotificationMode.all); - } - Future setTcpServerAddress(String value) async { await updateSettings(_settings.copyWith(tcpServerAddress: value)); } diff --git a/lib/widgets/channel_notification_mode_sheet.dart b/lib/widgets/channel_notification_mode_sheet.dart new file mode 100644 index 00000000..9239aff2 --- /dev/null +++ b/lib/widgets/channel_notification_mode_sheet.dart @@ -0,0 +1,65 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../l10n/l10n.dart'; +import '../services/app_settings_service.dart' + show AppSettingsService, ChannelNotificationMode; +import 'mesh_ui.dart'; + +/// Localized label for a channel notification [mode]. +String channelNotificationModeLabel( + BuildContext context, + ChannelNotificationMode mode, +) => switch (mode) { + ChannelNotificationMode.all => context.l10n.channels_notifyAll, + ChannelNotificationMode.mentionsOnly => + context.l10n.channels_notifyMentionsOnly, + ChannelNotificationMode.muted => context.l10n.channels_notifyNone, +}; + +/// Icon for a channel notification [mode]. +IconData channelNotificationModeIcon(ChannelNotificationMode mode) => + switch (mode) { + ChannelNotificationMode.all => Icons.notifications, + ChannelNotificationMode.mentionsOnly => Icons.notification_important, + ChannelNotificationMode.muted => Icons.notifications_off, + }; + +/// Shows the per-channel notification mode picker (all / mentions only / +/// muted) for the channel identified by [muteKey]. +void showChannelNotificationModeSheet(BuildContext context, String muteKey) { + final settingsService = context.read(); + final currentMode = settingsService.getChannelNotificationMode(muteKey); + + showMeshSheet( + context, + builder: (sheetContext) { + final scheme = Theme.of(sheetContext).colorScheme; + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final mode in ChannelNotificationMode.values) + ListTile( + leading: Icon( + channelNotificationModeIcon(mode), + color: mode == currentMode + ? scheme.primary + : scheme.onSurfaceVariant, + ), + title: Text(channelNotificationModeLabel(sheetContext, mode)), + trailing: mode == currentMode ? const Icon(Icons.check) : null, + onTap: () async { + Navigator.pop(sheetContext); + await settingsService.setChannelNotificationMode( + muteKey, + mode, + ); + }, + ), + ], + ), + ); + }, + ); +} diff --git a/test/connector/mention_detection_test.dart b/test/connector/mention_detection_test.dart new file mode 100644 index 00000000..91e84e54 --- /dev/null +++ b/test/connector/mention_detection_test.dart @@ -0,0 +1,33 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; + +void main() { + bool mentions(String text, String? name) => + MeshCoreConnector.textMentionsName(text, name); + + test('matches bracketed and plain mentions case-insensitively', () { + expect(mentions('@[Bob] hello', 'Bob'), isTrue); + expect(mentions('hey @[bob]', 'Bob'), isTrue); + expect(mentions('hey @bob, look', 'Bob'), isTrue); + expect(mentions('@BOB', 'Bob'), isTrue); + expect(mentions('ping @Иван!', 'иван'), isTrue); + }); + + test('requires a word boundary for plain mentions', () { + expect(mentions('hey @bobby', 'Bob'), isFalse); + expect(mentions('mail x@bob.com', 'Bob'), isFalse); + expect(mentions('hey bob', 'Bob'), isFalse); + }); + + test('names with spaces or regex characters must match in full', () { + expect(mentions('hi @Bob Smith', 'Bob Smith'), isTrue); + expect(mentions('hi @Bob', 'Bob Smith'), isFalse); + expect(mentions('@[Node (1)] ok', 'Node (1)'), isTrue); + expect(mentions('@[Node 1] ok', 'Node (1)'), isFalse); + }); + + test('no self name never matches', () { + expect(mentions('@[Bob] hi', null), isFalse); + expect(mentions('@ hi', ''), isFalse); + }); +} diff --git a/test/models/channel_notification_modes_json_test.dart b/test/models/channel_notification_modes_json_test.dart new file mode 100644 index 00000000..abd2bbef --- /dev/null +++ b/test/models/channel_notification_modes_json_test.dart @@ -0,0 +1,37 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/app_settings.dart'; + +void main() { + test('channel notification modes round-trip by name', () { + final settings = AppSettings( + channelNotificationModes: { + 'a': ChannelNotificationMode.mentionsOnly, + 'b': ChannelNotificationMode.muted, + }, + ); + final json = settings.toJson(); + expect(json['channel_notification_modes'], { + 'a': 'mentionsOnly', + 'b': 'muted', + }); + expect(json['muted_channels'], ['b']); + expect( + AppSettings.fromJson(json).channelNotificationModes, + settings.channelNotificationModes, + ); + }); + + test('invalid channel notification mode entries are skipped', () { + final settings = AppSettings.fromJson({ + 'channel_notification_modes': { + 'ok': 'muted', + 'unknown': 'loud', + 'int': 2, + 'null': null, + }, + }); + expect(settings.channelNotificationModes, { + 'ok': ChannelNotificationMode.muted, + }); + }); +} diff --git a/test/review_mode/review_mode_settings_revert_test.dart b/test/review_mode/review_mode_settings_revert_test.dart index fcd6ce3c..493163dd 100644 --- a/test/review_mode/review_mode_settings_revert_test.dart +++ b/test/review_mode/review_mode_settings_revert_test.dart @@ -24,7 +24,10 @@ void main() { test('channel mutes made in review mode are undone on exit', () async { final settings = AppSettingsService(); await settings.loadSettings(); - await settings.muteChannel('Hiking Group'); + await settings.setChannelNotificationMode( + 'Hiking Group', + ChannelNotificationMode.muted, + ); final connector = MeshCoreConnector(); addTearDown(connector.dispose); final retryService = MessageRetryService(); @@ -39,23 +42,41 @@ void main() { await connector.connectReview(); // Mutes are keyed by channel name, so these would leak into real radios. - await settings.muteChannel('Public'); - await settings.unmuteChannel('Hiking Group'); + await settings.setChannelNotificationMode( + 'Public', + ChannelNotificationMode.muted, + ); + await settings.setChannelNotificationMode( + 'Hiking Group', + ChannelNotificationMode.all, + ); // Other app preferences are the user's to change, even while reviewing. await PrefsManager.instance.setString('unrelated_key', 'changed'); await connector.disconnect(manual: true); - expect(settings.isChannelMuted('Public'), isFalse); - expect(settings.isChannelMuted('Hiking Group'), isTrue); + expect( + settings.getChannelNotificationMode('Public'), + ChannelNotificationMode.all, + ); + expect( + settings.getChannelNotificationMode('Hiking Group'), + ChannelNotificationMode.muted, + ); expect(PrefsManager.instance.getString('unrelated_key'), 'changed'); // A fresh launch has nothing left to undo. final relaunched = AppSettingsService(); await relaunched.loadSettings(); await endReviewModeSession(relaunched); - expect(relaunched.isChannelMuted('Public'), isFalse); - expect(relaunched.isChannelMuted('Hiking Group'), isTrue); + expect( + relaunched.getChannelNotificationMode('Public'), + ChannelNotificationMode.all, + ); + expect( + relaunched.getChannelNotificationMode('Hiking Group'), + ChannelNotificationMode.muted, + ); }); test( @@ -63,11 +84,20 @@ void main() { () async { final settings = AppSettingsService(); await settings.loadSettings(); - await settings.muteChannel('Hiking Group'); + await settings.setChannelNotificationMode( + 'Hiking Group', + ChannelNotificationMode.muted, + ); await beginReviewModeSession(settings); - await settings.muteChannel('Public'); - await settings.unmuteChannel('Hiking Group'); + await settings.setChannelNotificationMode( + 'Public', + ChannelNotificationMode.muted, + ); + await settings.setChannelNotificationMode( + 'Hiking Group', + ChannelNotificationMode.all, + ); await PrefsManager.instance.setString( 'contacts${ReviewRadio.storagePrefix}', '[]', @@ -76,11 +106,20 @@ void main() { final relaunched = AppSettingsService(); await relaunched.loadSettings(); - expect(relaunched.isChannelMuted('Public'), isTrue); + expect( + relaunched.getChannelNotificationMode('Public'), + ChannelNotificationMode.muted, + ); await endReviewModeSession(relaunched); - expect(relaunched.isChannelMuted('Public'), isFalse); - expect(relaunched.isChannelMuted('Hiking Group'), isTrue); + expect( + relaunched.getChannelNotificationMode('Public'), + ChannelNotificationMode.all, + ); + expect( + relaunched.getChannelNotificationMode('Hiking Group'), + ChannelNotificationMode.muted, + ); expect( PrefsManager.instance.getKeys().where( (k) => k.contains(ReviewRadio.storagePrefix), @@ -90,6 +129,61 @@ void main() { }, ); + test('every channel notification mode is restored on exit', () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.setChannelNotificationMode( + 'Hiking Group', + ChannelNotificationMode.mentionsOnly, + ); + await settings.setChannelNotificationMode( + 'Noisy', + ChannelNotificationMode.muted, + ); + + await beginReviewModeSession(settings); + await settings.setChannelNotificationMode( + 'Hiking Group', + ChannelNotificationMode.all, + ); + await settings.setChannelNotificationMode( + 'Noisy', + ChannelNotificationMode.mentionsOnly, + ); + await settings.setChannelNotificationMode( + 'Public', + ChannelNotificationMode.mentionsOnly, + ); + await endReviewModeSession(settings); + + expect( + settings.getChannelNotificationMode('Hiking Group'), + ChannelNotificationMode.mentionsOnly, + ); + expect( + settings.getChannelNotificationMode('Noisy'), + ChannelNotificationMode.muted, + ); + expect( + settings.getChannelNotificationMode('Public'), + ChannelNotificationMode.all, + ); + }); + + test('setting a channel back to all drops its stored mode', () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.setChannelNotificationMode( + 'Public', + ChannelNotificationMode.muted, + ); + await settings.setChannelNotificationMode( + 'Public', + ChannelNotificationMode.all, + ); + expect(settings.settings.channelNotificationModes, isEmpty); + }); + test('the review scope never adopts legacy unscoped data', () async { await PrefsManager.instance.setString('contacts', '[]'); await beginReviewModeSession(null); diff --git a/untranslated.json b/untranslated.json index 9e26dfee..f140f78b 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,69 @@ -{} \ No newline at end of file +{ + "bg": [ + "channels_notificationModeTooltip" + ], + + "de": [ + "channels_notificationModeTooltip" + ], + + "es": [ + "channels_notificationModeTooltip" + ], + + "fr": [ + "channels_notificationModeTooltip" + ], + + "hu": [ + "channels_notificationModeTooltip" + ], + + "it": [ + "channels_notificationModeTooltip" + ], + + "ja": [ + "channels_notificationModeTooltip" + ], + + "ko": [ + "channels_notificationModeTooltip" + ], + + "nl": [ + "channels_notificationModeTooltip" + ], + + "pl": [ + "channels_notificationModeTooltip" + ], + + "pt": [ + "channels_notificationModeTooltip" + ], + + "ru": [ + "channels_notificationModeTooltip" + ], + + "sk": [ + "channels_notificationModeTooltip" + ], + + "sl": [ + "channels_notificationModeTooltip" + ], + + "sv": [ + "channels_notificationModeTooltip" + ], + + "uk": [ + "channels_notificationModeTooltip" + ], + + "zh": [ + "channels_notificationModeTooltip" + ] +} From 92b147bd4920a5ab187ec970e29ee1e09833c65b Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 20:57:30 -0700 Subject: [PATCH 22/67] Format tcp_transport_service_native_test --- .../tcp_transport_service_native_test.dart | 52 ++++++++++--------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/test/services/tcp_transport_service_native_test.dart b/test/services/tcp_transport_service_native_test.dart index 72edf22e..3cb9629c 100644 --- a/test/services/tcp_transport_service_native_test.dart +++ b/test/services/tcp_transport_service_native_test.dart @@ -61,30 +61,34 @@ int _readIntOption(Socket socket, int level, int option) { } void main() { - test('connect enables TCP keepalive with short probe timings', () async { - final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); - final overrides = _CapturingConnectOverrides(); - final service = TcpTransportService(); - try { - await IOOverrides.runZoned( - () => service.connect( - host: InternetAddress.loopbackIPv4.address, - port: server.port, - ), - socketConnect: overrides.socketConnect, - ); - final socket = overrides.socket!; - // Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5, - // TCP_KEEPCNT 6. - expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3); - } finally { - await service.disconnect(); - await server.close(); - } - }, skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones'); + test( + 'connect enables TCP keepalive with short probe timings', + () async { + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final overrides = _CapturingConnectOverrides(); + final service = TcpTransportService(); + try { + await IOOverrides.runZoned( + () => service.connect( + host: InternetAddress.loopbackIPv4.address, + port: server.port, + ), + socketConnect: overrides.socketConnect, + ); + final socket = overrides.socket!; + // Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5, + // TCP_KEEPCNT 6. + expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3); + } finally { + await service.disconnect(); + await server.close(); + } + }, + skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones', + ); test('connect/disconnect updates TCP transport state', () async { final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); From 918ab7f5a0e8fddbee167e0d45e6b54a909a89be Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 20:58:49 -0700 Subject: [PATCH 23/67] Keep the reaction picker above the system navigation bar Open the emoji picker through showMeshSheet, which pads the sheet by the navigation bar or keyboard, instead of a bare modal bottom sheet. --- lib/screens/channel_chat_screen.dart | 5 ++--- lib/screens/chat_screen.dart | 5 ++--- lib/widgets/emoji_picker.dart | 6 +----- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 358ea298..7aa0cd15 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -2307,9 +2307,8 @@ class _ChannelChatScreenState extends State { } void _showEmojiPicker(ChannelMessage message) { - showModalBottomSheet( - context: context, - isScrollControlled: true, + showMeshSheet( + context, builder: (context) => EmojiPicker( onEmojiSelected: (emoji) { _sendReaction(message, emoji); diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index c0c503b4..4f60fd79 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -1161,9 +1161,8 @@ class _ChatScreenState extends State { } void _showEmojiPicker(Message message, Contact senderContact) { - showModalBottomSheet( - context: context, - isScrollControlled: true, + showMeshSheet( + context, builder: (context) => EmojiPicker( onEmojiSelected: (emoji) { _sendReaction(message, senderContact, emoji); diff --git a/lib/widgets/emoji_picker.dart b/lib/widgets/emoji_picker.dart index ab5c4edd..a6ef87e1 100644 --- a/lib/widgets/emoji_picker.dart +++ b/lib/widgets/emoji_picker.dart @@ -210,12 +210,8 @@ class EmojiPicker extends StatelessWidget { Widget build(BuildContext context) { final l10n = context.l10n; final emojiCategories = _emojiCategories(l10n); - return Container( + return SizedBox( height: MediaQuery.of(context).size.height * 0.5, - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surface, - borderRadius: const BorderRadius.vertical(top: Radius.circular(20)), - ), child: Column( children: [ Padding( From 4c9705b3cb15cca3dbf106793a3ebeb61fe355fe Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 20:59:49 -0700 Subject: [PATCH 24/67] Keep the GIF picker above the system navigation bar Open the GIF picker through showMeshSheet so it is padded by the navigation bar or keyboard, and cap its height instead of fixing it so it shrinks when the keyboard is up. --- lib/widgets/chat_composer.dart | 6 +++--- lib/widgets/gif_picker.dart | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/widgets/chat_composer.dart b/lib/widgets/chat_composer.dart index 28cbf961..428381aa 100644 --- a/lib/widgets/chat_composer.dart +++ b/lib/widgets/chat_composer.dart @@ -9,6 +9,7 @@ import '../theme/mesh_theme.dart'; import 'byte_count_input.dart'; import 'gif_message.dart'; import 'gif_picker.dart'; +import 'mesh_ui.dart'; import 'message_translation_button.dart'; /// One entry of the composer's "+" menu. @@ -27,9 +28,8 @@ class ChatComposerAction { /// Opens the GIF picker and puts the chosen GIF into [controller]. void showChatGifPicker(BuildContext context, TextEditingController controller) { - showModalBottomSheet( - context: context, - isScrollControlled: true, + showMeshSheet( + context, builder: (context) => GifPicker( onGifSelected: (gifId) { controller.text = GifHelper.encodeGif(gifId); diff --git a/lib/widgets/gif_picker.dart b/lib/widgets/gif_picker.dart index e86ead15..dcd53c78 100644 --- a/lib/widgets/gif_picker.dart +++ b/lib/widgets/gif_picker.dart @@ -117,7 +117,9 @@ class _GifPickerState extends State { @override Widget build(BuildContext context) { return Container( - height: MediaQuery.of(context).size.height * 0.7, + constraints: BoxConstraints( + maxHeight: MediaQuery.of(context).size.height * 0.7, + ), padding: const EdgeInsets.all(16), child: Column( children: [ From c296597a2dd9ce9b335058a152e4732e5026d649 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 20:59:59 -0700 Subject: [PATCH 25/67] Show the routing key prefix on each contact Contacts now show the first path-hash-width bytes of their public key as a monospace badge before the path label, so they can be matched to hops in routing paths and told apart. The width follows the radio's path hash size setting. --- lib/l10n/app_en.arb | 2 + lib/l10n/app_localizations.dart | 6 ++ lib/l10n/app_localizations_bg.dart | 5 ++ lib/l10n/app_localizations_de.dart | 5 ++ lib/l10n/app_localizations_en.dart | 5 ++ lib/l10n/app_localizations_es.dart | 5 ++ lib/l10n/app_localizations_fr.dart | 5 ++ lib/l10n/app_localizations_hu.dart | 5 ++ lib/l10n/app_localizations_it.dart | 5 ++ lib/l10n/app_localizations_ja.dart | 5 ++ lib/l10n/app_localizations_ko.dart | 5 ++ lib/l10n/app_localizations_nl.dart | 5 ++ lib/l10n/app_localizations_pl.dart | 5 ++ lib/l10n/app_localizations_pt.dart | 5 ++ lib/l10n/app_localizations_ru.dart | 5 ++ lib/l10n/app_localizations_sk.dart | 5 ++ lib/l10n/app_localizations_sl.dart | 5 ++ lib/l10n/app_localizations_sv.dart | 5 ++ lib/l10n/app_localizations_uk.dart | 5 ++ lib/l10n/app_localizations_zh.dart | 5 ++ lib/models/contact.dart | 11 ++++ lib/screens/contacts_screen.dart | 43 ++++++++++++++- test/models/contact_key_prefix_test.dart | 33 +++++++++++ untranslated.json | 70 +++++++++++++++++++++++- 24 files changed, 253 insertions(+), 2 deletions(-) create mode 100644 test/models/contact_key_prefix_test.dart diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index f62a038b..713faace 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3437,6 +3437,8 @@ "@repeater_prvKeyLengthError": {"placeholders": {"length": {"type": "int"}}}, "contacts_advertFailed": "Couldn't send advertisement", "contacts_manageGroups": "Manage groups", + "contacts_keyPrefixSemantics": "Key prefix {prefix}", + "@contacts_keyPrefixSemantics": {"placeholders": {"prefix": {"type": "String"}}}, "community_shortId": "ID: {id}…", "@community_shortId": {"placeholders": {"id": {"type": "String"}}}, "tcpSectionTitle": "TCP / IP", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index b5e7efc5..0e518f54 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -10333,6 +10333,12 @@ abstract class AppLocalizations { /// **'Manage groups'** String get contacts_manageGroups; + /// No description provided for @contacts_keyPrefixSemantics. + /// + /// In en, this message translates to: + /// **'Key prefix {prefix}'** + String contacts_keyPrefixSemantics(String prefix); + /// No description provided for @community_shortId. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index b9f79a6f..c6415622 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -6166,6 +6166,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get contacts_manageGroups => 'Управление на групи'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index d7893ccf..c676dd50 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -6181,6 +6181,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get contacts_manageGroups => 'Gruppen verwalten'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0265ac8b..21530f6e 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -6080,6 +6080,11 @@ class AppLocalizationsEn extends AppLocalizations { @override String get contacts_manageGroups => 'Manage groups'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 75c2ab0e..8359564b 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -6169,6 +6169,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get contacts_manageGroups => 'Gestionar grupos'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 85de8bbb..38d3d2f1 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -6194,6 +6194,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get contacts_manageGroups => 'Gérer les groupes'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID : $id…'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index ef4b3d9b..49926094 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -6157,6 +6157,11 @@ class AppLocalizationsHu extends AppLocalizations { @override String get contacts_manageGroups => 'Csoportok kezelése'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 50bb49d9..131ceb14 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -6176,6 +6176,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get contacts_manageGroups => 'Gestisci gruppi'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 2aabf56e..1f80c37d 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -5878,6 +5878,11 @@ class AppLocalizationsJa extends AppLocalizations { @override String get contacts_manageGroups => 'グループを管理'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 98a81ac1..23d8c73b 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -5888,6 +5888,11 @@ class AppLocalizationsKo extends AppLocalizations { @override String get contacts_manageGroups => '그룹 관리'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 082f2a18..219a69b4 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -6136,6 +6136,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get contacts_manageGroups => 'Groepen beheren'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 3db02722..c6364e22 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -6200,6 +6200,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get contacts_manageGroups => 'Zarządzaj grupami'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 9b89ff31..65fe9656 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -6165,6 +6165,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get contacts_manageGroups => 'Gerenciar grupos'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index a1686804..2111d3e1 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -6186,6 +6186,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get contacts_manageGroups => 'Управление группами'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 9cd7cc6d..0e06e5b0 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -6148,6 +6148,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get contacts_manageGroups => 'Spravovať skupiny'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 8602eb0d..5ff3571c 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -6150,6 +6150,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get contacts_manageGroups => 'Upravljaj skupine'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 1d87483d..f3b28979 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -6116,6 +6116,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get contacts_manageGroups => 'Hantera grupper'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index ebd6d5eb..8e658ffd 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -6188,6 +6188,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get contacts_manageGroups => 'Керування групами'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID: $id…'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 703a27fe..31d2b20f 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5744,6 +5744,11 @@ class AppLocalizationsZh extends AppLocalizations { @override String get contacts_manageGroups => '管理分组'; + @override + String contacts_keyPrefixSemantics(String prefix) { + return 'Key prefix $prefix'; + } + @override String community_shortId(String id) { return 'ID:$id…'; diff --git a/lib/models/contact.dart b/lib/models/contact.dart index f079e028..a14d91b1 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -43,6 +43,17 @@ class Contact { String get publicKeyHex => pubKeyToHex(publicKey); + /// Uppercase hex of the first [byteWidth] public-key bytes: the hash this + /// node appears as in routing paths. + String publicKeyPrefixHex(int byteWidth) { + final width = byteWidth.clamp(1, 3).toInt(); + return publicKey + .take(width) + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join() + .toUpperCase(); + } + /// Non-localized type label, intended for logs and non-UI exports /// (e.g. GPX). For UI use the `typeLabel(l10n)` extension in /// `lib/l10n/contact_localization.dart`. diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index e7f8f4b0..9e25fa19 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -1884,9 +1884,13 @@ class _ContactTile extends StatelessWidget { ], ), const SizedBox(height: 3), - // Path / subtitle row + // Key prefix + path / subtitle row Row( children: [ + _KeyPrefixBadge( + prefix: contact.publicKeyPrefixHex(pathHashByteWidth), + ), + const SizedBox(width: 8), Expanded( child: Text( contact.pathLabel( @@ -1953,6 +1957,43 @@ class _ContactTile extends StatelessWidget { } } +/// Mono pill showing the contact's routing hash (public-key prefix), so it can +/// be matched against hops in paths. +class _KeyPrefixBadge extends StatelessWidget { + final String prefix; + + const _KeyPrefixBadge({required this.prefix}); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Semantics( + label: context.l10n.contacts_keyPrefixSemantics( + prefix.split('').join(' '), + ), + excludeSemantics: true, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(MeshRadii.xs), + border: Border.all(color: scheme.outline), + ), + child: Text( + prefix, + maxLines: 1, + style: MeshTheme.mono( + fontSize: 13, + fontWeight: FontWeight.w700, + color: scheme.onSurface, + letterSpacing: 0.6, + ), + ), + ), + ); + } +} + /// Disposes [controller] when the dialog content unmounts, i.e. after the /// route's exit animation, so the TextField never sees a disposed controller. class _DisposeControllerOnUnmount extends StatefulWidget { diff --git a/test/models/contact_key_prefix_test.dart b/test/models/contact_key_prefix_test.dart new file mode 100644 index 00000000..6698398c --- /dev/null +++ b/test/models/contact_key_prefix_test.dart @@ -0,0 +1,33 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; + +Contact _contact(List key) => Contact( + publicKey: Uint8List.fromList(key), + name: 'Node', + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), +); + +void main() { + final contact = _contact([0xA3, 0x0F, 0xB2, 0x44]); + + test('formats the first pathHashByteWidth bytes as uppercase hex', () { + expect(contact.publicKeyPrefixHex(1), 'A3'); + expect(contact.publicKeyPrefixHex(2), 'A30F'); + expect(contact.publicKeyPrefixHex(3), 'A30FB2'); + }); + + test('clamps width to the supported 1-3 range', () { + expect(contact.publicKeyPrefixHex(0), 'A3'); + expect(contact.publicKeyPrefixHex(4), 'A30FB2'); + }); + + test('handles keys shorter than the width', () { + expect(_contact([0x01]).publicKeyPrefixHex(3), '01'); + }); +} diff --git a/untranslated.json b/untranslated.json index 9e26dfee..f9d91c98 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,69 @@ -{} \ No newline at end of file +{ + "bg": [ + "contacts_keyPrefixSemantics" + ], + + "de": [ + "contacts_keyPrefixSemantics" + ], + + "es": [ + "contacts_keyPrefixSemantics" + ], + + "fr": [ + "contacts_keyPrefixSemantics" + ], + + "hu": [ + "contacts_keyPrefixSemantics" + ], + + "it": [ + "contacts_keyPrefixSemantics" + ], + + "ja": [ + "contacts_keyPrefixSemantics" + ], + + "ko": [ + "contacts_keyPrefixSemantics" + ], + + "nl": [ + "contacts_keyPrefixSemantics" + ], + + "pl": [ + "contacts_keyPrefixSemantics" + ], + + "pt": [ + "contacts_keyPrefixSemantics" + ], + + "ru": [ + "contacts_keyPrefixSemantics" + ], + + "sk": [ + "contacts_keyPrefixSemantics" + ], + + "sl": [ + "contacts_keyPrefixSemantics" + ], + + "sv": [ + "contacts_keyPrefixSemantics" + ], + + "uk": [ + "contacts_keyPrefixSemantics" + ], + + "zh": [ + "contacts_keyPrefixSemantics" + ] +} From 00756ef05efdd88a1749232af175477e10629810 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:00:06 -0700 Subject: [PATCH 26/67] Set my location by long-pressing the path maps Move the map's confirm-and-set-location flow into a shared helper and call it on long-press and right-click in the path trace and channel message path maps, so the self position can be set while viewing a path. --- lib/screens/channel_message_path_screen.dart | 5 ++ lib/screens/map_screen.dart | 69 +---------------- lib/screens/path_trace_map.dart | 13 ++++ lib/widgets/set_my_location_dialog.dart | 79 ++++++++++++++++++++ 4 files changed, 99 insertions(+), 67 deletions(-) create mode 100644 lib/widgets/set_my_location_dialog.dart diff --git a/lib/screens/channel_message_path_screen.dart b/lib/screens/channel_message_path_screen.dart index 092e296a..218fe78f 100644 --- a/lib/screens/channel_message_path_screen.dart +++ b/lib/screens/channel_message_path_screen.dart @@ -24,6 +24,7 @@ import '../widgets/adaptive_app_bar_title.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/path_map_scaffold.dart'; import '../widgets/path_map_ui.dart'; +import '../widgets/set_my_location_dialog.dart'; class ChannelMessagePathScreen extends StatelessWidget { final ChannelMessage message; @@ -911,6 +912,10 @@ class _ChannelMessagePathMapScreenState initialCenter: model.initialCenter, initialZoom: model.initialZoom, bounds: model.bounds, + onLongPress: (_, point) => + confirmAndSetMyLocation(context, connector, point), + onSecondaryTap: (_, point) => + confirmAndSetMyLocation(context, connector, point), onPositionChanged: (camera, hasGesture) { if (!mounted) return; // A manual pan/zoom releases the follow lock. diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index d2d74bb9..5dbd4f7a 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -43,6 +43,7 @@ import '../theme/mesh_theme.dart'; import '../widgets/mesh_ui.dart'; import '../widgets/repeater_login_dialog.dart'; import '../widgets/room_login_dialog.dart'; +import '../widgets/set_my_location_dialog.dart'; import '../helpers/guessed_location_estimator.dart'; import '../helpers/snack_bar_builder.dart'; import '../helpers/utf8_length_limiter.dart'; @@ -3498,7 +3499,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { title: Text(context.l10n.map_setAsMyLocation), onTap: () { Navigator.pop(sheetContext); - _confirmAndSetMyLocation(connector, position); + confirmAndSetMyLocation(this.context, connector, position); }, ), ListTile( @@ -3512,72 +3513,6 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ); } - Future _confirmAndSetMyLocation( - MeshCoreConnector connector, - LatLng position, - ) async { - if (!connector.isConnected) return; - final l10n = context.l10n; - final latText = position.latitude.toStringAsFixed(6); - final lonText = position.longitude.toStringAsFixed(6); - final confirmed = await showDialog( - context: context, - builder: (dialogContext) => AlertDialog( - title: Text(l10n.map_setLocationConfirmTitle), - content: Text(l10n.map_setLocationConfirmBody(latText, lonText)), - actions: [ - TextButton( - onPressed: () => Navigator.pop(dialogContext, false), - child: Text(l10n.common_cancel), - ), - FilledButton( - onPressed: () => Navigator.pop(dialogContext, true), - child: Text(l10n.map_setLocationAction), - ), - ], - ), - ); - if (confirmed != true || !mounted || !connector.isConnected) return; - - // The firmware stores coordinates as int32 micro-degrees. - bool matches() { - final lat = connector.selfLatitude; - final lon = connector.selfLongitude; - return lat != null && - lon != null && - (lat - position.latitude).abs() < 2e-6 && - (lon - position.longitude).abs() < 2e-6; - } - - var ok = false; - try { - await connector.setNodeLocation( - lat: position.latitude, - lon: position.longitude, - ); - await connector.refreshDeviceInfo(); - // Self info arrives asynchronously after the query; wait for it. - final deadline = DateTime.now().add(const Duration(seconds: 6)); - while (mounted && connector.isConnected) { - if (matches()) { - ok = true; - break; - } - if (DateTime.now().isAfter(deadline)) break; - await Future.delayed(const Duration(milliseconds: 250)); - } - } catch (e) { - debugPrint('Set node location failed: $e'); - } - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text( - ok ? l10n.map_locationSetSuccess : l10n.map_locationSetFailed, - ), - ); - } - Future _shareMarker({ required BuildContext context, required MeshCoreConnector connector, diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index f0bee80e..43d21d70 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -22,6 +22,7 @@ import 'package:meshcore_open/helpers/snack_bar_builder.dart'; import 'package:meshcore_open/widgets/path_map_scaffold.dart'; import 'package:meshcore_open/widgets/path_map_ui.dart'; import 'package:meshcore_open/widgets/snr_indicator.dart'; +import 'package:meshcore_open/widgets/set_my_location_dialog.dart'; import 'package:provider/provider.dart'; import '../theme/mesh_theme.dart'; @@ -239,6 +240,16 @@ class _PathTraceMapScreenState extends State }); } + Future _setMyLocation(LatLng point) async { + final connector = context.read(); + final ok = await confirmAndSetMyLocation(context, connector, point); + if (!ok || !mounted || !_hasData) return; + // Display paths start at the self position, so redraw them from it. + setState(() { + _rebuildDisplayPaths(connector); + }); + } + /// Keeps the camera centered on the packet while the follow lock is on. void _followPacketCamera() { if (!mounted) return; @@ -1497,6 +1508,8 @@ class _PathTraceMapScreenState extends State initialCenter: _initialCenter!, initialZoom: _initialZoom, bounds: _bounds, + onLongPress: (_, point) => _setMyLocation(point), + onSecondaryTap: (_, point) => _setMyLocation(point), onPositionChanged: (camera, hasGesture) { if (!mounted) return; // A manual pan/zoom releases the follow lock. diff --git a/lib/widgets/set_my_location_dialog.dart b/lib/widgets/set_my_location_dialog.dart new file mode 100644 index 00000000..5c611ff0 --- /dev/null +++ b/lib/widgets/set_my_location_dialog.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; +import 'package:latlong2/latlong.dart'; + +import '../connector/meshcore_connector.dart'; +import '../helpers/snack_bar_builder.dart'; +import '../l10n/l10n.dart'; + +/// Asks the user to confirm, then sets the radio's advertised location to +/// [position] and waits for SELF_INFO to report it. Shows a success or +/// failure snackbar and returns whether the radio confirmed the new location. +Future confirmAndSetMyLocation( + BuildContext context, + MeshCoreConnector connector, + LatLng position, +) async { + if (!connector.isConnected) return false; + final l10n = context.l10n; + final latText = position.latitude.toStringAsFixed(6); + final lonText = position.longitude.toStringAsFixed(6); + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(l10n.map_setLocationConfirmTitle), + content: Text(l10n.map_setLocationConfirmBody(latText, lonText)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(l10n.common_cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text(l10n.map_setLocationAction), + ), + ], + ), + ); + if (confirmed != true || !context.mounted || !connector.isConnected) { + return false; + } + + // The firmware stores coordinates as int32 micro-degrees. + bool matches() { + final lat = connector.selfLatitude; + final lon = connector.selfLongitude; + return lat != null && + lon != null && + (lat - position.latitude).abs() < 2e-6 && + (lon - position.longitude).abs() < 2e-6; + } + + var ok = false; + try { + await connector.setNodeLocation( + lat: position.latitude, + lon: position.longitude, + ); + await connector.refreshDeviceInfo(); + // Self info arrives asynchronously after the query; wait for it. + final deadline = DateTime.now().add(const Duration(seconds: 6)); + while (context.mounted && connector.isConnected) { + if (matches()) { + ok = true; + break; + } + if (DateTime.now().isAfter(deadline)) break; + await Future.delayed(const Duration(milliseconds: 250)); + } + } catch (e) { + debugPrint('Set node location failed: $e'); + } + if (!context.mounted) return ok; + showDismissibleSnackBar( + context, + content: Text( + ok ? l10n.map_locationSetSuccess : l10n.map_locationSetFailed, + ), + ); + return ok; +} From ed5884e2526d94735b6fffd6158791d51478b0d6 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:00:24 -0700 Subject: [PATCH 27/67] Declutter the map overlay Drop the row of activity/type/group chips under the Local/Online/Both switch; every option is already in the filter sheet, whose button now shows a badge with the number of active filters. Add a one-line hint to each map source segment. --- lib/l10n/app_en.arb | 3 + lib/l10n/app_localizations.dart | 18 ++++ lib/l10n/app_localizations_bg.dart | 11 +++ lib/l10n/app_localizations_de.dart | 11 +++ lib/l10n/app_localizations_en.dart | 11 +++ lib/l10n/app_localizations_es.dart | 11 +++ lib/l10n/app_localizations_fr.dart | 11 +++ lib/l10n/app_localizations_hu.dart | 11 +++ lib/l10n/app_localizations_it.dart | 11 +++ lib/l10n/app_localizations_ja.dart | 11 +++ lib/l10n/app_localizations_ko.dart | 11 +++ lib/l10n/app_localizations_nl.dart | 11 +++ lib/l10n/app_localizations_pl.dart | 11 +++ lib/l10n/app_localizations_pt.dart | 11 +++ lib/l10n/app_localizations_ru.dart | 11 +++ lib/l10n/app_localizations_sk.dart | 11 +++ lib/l10n/app_localizations_sl.dart | 11 +++ lib/l10n/app_localizations_sv.dart | 11 +++ lib/l10n/app_localizations_uk.dart | 11 +++ lib/l10n/app_localizations_zh.dart | 11 +++ lib/screens/map_screen.dart | 144 ++++------------------------- untranslated.json | 85 +++++++++++++---- 22 files changed, 303 insertions(+), 145 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 713faace..6396ba8a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3467,6 +3467,9 @@ "networkMap_sourceLocal": "Local", "networkMap_sourceOnline": "Online", "networkMap_sourceBoth": "Both", + "networkMap_sourceLocalHint": "Nodes your radio has heard", + "networkMap_sourceOnlineHint": "Repeaters from the online network map", + "networkMap_sourceBothHint": "Your radio's nodes plus the online network map", "networkMap_zoomInHint": "Zoom in to see the online network map", "networkMap_loadFailed": "Couldn't load the online network map", "networkMap_inYourContacts": "In your contacts", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 0e518f54..e2ddefb1 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -10477,6 +10477,24 @@ abstract class AppLocalizations { /// **'Both'** String get networkMap_sourceBoth; + /// No description provided for @networkMap_sourceLocalHint. + /// + /// In en, this message translates to: + /// **'Nodes your radio has heard'** + String get networkMap_sourceLocalHint; + + /// No description provided for @networkMap_sourceOnlineHint. + /// + /// In en, this message translates to: + /// **'Repeaters from the online network map'** + String get networkMap_sourceOnlineHint; + + /// No description provided for @networkMap_sourceBothHint. + /// + /// In en, this message translates to: + /// **'Your radio\'s nodes plus the online network map'** + String get networkMap_sourceBothHint; + /// No description provided for @networkMap_zoomInHint. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index c6415622..20e5ed39 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -6256,6 +6256,17 @@ class AppLocalizationsBg extends AppLocalizations { @override String get networkMap_sourceBoth => 'И двете'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Увеличете, за да видите онлайн мрежовата карта'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index c676dd50..e2b6ecc7 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -6269,6 +6269,17 @@ class AppLocalizationsDe extends AppLocalizations { @override String get networkMap_sourceBoth => 'Beides'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Zoome hinein, um die Online-Netzwerkkarte zu sehen'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 21530f6e..aafe85b9 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -6167,6 +6167,17 @@ class AppLocalizationsEn extends AppLocalizations { @override String get networkMap_sourceBoth => 'Both'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Zoom in to see the online network map'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 8359564b..3ff40ed9 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -6258,6 +6258,17 @@ class AppLocalizationsEs extends AppLocalizations { @override String get networkMap_sourceBoth => 'Ambos'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Acerca el zoom para ver el mapa de la red en línea'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 38d3d2f1..e7195127 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -6284,6 +6284,17 @@ class AppLocalizationsFr extends AppLocalizations { @override String get networkMap_sourceBoth => 'Les deux'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Zoomez pour voir la carte du réseau en ligne'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 49926094..d9d39273 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -6246,6 +6246,17 @@ class AppLocalizationsHu extends AppLocalizations { @override String get networkMap_sourceBoth => 'Mindkettő'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Nagyíts rá az online hálózati térkép megtekintéséhez'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 131ceb14..59d513e2 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -6265,6 +6265,17 @@ class AppLocalizationsIt extends AppLocalizations { @override String get networkMap_sourceBoth => 'Entrambi'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Ingrandisci per vedere la mappa della rete online'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 1f80c37d..1a71023f 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -5965,6 +5965,17 @@ class AppLocalizationsJa extends AppLocalizations { @override String get networkMap_sourceBoth => '両方'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'ズームインするとオンラインのネットワークマップが表示されます'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 23d8c73b..a8b0e72e 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -5975,6 +5975,17 @@ class AppLocalizationsKo extends AppLocalizations { @override String get networkMap_sourceBoth => '모두'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => '온라인 네트워크 지도를 보려면 확대하세요'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 219a69b4..49d228c4 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -6223,6 +6223,17 @@ class AppLocalizationsNl extends AppLocalizations { @override String get networkMap_sourceBoth => 'Beide'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Zoom in om de online netwerkkaart te zien'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index c6364e22..7465e3d9 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -6289,6 +6289,17 @@ class AppLocalizationsPl extends AppLocalizations { @override String get networkMap_sourceBoth => 'Obie'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Przybliż, aby zobaczyć mapę sieci online'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 65fe9656..e1587a43 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -6253,6 +6253,17 @@ class AppLocalizationsPt extends AppLocalizations { @override String get networkMap_sourceBoth => 'Ambos'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Aproxime o zoom para ver o mapa da rede online'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 2111d3e1..6b279c00 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -6276,6 +6276,17 @@ class AppLocalizationsRu extends AppLocalizations { @override String get networkMap_sourceBoth => 'Обе'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Приблизьте, чтобы увидеть онлайн-карту сети'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0e06e5b0..a06dc817 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -6236,6 +6236,17 @@ class AppLocalizationsSk extends AppLocalizations { @override String get networkMap_sourceBoth => 'Obe'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Priblížte, aby ste videli online sieťovú mapu'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 5ff3571c..48bc7a49 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -6238,6 +6238,17 @@ class AppLocalizationsSl extends AppLocalizations { @override String get networkMap_sourceBoth => 'Oboje'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Povečajte, da vidite spletni omrežni zemljevid'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index f3b28979..efd22e6d 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -6203,6 +6203,17 @@ class AppLocalizationsSv extends AppLocalizations { @override String get networkMap_sourceBoth => 'Båda'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Zooma in för att se nätverkskartan online'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 8e658ffd..9e033ec4 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -6277,6 +6277,17 @@ class AppLocalizationsUk extends AppLocalizations { @override String get networkMap_sourceBoth => 'Обидві'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => 'Наблизьте, щоб побачити онлайн-карту мережі'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 31d2b20f..f80452cc 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5830,6 +5830,17 @@ class AppLocalizationsZh extends AppLocalizations { @override String get networkMap_sourceBoth => '两者'; + @override + String get networkMap_sourceLocalHint => 'Nodes your radio has heard'; + + @override + String get networkMap_sourceOnlineHint => + 'Repeaters from the online network map'; + + @override + String get networkMap_sourceBothHint => + 'Your radio\'s nodes plus the online network map'; + @override String get networkMap_zoomInHint => '放大以查看在线网络地图'; diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 5dbd4f7a..aa28a882 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -1080,7 +1080,11 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ? FloatingActionButton( onPressed: () => _showFilterSheet(context, settingsService), tooltip: context.l10n.map_filterNodes, - child: const Icon(Icons.filter_list), + child: Badge.count( + count: _activeFilterCount(settings), + isLabelVisible: _activeFilterCount(settings) > 0, + child: const Icon(Icons.filter_list), + ), ) : null, ), @@ -2023,69 +2027,6 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ), const SizedBox(height: 6), _buildMapSourceSwitch(context, mapSource), - const SizedBox(height: 6), - LayoutBuilder( - builder: (context, constraints) { - final chips = [ - _mapChip( - label: context.l10n.time_allTime, - selected: _freshness == _Freshness.all, - onTap: () => setState(() => _freshness = _Freshness.all), - ), - _mapChip( - label: context.l10n.map_online, - selected: _freshness == _Freshness.online, - color: MapPalette.online, - onTap: () => setState(() => _freshness = _Freshness.online), - ), - _mapChip( - label: context.l10n.map_recent, - selected: _freshness == _Freshness.recent, - color: MapPalette.stale, - onTap: () => setState(() => _freshness = _Freshness.recent), - ), - _mapChip( - label: context.l10n.map_stale, - selected: _freshness == _Freshness.stale, - color: MapPalette.offline, - onTap: () => setState(() => _freshness = _Freshness.stale), - ), - _mapChip( - label: context.l10n.map_repeaters, - selected: settings.mapShowRepeaters, - color: MapPalette.repeater, - onTap: () => settingsService.setMapShowRepeaters( - !settings.mapShowRepeaters, - ), - ), - _mapChip( - label: context.l10n.map_chatNodes, - selected: settings.mapShowChatNodes, - color: MapPalette.selected, - onTap: () => settingsService.setMapShowChatNodes( - !settings.mapShowChatNodes, - ), - ), - _mapChip( - label: context.l10n.map_groupChip, - selected: settings.mapClusterNodes, - color: MapPalette.cluster, - onTap: () => settingsService.setMapClusterNodes( - !settings.mapClusterNodes, - ), - ), - ]; - - if (constraints.maxWidth < 600) { - return Wrap(runSpacing: 6, children: chips); - } - - return SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row(children: chips), - ); - }, - ), if (hasQuery) _buildSearchResults(context, allContacts, guessedLocations) else if (_statsExpanded) @@ -2107,6 +2048,14 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ); } + int _activeFilterCount(AppSettings settings) => [ + _freshness != _Freshness.all, + !settings.mapShowChatNodes, + !settings.mapShowRepeaters, + !settings.mapShowOtherNodes, + settings.mapKeyPrefixEnabled, + ].where((active) => active).length; + Widget _buildMapSourceSwitch(BuildContext context, MapSourceOption source) { final l10n = context.l10n; return Material( @@ -2128,16 +2077,19 @@ class _MapScreenState extends State with DisconnectNavigationMixin { value: MapSourceOption.local, icon: const Icon(Icons.radio, size: 20), label: Text(l10n.networkMap_sourceLocal), + tooltip: l10n.networkMap_sourceLocalHint, ), ButtonSegment( value: MapSourceOption.online, icon: const Icon(Icons.public, size: 20), label: Text(l10n.networkMap_sourceOnline), + tooltip: l10n.networkMap_sourceOnlineHint, ), ButtonSegment( value: MapSourceOption.both, icon: const Icon(Icons.layers, size: 20), label: Text(l10n.networkMap_sourceBoth), + tooltip: l10n.networkMap_sourceBothHint, ), ], selected: {source}, @@ -2177,70 +2129,6 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ); } - Widget _mapChip({ - required String label, - required bool selected, - required VoidCallback onTap, - Color? color, - }) { - final accent = color ?? MapPalette.selected; - return Padding( - padding: const EdgeInsets.only(right: 6), - child: Semantics( - button: true, - selected: selected, - child: Material( - color: selected - ? Color.alphaBlend( - accent.withValues(alpha: 0.34), - _overlayPanelColor, - ) - : _overlayPanelColor, - shape: StadiumBorder( - side: BorderSide( - color: selected ? accent : _overlayBorderColor, - width: selected ? 1.5 : 1, - ), - ), - clipBehavior: Clip.antiAlias, - child: InkWell( - onTap: () { - HapticFeedback.selectionClick(); - onTap(); - }, - child: Container( - constraints: const BoxConstraints(minHeight: 44), - padding: const EdgeInsets.symmetric(horizontal: 14), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (selected) ...[ - Icon( - Icons.check, - size: 16, - color: _overlayPrimaryTextColor, - ), - const SizedBox(width: 4), - ], - Text( - label, - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w600, - color: selected - ? _overlayPrimaryTextColor - : _overlaySecondaryTextColor, - ), - ), - ], - ), - ), - ), - ), - ), - ); - } - Widget _buildSearchResults( BuildContext context, List allContacts, diff --git a/untranslated.json b/untranslated.json index f9d91c98..1027242f 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1,69 +1,120 @@ { "bg": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "de": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "es": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "fr": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "hu": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "it": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "ja": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "ko": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "nl": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "pl": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "pt": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "ru": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "sk": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "sl": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "sv": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "uk": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ], "zh": [ - "contacts_keyPrefixSemantics" + "contacts_keyPrefixSemantics", + "networkMap_sourceLocalHint", + "networkMap_sourceOnlineHint", + "networkMap_sourceBothHint" ] } From caf20b44158dd09ad95498a534844ca57640a896 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:00:53 -0700 Subject: [PATCH 28/67] Summarize location, image and GIF messages in notifications Notification bodies now use the chat's parsers to show a localized summary for shared locations (m: markers), channel images, GIFs and reactions instead of the raw payload. The marker parser moves out of the map screen into helpers/marker_message.dart so the service can use it. --- lib/helpers/marker_message.dart | 30 ++++++++ lib/l10n/app_en.arb | 19 +++++ lib/l10n/app_localizations.dart | 30 ++++++++ lib/l10n/app_localizations_bg.dart | 19 +++++ lib/l10n/app_localizations_de.dart | 19 +++++ lib/l10n/app_localizations_en.dart | 19 +++++ lib/l10n/app_localizations_es.dart | 19 +++++ lib/l10n/app_localizations_fr.dart | 19 +++++ lib/l10n/app_localizations_hu.dart | 19 +++++ lib/l10n/app_localizations_it.dart | 19 +++++ lib/l10n/app_localizations_ja.dart | 19 +++++ lib/l10n/app_localizations_ko.dart | 19 +++++ lib/l10n/app_localizations_nl.dart | 19 +++++ lib/l10n/app_localizations_pl.dart | 19 +++++ lib/l10n/app_localizations_pt.dart | 19 +++++ lib/l10n/app_localizations_ru.dart | 19 +++++ lib/l10n/app_localizations_sk.dart | 19 +++++ lib/l10n/app_localizations_sl.dart | 19 +++++ lib/l10n/app_localizations_sv.dart | 19 +++++ lib/l10n/app_localizations_uk.dart | 19 +++++ lib/l10n/app_localizations_zh.dart | 19 +++++ lib/screens/channel_chat_screen.dart | 1 + lib/screens/chat_screen.dart | 1 + lib/screens/map_screen.dart | 30 +------- lib/services/notification_service.dart | 26 +++++-- test/screens/map_marker_parse_test.dart | 2 +- test/services/notification_text_test.dart | 45 ++++++++++++ untranslated.json | 85 +++++++++++++++++++++++ 28 files changed, 575 insertions(+), 36 deletions(-) create mode 100644 lib/helpers/marker_message.dart create mode 100644 test/services/notification_text_test.dart diff --git a/lib/helpers/marker_message.dart b/lib/helpers/marker_message.dart new file mode 100644 index 00000000..52f251c6 --- /dev/null +++ b/lib/helpers/marker_message.dart @@ -0,0 +1,30 @@ +import 'package:latlong2/latlong.dart'; + +class MarkerPayload { + final LatLng position; + final String label; + final String flags; + + MarkerPayload({ + required this.position, + required this.label, + required this.flags, + }); +} + +/// Parse a shared marker text message of the form +/// `m:,|