Settings: open dedicated pages instead of dialogs

Node Name, Radio Settings, Location, Contact Settings, Privacy and About
now open pages laid out like App Settings. Settings stored on the radio
are sent only on Save, with a warning when leaving unsaved changes.

- Shared SaveToRadioPage / UnsavedChangesGuard / MeshInfoCard
- Node Name byte counter, Location map picker, About links
- Export Data refresh; Settings text and title consistency
- Radio Settings docs corrected against code and firmware
- design.md: settings pages, Save rules, text and app bar rules

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
celsoazevedoandClaude Opus 5.5 committed 2026-11-23 21:21:18 +00:00
1 parent 945b82437f
commit fc7bbe9e02
66 files changed
+7011 -3749

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../widgets/mesh_nav_tile.dart';
import '../widgets/mesh_ui.dart';
const String _sourceCodeHost = 'github.com/zjs81/meshcore-open';
final Uri _sourceCodeUrl = Uri.https('github.com', '/zjs81/meshcore-open');
final Uri _licenseUrl = Uri.https(
'github.com',
'/zjs81/meshcore-open/blob/HEAD/LICENSE',
);
final Uri _contributorsUrl = Uri.https(
'github.com',
'/zjs81/meshcore-open/graphs/contributors',
);
/// Version label for Settings and About.
Future<String> loadAppVersionLabel() async {
final info = await PackageInfo.fromPlatform();
return '${info.version} BETA';
}
/// App name, version, description, source code, licenses and credits.
class AboutScreen extends StatefulWidget {
const AboutScreen({super.key});
@override
State<AboutScreen> createState() => _AboutScreenState();
}
class _AboutScreenState extends State<AboutScreen> {
String? _version;
@override
void initState() {
super.initState();
loadAppVersionLabel().then((version) {
if (mounted) setState(() => _version = version);
});
}
Future<void> _open(Uri url) async {
final opened = await launchUrl(url, mode: LaunchMode.externalApplication);
if (opened || !mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.chat_couldNotOpenLink(url.toString())),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final version = _version ?? l10n.common_loading;
// The current year, so the notice doesn't go stale between releases.
final legalese = l10n.settings_aboutLegalese('${DateTime.now().year}');
return Scaffold(
appBar: AppBar(
title: AdaptiveAppBarTitle(l10n.settings_about),
centerTitle: true,
),
body: MeshSettingsTileTheme(
child: SafeArea(
top: false,
child: ListView(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 24),
children: [
MeshCard(
padding: const EdgeInsets.all(16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(MeshRadii.sm),
child: Image.asset(
'assets/images/mesh-icon.png',
width: 56,
height: 56,
excludeFromSemantics: true,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.appTitle,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
version,
style: MeshTheme.mono(
fontSize: 14,
color: scheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
Text(
l10n.settings_aboutDescription,
style: theme.textTheme.bodyMedium,
),
],
),
),
],
),
),
SectionHeader(l10n.about_project),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
MeshNavTile(
icon: Icons.code,
title: l10n.about_sourceCode,
subtitle: _sourceCodeHost,
trailing: Icon(
Icons.open_in_new,
size: 24,
color: scheme.onSurfaceVariant,
),
onTap: () => _open(_sourceCodeUrl),
),
const Divider(height: 1, indent: 16),
MeshNavTile(
icon: Icons.gavel_outlined,
title: l10n.about_license,
trailing: Icon(
Icons.open_in_new,
size: 24,
color: scheme.onSurfaceVariant,
),
onTap: () => _open(_licenseUrl),
),
const Divider(height: 1, indent: 16),
MeshNavTile(
icon: Icons.description_outlined,
title: l10n.about_openSourceLicenses,
onTap: () => showLicensePage(
context: context,
applicationName: l10n.appTitle,
applicationVersion: version,
applicationLegalese: legalese,
),
),
],
),
),
SectionHeader(l10n.about_credits),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
MeshNavTile(
icon: Icons.people_outline,
title: l10n.about_contributors,
trailing: Icon(
Icons.open_in_new,
size: 24,
color: scheme.onSurfaceVariant,
),
onTap: () => _open(_contributorsUrl),
),
const Divider(height: 1, indent: 16),
ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
leading: const Icon(Icons.terrain_outlined, size: 24),
title: Text(l10n.settings_aboutOpenMeteoAttribution),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 20, 16, 0),
child: Text(
legalese,
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
),
],
),
),
),
);
}
}
+1 -27
View File
@@ -236,8 +236,6 @@ class _AddContactScreenState extends State<AddContactScreen> {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return Scaffold(
appBar: AppBar(
@@ -264,31 +262,7 @@ class _AddContactScreenState extends State<AddContactScreen> {
child: ListView(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 24),
children: [
MeshCard(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 14,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
Icons.info_outline,
size: 24,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 16),
Expanded(
child: Text(
l10n.addContact_infoBanner,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurface,
),
),
),
],
),
),
MeshInfoCard(l10n.addContact_infoBanner),
const SizedBox(height: 8),
MeshCard(
padding: EdgeInsets.zero,
+188
View File
@@ -0,0 +1,188 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import '../theme/theme_icons.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/unsaved_changes_guard.dart';
typedef _ContactForm = ({
bool autoAddUsers,
bool autoAddRepeaters,
bool autoAddRoomServers,
bool autoAddSensors,
bool overwriteOldest,
bool evictDiscovered,
});
/// Contact auto-add and overflow options. Sent on Save.
class ContactSettingsScreen extends StatefulWidget {
const ContactSettingsScreen({super.key});
@override
State<ContactSettingsScreen> createState() => _ContactSettingsScreenState();
}
class _ContactSettingsScreenState extends State<ContactSettingsScreen> {
late bool _autoAddUsers;
late bool _autoAddRepeaters;
late bool _autoAddRoomServers;
late bool _autoAddSensors;
late bool _overwriteOldest;
late bool _evictDiscovered;
late _ContactForm _savedForm;
@override
void initState() {
super.initState();
final connector = context.read<MeshCoreConnector>();
_autoAddUsers = connector.autoAddUsers ?? false;
_autoAddRepeaters = connector.autoAddRepeaters ?? false;
_autoAddRoomServers = connector.autoAddRoomServers ?? false;
_autoAddSensors = connector.autoAddSensors ?? false;
_overwriteOldest = connector.autoAddOverwriteOldest ?? false;
_evictDiscovered = context
.read<AppSettingsService>()
.settings
.evictDiscoveredContactsEnabled;
_savedForm = _form;
}
_ContactForm get _form => (
autoAddUsers: _autoAddUsers,
autoAddRepeaters: _autoAddRepeaters,
autoAddRoomServers: _autoAddRoomServers,
autoAddSensors: _autoAddSensors,
overwriteOldest: _overwriteOldest,
evictDiscovered: _evictDiscovered,
);
Future<bool> _save() async {
final l10n = context.l10n;
final connector = context.read<MeshCoreConnector>();
final settingsService = context.read<AppSettingsService>();
final form = _form;
await connector.sendFrame(
buildSetAutoAddConfigFrame(
autoAddChat: form.autoAddUsers,
autoAddRepeater: form.autoAddRepeaters,
autoAddRoomServer: form.autoAddRoomServers,
autoAddSensor: form.autoAddSensors,
overwriteOldest: form.overwriteOldest,
),
);
await connector.sendFrame(buildGetAutoAddFlagsFrame());
await settingsService.setEvictDiscoveredContactsEnabled(
form.evictDiscovered,
);
if (form.evictDiscovered) {
await connector.trimDiscoveredContactsToLimit();
}
if (!mounted) return true;
setState(() => _savedForm = form);
showDismissibleSnackBar(
context,
content: Text(l10n.settings_contactSettingsSaved),
);
return true;
}
Widget _switch({
required Widget icon,
required String title,
String? subtitle,
required bool value,
required ValueChanged<bool> onChanged,
}) {
return SwitchListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
secondary: icon,
title: Text(title),
subtitle: subtitle == null ? null : Text(subtitle),
value: value,
onChanged: (value) => setState(() => onChanged(value)),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
const divider = Divider(height: 1, indent: 16);
return SaveToRadioPage(
title: l10n.settings_contactSettings,
hasChanges: _form != _savedForm,
onSave: _save,
children: [
SectionHeader(
l10n.contactsSettings_autoAddTitle,
description: l10n.contactsSettings_autoAddDescription,
),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
// Same icons as the contact list and map.
_switch(
icon: const Icon(Icons.person, size: 24),
title: l10n.contactsSettings_autoAddUsersTitle,
value: _autoAddUsers,
onChanged: (v) => _autoAddUsers = v,
),
divider,
_switch(
icon: const ThemedIcon(ThemeIconSlot.repeater, size: 24),
title: l10n.contactsSettings_autoAddRepeatersTitle,
value: _autoAddRepeaters,
onChanged: (v) => _autoAddRepeaters = v,
),
divider,
_switch(
icon: const ThemedIcon(ThemeIconSlot.room, size: 24),
title: l10n.contactsSettings_autoAddRoomServersTitle,
value: _autoAddRoomServers,
onChanged: (v) => _autoAddRoomServers = v,
),
divider,
_switch(
icon: const ThemedIcon(ThemeIconSlot.sensor, size: 24),
title: l10n.contactsSettings_autoAddSensorsTitle,
value: _autoAddSensors,
onChanged: (v) => _autoAddSensors = v,
),
],
),
),
SectionHeader(l10n.contactsSettings_otherTitle),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
_switch(
icon: const ThemedIcon(ThemeIconSlot.contacts, size: 24),
title: l10n.contactsSettings_overwriteOldestTitle,
subtitle: l10n.contactsSettings_overwriteOldestSubtitle,
value: _overwriteOldest,
onChanged: (v) => _overwriteOldest = v,
),
divider,
_switch(
// The Discovered Contacts icon.
icon: const Icon(Icons.person_add_rounded, size: 24),
title: l10n.contactsSettings_evictDiscoveredContactsTitle,
subtitle: l10n.contactsSettings_evictDiscoveredContactsSubtitle(
MeshCoreConnector.maxDiscoveredContacts,
),
value: _evictDiscovered,
onChanged: (v) => _evictDiscovered = v,
),
],
),
),
],
);
}
}
+7 -5
View File
@@ -159,19 +159,19 @@ class _CoordinateMapScreenState extends State<CoordinateMapScreen> {
right: 12,
child: Column(
children: [
_CoordinateMapControlButton(
CoordinateMapControlButton(
icon: Icons.add,
tooltip: l10n.map_zoomIn,
onPressed: () => _zoomBy(1),
),
const SizedBox(height: 8),
_CoordinateMapControlButton(
CoordinateMapControlButton(
icon: Icons.remove,
tooltip: l10n.map_zoomOut,
onPressed: () => _zoomBy(-1),
),
const SizedBox(height: 8),
_CoordinateMapControlButton(
CoordinateMapControlButton(
icon: Icons.my_location,
tooltip: l10n.map_centerMap,
onPressed: () => _mapController.move(_position, _initialZoom),
@@ -227,12 +227,14 @@ class _CoordinateMapScreenState extends State<CoordinateMapScreen> {
}
}
class _CoordinateMapControlButton extends StatelessWidget {
/// Zoom and recenter button floating over a full-screen map.
class CoordinateMapControlButton extends StatelessWidget {
final IconData icon;
final String tooltip;
final VoidCallback onPressed;
const _CoordinateMapControlButton({
const CoordinateMapControlButton({
super.key,
required this.icon,
required this.tooltip,
required this.onPressed,
+18 -15
View File
@@ -11,10 +11,11 @@ import '../connector/meshcore_connector.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import '../theme/theme_icons.dart';
import '../utils/bookmark_markdown_export.dart';
import '../utils/platform_info.dart';
import '../utils/share_origin.dart';
import '../widgets/app_bar.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/mesh_nav_tile.dart';
import '../widgets/sync_progress_overlay.dart';
@@ -34,11 +35,7 @@ class ExportScreen extends StatelessWidget {
final connector = context.read<MeshCoreConnector>();
return Scaffold(
appBar: AppBar(
title: AppBarTitle(
l10n.settings_export,
indicators: false,
subtitle: false,
),
title: AdaptiveAppBarTitle(l10n.settings_exportData),
centerTitle: true,
bottom: const SyncProgressAppBarBottom(),
),
@@ -47,25 +44,32 @@ class ExportScreen extends StatelessWidget {
child: ListView(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 24),
children: [
SectionHeader(l10n.settings_export),
SectionHeader(
l10n.export_messagesTitle,
description: l10n.export_messagesDescription,
),
MeshCard(
padding: EdgeInsets.zero,
child: MeshNavTile(
// The bookmark icon used in chats.
icon: Icons.bookmark_border,
title: l10n.settings_exportBookmarks,
subtitle: l10n.settings_exportBookmarksSubtitle,
onTap: () => _exportBookmarks(context),
),
),
const SizedBox(height: 16),
SectionHeader(
l10n.export_locationsTitle,
description: l10n.export_locationsDescription,
),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
// Same icons as the contact list and Contact Settings.
MeshNavTile(
icon: Icons.download_outlined,
icon: Icons.cell_tower,
iconSlot: ThemeIconSlot.repeater,
title: l10n.settings_gpxExportRepeaters,
subtitle: l10n.settings_gpxExportRepeatersSubtitle,
onTap: () {
final exporter = GpxExport(connector)..addRepeaters();
_gpxExport(
@@ -79,9 +83,8 @@ class ExportScreen extends StatelessWidget {
),
const Divider(height: 1, indent: 16),
MeshNavTile(
icon: Icons.download_outlined,
icon: Icons.person,
title: l10n.settings_gpxExportContacts,
subtitle: l10n.settings_gpxExportContactsSubtitle,
onTap: () {
final exporter = GpxExport(connector)..addContacts();
_gpxExport(
@@ -95,9 +98,9 @@ class ExportScreen extends StatelessWidget {
),
const Divider(height: 1, indent: 16),
MeshNavTile(
icon: Icons.download_outlined,
icon: Icons.people_outline,
iconSlot: ThemeIconSlot.contacts,
title: l10n.settings_gpxExportAll,
subtitle: l10n.settings_gpxExportAllSubtitle,
onTap: () {
final exporter = GpxExport(connector)..addAll();
_gpxExport(
+192
View File
@@ -0,0 +1,192 @@
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:provider/provider.dart';
import '../l10n/l10n.dart';
import '../services/map_tile_cache_service.dart';
import '../theme/mesh_theme.dart';
import '../widgets/adaptive_app_bar_title.dart';
import 'coordinate_map_screen.dart';
import 'map_screen.dart';
/// Map with a fixed centre pin. Pops the chosen [LatLng], or null on back.
class LocationPickerScreen extends StatefulWidget {
/// Start position; defaults to the Map tab's last camera.
final LatLng? initial;
const LocationPickerScreen({super.key, this.initial});
@override
State<LocationPickerScreen> createState() => _LocationPickerScreenState();
}
class _LocationPickerScreenState extends State<LocationPickerScreen> {
static const double _minZoom = 2.0;
static const double _maxZoom = 18.0;
static const double _pinnedZoom = 15.0;
static const double _pinSize = 48.0;
final MapController _mapController = MapController();
late final ({LatLng center, double zoom}) _initialCamera;
late LatLng _center;
@override
void initState() {
super.initState();
final initial = widget.initial;
_initialCamera = initial != null
? (center: initial, zoom: _pinnedZoom)
: savedMapCamera() ?? (center: const LatLng(20, 0), zoom: _minZoom);
_center = _initialCamera.center;
}
@override
void dispose() {
_mapController.dispose();
super.dispose();
}
void _zoomBy(double delta) {
final camera = _mapController.camera;
final nextZoom = (camera.zoom + delta).clamp(_minZoom, _maxZoom).toDouble();
_mapController.move(camera.center, nextZoom);
}
/// Wraps longitude to ±180 (the camera can go past it) and clamps latitude.
LatLng get _normalizedCenter {
final lon = ((_center.longitude + 180) % 360 + 360) % 360 - 180;
return LatLng(_center.latitude.clamp(-90.0, 90.0), lon);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final mapTheme = MeshMapTheme.of(context);
final tileCache = context.read<MapTileCacheService>();
final center = _normalizedCenter;
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: AdaptiveAppBarTitle(l10n.location_pickOnMap),
),
// Scrolls at large text sizes instead of covering the map.
body: LayoutBuilder(
builder: (context, constraints) => Column(
children: [
Expanded(
child: Stack(
children: [
FlutterMap(
mapController: _mapController,
options: MapOptions(
initialCenter: _initialCamera.center,
initialZoom: _initialCamera.zoom,
minZoom: _minZoom,
maxZoom: _maxZoom,
interactionOptions: const InteractionOptions(
flags: ~InteractiveFlag.rotate,
),
onPositionChanged: (camera, _) =>
setState(() => _center = camera.center),
onTap: (_, point) => _mapController.move(
point,
_mapController.camera.zoom,
),
),
children: [tileCache.buildTileLayer(context)],
),
// Pin tip at the map centre.
Center(
child: IgnorePointer(
child: Transform.translate(
offset: const Offset(0, -_pinSize / 2),
child: Icon(
Icons.location_on,
size: _pinSize,
color: mapTheme.followsTheme
? mapTheme.accent
: MapPalette.batteryLow,
shadows: const [
Shadow(
color: MapPalette.markerShadow,
blurRadius: 8,
offset: Offset(0, 3),
),
],
),
),
),
),
Positioned(
top: 12,
right: 12,
child: Column(
children: [
CoordinateMapControlButton(
icon: Icons.add,
tooltip: l10n.map_zoomIn,
onPressed: () => _zoomBy(1),
),
const SizedBox(height: 8),
CoordinateMapControlButton(
icon: Icons.remove,
tooltip: l10n.map_zoomOut,
onPressed: () => _zoomBy(-1),
),
],
),
),
],
),
),
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: constraints.maxHeight * 0.6,
),
child: Material(
color: scheme.surfaceContainerLow,
child: SafeArea(
top: false,
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
l10n.locationPicker_hint,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
const SizedBox(height: 4),
Text(
'${center.latitude.toStringAsFixed(6)}, '
'${center.longitude.toStringAsFixed(6)}',
style: MeshTheme.mono(
fontSize: 15,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
),
const SizedBox(height: 12),
FilledButton.icon(
onPressed: () => Navigator.pop(context, center),
icon: const Icon(Icons.check),
label: Text(l10n.locationPicker_useLocation),
),
],
),
),
),
),
),
],
),
),
);
}
}
+329
View File
@@ -0,0 +1,329 @@
import 'package:flutter/material.dart';
import 'package:latlong2/latlong.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../helpers/guessed_location_estimator.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import '../widgets/mesh_nav_tile.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/unsaved_changes_guard.dart';
import 'location_picker_screen.dart';
/// Form values compared to detect unsaved edits.
typedef _LocationForm = ({
String latitude,
String longitude,
String interval,
bool gpsEnabled,
});
/// Advertised location and, with GPS hardware, GPS settings. Sent on Save.
class LocationSettingsScreen extends StatefulWidget {
const LocationSettingsScreen({super.key});
@override
State<LocationSettingsScreen> createState() => _LocationSettingsScreenState();
}
class _LocationSettingsScreenState extends State<LocationSettingsScreen> {
final _latController = TextEditingController();
final _lonController = TextEditingController();
final _intervalController = TextEditingController();
late final bool _hasGps;
bool _gpsEnabled = false;
double? _deviceLatitude;
double? _deviceLongitude;
late _LocationForm _savedForm;
String? _latError;
String? _lonError;
String? _intervalError;
@override
void initState() {
super.initState();
final connector = context.read<MeshCoreConnector>();
final settingsService = context.read<AppSettingsService>();
// Null until the device answers.
final customVars = connector.currentCustomVars ?? {};
_hasGps = customVars.containsKey('gps');
_gpsEnabled = customVars['gps'] == '1';
_deviceLatitude = connector.selfLatitude;
_deviceLongitude = connector.selfLongitude;
if (_hasLocation) {
_latController.text = _deviceLatitude!.toStringAsFixed(6);
_lonController.text = _deviceLongitude!.toStringAsFixed(6);
}
_intervalController.text = settingsService
.resolvedGpsIntervalSeconds(customVars)
.toString();
_savedForm = _currentForm();
}
@override
void dispose() {
_latController.dispose();
_lonController.dispose();
_intervalController.dispose();
super.dispose();
}
/// Firmware stores "no location" as 0,0 (the default for a fresh node), so
/// that pair is shown as empty fields rather than a real coordinate.
bool get _hasLocation {
final lat = _deviceLatitude;
final lon = _deviceLongitude;
return lat != null && lon != null && !(lat == 0 && lon == 0);
}
_LocationForm _currentForm() => (
latitude: _latController.text.trim(),
longitude: _lonController.text.trim(),
interval: _hasGps ? _intervalController.text.trim() : '',
gpsEnabled: _hasGps && _gpsEnabled,
);
/// Valid field coordinates, else the radio's location.
LatLng? get _pickerStart {
final lat = double.tryParse(_latController.text.trim());
final lon = double.tryParse(_lonController.text.trim());
if (lat != null && lon != null && isPlausibleLocation(lat, lon)) {
return LatLng(lat, lon);
}
return _hasLocation ? LatLng(_deviceLatitude!, _deviceLongitude!) : null;
}
Future<void> _pickOnMap() async {
final picked = await Navigator.push<LatLng>(
context,
MaterialPageRoute(
builder: (_) => LocationPickerScreen(initial: _pickerStart),
),
);
if (picked == null || !mounted) return;
setState(() {
_latController.text = picked.latitude.toStringAsFixed(6);
_lonController.text = picked.longitude.toStringAsFixed(6);
_latError = null;
_lonError = null;
});
}
/// Validates all fields, then sends GPS (if changed), interval and location.
Future<bool> _save() async {
final l10n = context.l10n;
// Validate first so a typo doesn't leave half the changes applied.
int? interval;
String? intervalError;
if (_hasGps) {
final intervalText = _intervalController.text.trim();
if (intervalText.isNotEmpty) {
interval = int.tryParse(intervalText);
if (interval == null || interval < 60 || interval >= 86400) {
intervalError = l10n.settings_locationIntervalInvalid;
}
}
}
final latText = _latController.text.trim();
final lonText = _lonController.text.trim();
double? lat;
double? lon;
String? latError;
String? lonError;
var clearsLocation = false;
if (latText.isEmpty && lonText.isEmpty) {
// Clearing both fields removes the location. Companion firmware has no
// dedicated "clear" command: CMD_SET_ADVERT_LATLON with 0,0 restores
// the factory default, which firmware and this app treat as unset.
if (_hasLocation) {
lat = 0;
lon = 0;
clearsLocation = true;
}
} else {
// One empty field keeps the device's current value for that axis.
lat = latText.isNotEmpty
? double.tryParse(latText)
: (_hasLocation ? _deviceLatitude : null);
lon = lonText.isNotEmpty
? double.tryParse(lonText)
: (_hasLocation ? _deviceLongitude : null);
if (lat == null) {
latError = latText.isEmpty
? l10n.settings_locationBothRequired
: l10n.settings_locationInvalid;
} else if (lat < -90 || lat > 90) {
latError = l10n.settings_locationInvalid;
}
if (lon == null) {
lonError = lonText.isEmpty
? l10n.settings_locationBothRequired
: l10n.settings_locationInvalid;
} else if (lon < -180 || lon > 180) {
lonError = l10n.settings_locationInvalid;
}
}
if (intervalError != null || latError != null || lonError != null) {
setState(() {
_intervalError = intervalError;
_latError = latError;
_lonError = lonError;
});
return false;
}
// An empty interval leaves the stored one; show it again.
if (_hasGps && _intervalController.text.trim().isEmpty) {
_intervalController.text = _savedForm.interval;
}
final gpsChanged = _hasGps && _gpsEnabled != _savedForm.gpsEnabled;
if (!gpsChanged && interval == null && (lat == null || lon == null)) {
// Nothing to send, like the old dialog.
setState(() => _savedForm = _currentForm());
return true;
}
final connector = context.read<MeshCoreConnector>();
final settingsService = context.read<AppSettingsService>();
if (gpsChanged) {
await connector.setCustomVar(_gpsEnabled ? "gps:1" : "gps:0");
}
if (interval != null) {
await settingsService.setGpsIntervalSeconds(
interval,
writeToDevice: (value) => connector.setCustomVar("gps_interval:$value"),
);
}
if (lat != null && lon != null) {
await connector.setNodeLocation(lat: lat, lon: lon);
}
await connector.refreshDeviceInfo();
if (!mounted) return true;
setState(() {
if (lat != null && lon != null) {
_deviceLatitude = lat;
_deviceLongitude = lon;
}
_savedForm = _currentForm();
});
showDismissibleSnackBar(
context,
content: Text(
clearsLocation
? l10n.settings_locationCleared
: l10n.settings_locationUpdated,
),
);
return true;
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
const coordinateKeyboard = TextInputType.numberWithOptions(
decimal: true,
signed: true,
);
return SaveToRadioPage(
title: l10n.settings_location,
hasChanges: _currentForm() != _savedForm,
onSave: _save,
children: [
SectionHeader(
l10n.location_coordinates,
description: l10n.location_coordinatesDescription,
),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(14),
child: Column(
children: [
TextField(
controller: _latController,
onTapOutside: (_) => FocusScope.of(context).unfocus(),
onChanged: (_) => setState(() => _latError = null),
decoration: InputDecoration(
labelText: l10n.settings_latitude,
errorText: _latError,
errorMaxLines: 2,
),
keyboardType: coordinateKeyboard,
),
const SizedBox(height: 16),
TextField(
controller: _lonController,
onTapOutside: (_) => FocusScope.of(context).unfocus(),
onChanged: (_) => setState(() => _lonError = null),
decoration: InputDecoration(
labelText: l10n.settings_longitude,
helperText: l10n.settings_locationClearHelper,
helperMaxLines: 2,
errorText: _lonError,
errorMaxLines: 2,
),
keyboardType: coordinateKeyboard,
),
],
),
),
const Divider(height: 1, indent: 16),
MeshNavTile(
icon: Icons.map_outlined,
title: l10n.location_pickOnMap,
onTap: _pickOnMap,
),
],
),
),
if (_hasGps) ...[
SectionHeader(l10n.telemetry_gpsLabel),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
secondary: const Icon(Icons.gps_fixed, size: 24),
title: Text(l10n.settings_locationGPSEnable),
subtitle: Text(l10n.settings_locationGPSEnableSubtitle),
value: _gpsEnabled,
// Sent on Save.
onChanged: (value) => setState(() => _gpsEnabled = value),
),
const Divider(height: 1, indent: 16),
Padding(
padding: const EdgeInsets.all(14),
child: TextField(
controller: _intervalController,
onTapOutside: (_) => FocusScope.of(context).unfocus(),
onChanged: (_) => setState(() => _intervalError = null),
decoration: InputDecoration(
labelText: l10n.settings_locationIntervalSec,
helperText: l10n.settings_locationIntervalHelper,
errorText: _intervalError,
errorMaxLines: 2,
),
keyboardType: const TextInputType.numberWithOptions(
decimal: false,
signed: false,
),
),
),
],
),
),
],
],
);
}
}
+12 -9
View File
@@ -54,6 +54,17 @@ import '../helpers/utf8_length_limiter.dart';
import 'line_of_sight_map_screen.dart';
import '../theme/theme_icons.dart';
const String _lastCameraKey = 'map_last_camera';
/// The Map tab's last camera, or null if never saved.
({LatLng center, double zoom})? savedMapCamera() {
final saved = PrefsManager.instance.getStringList(_lastCameraKey);
if (saved == null || saved.length != 3) return null;
final values = saved.map(double.tryParse).toList();
if (values.contains(null)) return null;
return (center: LatLng(values[0]!, values[1]!), zoom: values[2]!);
}
class MapScreen extends StatefulWidget {
final LatLng? highlightPosition;
final String? highlightLabel;
@@ -133,7 +144,6 @@ class _MapScreenState extends State<MapScreen> with WidgetsBindingObserver {
// been positioned once.
({LatLng center, double zoom})? _initialCamera;
static const String _lastCameraKey = 'map_last_camera';
static const Duration _cameraSaveDelay = Duration(milliseconds: 500);
Timer? _cameraSaveTimer;
List<String>? _pendingCamera;
@@ -144,14 +154,7 @@ class _MapScreenState extends State<MapScreen> with WidgetsBindingObserver {
if (lat != null && lon != null && isPlausibleLocation(lat, lon)) {
return (center: LatLng(lat, lon), zoom: 12.0);
}
final saved = PrefsManager.instance.getStringList(_lastCameraKey);
if (saved != null && saved.length == 3) {
final values = saved.map(double.tryParse).toList();
if (!values.contains(null)) {
return (center: LatLng(values[0]!, values[1]!), zoom: values[2]!);
}
}
return (center: const LatLng(20, 0), zoom: _mapMinZoom);
return savedMapCamera() ?? (center: const LatLng(20, 0), zoom: _mapMinZoom);
}
void _scheduleCameraSave() {
+196
View File
@@ -0,0 +1,196 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/snack_bar_builder.dart';
import '../helpers/utf8_length_limiter.dart';
import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
import '../widgets/mesh_nav_tile.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/unsaved_changes_guard.dart';
/// Node name editor showing the bytes left for messages.
class NodeNameScreen extends StatefulWidget {
const NodeNameScreen({super.key});
@override
State<NodeNameScreen> createState() => _NodeNameScreenState();
}
class _NodeNameScreenState extends State<NodeNameScreen> {
final _page = GlobalKey<SaveToRadioPageState>();
late final TextEditingController _controller;
late String _savedName;
@override
void initState() {
super.initState();
final name = context.read<MeshCoreConnector>().selfName ?? '';
// Compared trimmed, like the field.
_savedName = name.trim();
_controller = TextEditingController(text: name)
..addListener(() => setState(() {}));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
String get _name => _controller.text.trim();
Future<bool> _save() async {
final l10n = context.l10n;
final connector = context.read<MeshCoreConnector>();
final name = _name;
await connector.setNodeName(name);
await connector.refreshDeviceInfo();
if (!mounted) return true;
setState(() => _savedName = name);
showDismissibleSnackBar(
context,
content: Text(l10n.settings_nodeNameUpdated),
);
return true;
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final bytes = utf8ByteLength(_name);
final over = bytes - maxRadioNameBytes;
return SaveToRadioPage(
key: _page,
title: l10n.settings_nodeName,
hasChanges: _name != _savedName,
canSave: _name.isNotEmpty && over <= 0,
onSave: _save,
children: [
SectionHeader(l10n.settings_nodeName),
MeshCard(
child: TextField(
controller: _controller,
autofocus: _savedName.isEmpty,
textInputAction: TextInputAction.done,
onSubmitted: (_) => _page.currentState?.save(),
onTapOutside: (_) => FocusScope.of(context).unfocus(),
// No length limit: an over-long name shows how far over it is
// instead of silently refusing input.
decoration: InputDecoration(
labelText: l10n.settings_infoName,
hintText: l10n.settings_nodeNameHint,
errorText: over > 0 ? l10n.nodeName_bytesOver(over) : null,
suffixIcon: Padding(
padding: const EdgeInsetsDirectional.only(start: 8, end: 12),
child: Text(
'$bytes / $maxRadioNameBytes',
style: TextStyle(
fontSize: 12,
color: over > 0 ? scheme.error : scheme.onSurfaceVariant,
),
),
),
suffixIconConstraints: const BoxConstraints(),
),
),
),
SectionHeader(
l10n.nodeName_messageLength,
description: l10n.nodeName_info,
),
_buildMessageLimits(context),
],
);
}
Widget _buildMessageLimits(BuildContext context) {
final l10n = context.l10n;
final name = _name;
// Empty or over-long names can't be saved.
final channelValue =
name.isEmpty || utf8ByteLength(name) > maxRadioNameBytes
? l10n.common_notAvailable
: l10n.nodeName_bytesAvailable(maxChannelMessageBytes(name));
return MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
_LimitRow(
icon: Icons.forum_outlined,
title: l10n.nodeName_channelMessages,
value: channelValue,
subtitle: l10n.nodeName_channelMessagesSubtitle,
),
const Divider(height: 1, indent: 16),
_LimitRow(
icon: Icons.chat_bubble_outline,
title: l10n.nodeName_directMessages,
value: l10n.nodeName_bytesAvailable(maxContactMessageBytes()),
subtitle: l10n.nodeName_directMessagesSubtitle,
),
],
),
);
}
}
/// Settings row with a read-only value: icon, title, the value in mono 15
/// (like the Settings device info values) and a subtitle.
class _LimitRow extends StatelessWidget {
final IconData icon;
final String title;
final String value;
final String subtitle;
const _LimitRow({
required this.icon,
required this.title,
required this.value,
required this.subtitle,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return MergeSemantics(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(icon, size: 24, color: scheme.onSurfaceVariant),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: meshTileTitleStyle(theme)),
const SizedBox(height: 2),
Text(
value,
style: MeshTheme.mono(
fontSize: 15,
fontWeight: FontWeight.w500,
color: scheme.onSurface,
),
),
const SizedBox(height: 2),
Text(
subtitle,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
],
),
),
);
}
}
+205
View File
@@ -0,0 +1,205 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/settings_reveal.dart';
import '../widgets/unsaved_changes_guard.dart';
typedef _PrivacyForm = ({
bool advertLocation,
bool autoZeroHopAdvert,
int multiAcks,
int telemetryBase,
int telemetryLocation,
int telemetryEnvironment,
});
/// Location sharing, ACKs and telemetry permissions. Sent on Save.
class PrivacySettingsScreen extends StatefulWidget {
const PrivacySettingsScreen({super.key});
@override
State<PrivacySettingsScreen> createState() => _PrivacySettingsScreenState();
}
class _PrivacySettingsScreenState extends State<PrivacySettingsScreen> {
late bool _advertLocation;
late bool _autoZeroHopAdvert;
// Raw value: firmware also accepts 2, kept unless the switch is changed.
late int _multiAcks;
late int _telemetryBase;
late int _telemetryLocation;
late int _telemetryEnvironment;
late _PrivacyForm _savedForm;
@override
void initState() {
super.initState();
final connector = context.read<MeshCoreConnector>();
_advertLocation = connector.advertLocationPolicy != 0;
_autoZeroHopAdvert = context
.read<AppSettingsService>()
.settings
.autoSendZeroHopAdvertOnGpsUpdate;
_multiAcks = connector.multiAcks;
_telemetryBase = connector.telemetryModeBase;
_telemetryLocation = connector.telemetryModeLoc;
_telemetryEnvironment = connector.telemetryModeEnv;
_savedForm = _form;
}
_PrivacyForm get _form => (
advertLocation: _advertLocation,
autoZeroHopAdvert: _autoZeroHopAdvert,
multiAcks: _multiAcks,
telemetryBase: _telemetryBase,
telemetryLocation: _telemetryLocation,
telemetryEnvironment: _telemetryEnvironment,
);
Future<bool> _save() async {
final l10n = context.l10n;
final connector = context.read<MeshCoreConnector>();
final settingsService = context.read<AppSettingsService>();
final form = _form;
await connector.setTelemetryModeBase(
form.telemetryBase,
form.telemetryLocation,
form.telemetryEnvironment,
form.advertLocation ? 1 : 0,
form.multiAcks,
);
await settingsService.setAutoSendZeroHopAdvertOnGpsUpdate(
form.autoZeroHopAdvert,
);
await connector.refreshDeviceInfo();
if (!mounted) return true;
setState(() => _savedForm = form);
showDismissibleSnackBar(
context,
content: Text(l10n.settings_telemetryModeUpdated),
);
return true;
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
const switchPadding = EdgeInsets.symmetric(horizontal: 16, vertical: 4);
return SaveToRadioPage(
title: l10n.settings_privacy,
hasChanges: _form != _savedForm,
onSave: _save,
children: [
const SizedBox(height: 8),
MeshInfoCard(l10n.settings_privacySettingsDescription),
SectionHeader(l10n.settings_location),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
SwitchListTile(
contentPadding: switchPadding,
// Same icon as the Location row in Settings.
secondary: const Icon(Icons.location_on_outlined, size: 24),
title: Text(l10n.settings_advertLocation),
subtitle: Text(l10n.settings_advertLocationSubtitle),
value: _advertLocation,
onChanged: (value) => setState(() => _advertLocation = value),
),
SettingsReveal(
visible: _advertLocation,
children: [
SwitchListTile(
contentPadding: switchPadding,
// Same icon as the zero-hop advert action in Contacts.
secondary: const Icon(
Icons.connect_without_contact,
size: 24,
),
title: Text(l10n.settings_autoZeroHopAdvertOnGpsUpdate),
subtitle: Text(
l10n.settings_autoZeroHopAdvertOnGpsUpdateSubtitle,
),
value: _autoZeroHopAdvert,
onChanged: (value) =>
setState(() => _autoZeroHopAdvert = value),
),
],
),
],
),
),
SectionHeader(l10n.appSettings_messaging),
MeshCard(
padding: EdgeInsets.zero,
child: SwitchListTile(
contentPadding: switchPadding,
// Double form of the delivered tick used in chats.
secondary: const Icon(Icons.done_all, size: 24),
title: Text(l10n.settings_multiAck),
subtitle: Text(l10n.settings_multiAckSubtitle),
value: _multiAcks == 1,
onChanged: (value) => setState(() => _multiAcks = value ? 1 : 0),
),
),
SectionHeader(l10n.contact_telemetry),
MeshInfoCard(l10n.settings_telemetryPerContactHint),
MeshCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_telemetryField(
label: l10n.settings_telemetryBaseMode,
value: _telemetryBase,
onChanged: (value) => _telemetryBase = value,
),
const SizedBox(height: 16),
_telemetryField(
label: l10n.settings_telemetryLocationMode,
value: _telemetryLocation,
onChanged: (value) => _telemetryLocation = value,
),
const SizedBox(height: 16),
_telemetryField(
label: l10n.settings_telemetryEnvironmentMode,
value: _telemetryEnvironment,
onChanged: (value) => _telemetryEnvironment = value,
),
],
),
),
],
);
}
Widget _telemetryField({
required String label,
required int value,
required ValueChanged<int> onChanged,
}) {
final l10n = context.l10n;
DropdownMenuItem<int> item(int mode, String text) => DropdownMenuItem(
value: mode,
child: Text(text, maxLines: 1, overflow: TextOverflow.ellipsis),
);
return DropdownButtonFormField<int>(
initialValue: value,
isExpanded: true,
decoration: InputDecoration(labelText: label),
items: [
item(teleModeDeny, l10n.settings_denyAll),
item(teleModeAllowFlags, l10n.settings_allowByContact),
item(teleModeAllowAll, l10n.settings_allowAll),
],
onChanged: (mode) {
if (mode != null) setState(() => onChanged(mode));
},
);
}
}
+958
View File
@@ -0,0 +1,958 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/radio_settings.dart';
import '../services/app_debug_log_service.dart';
import '../theme/mesh_theme.dart';
import '../theme/theme_icons.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/unsaved_changes_guard.dart';
/// Convert device coding-rate value (1-4 on some firmware, 5-8 on others)
/// to the UI enum range (always 5-8).
int _toUiCodingRate(int deviceCr) {
return deviceCr <= 4 ? deviceCr + 4 : deviceCr;
}
const Set<int> _defaultRepeatFreqsKHz = {433000, 869495, 918000};
/// Whether the firmware accepts [freqKHz] for off-grid client repeat, using
/// the ranges from CMD_GET_ALLOWED_REPEAT_FREQ when known.
bool _isAllowedRepeatFreqKHz(MeshCoreConnector connector, int freqKHz) {
final ranges = connector.allowedRepeatFreqRanges;
if (ranges == null || ranges.isEmpty) {
return _defaultRepeatFreqsKHz.contains(freqKHz);
}
return ranges.any((r) => freqKHz >= r.lowKHz && freqKHz <= r.highKHz);
}
/// Lowest TX power companion firmware accepts (CMD_SET_RADIO_TX_POWER).
const int _minTxPowerDbm = -9;
/// Form values compared to detect unsaved edits. Numbers are compared parsed
/// ("869.6" equals "869.600").
typedef _RadioForm = ({
Object frequency,
LoRaBandwidth bandwidth,
LoRaSpreadingFactor spreadingFactor,
LoRaCodingRate codingRate,
Object txPower,
bool clientRepeat,
int pathHashByteWidth,
});
/// Radio parameters, sent on Save. Edits stay if the radio rejects them.
class RadioSettingsScreen extends StatefulWidget {
final MeshCoreConnector connector;
const RadioSettingsScreen({super.key, required this.connector});
@override
State<RadioSettingsScreen> createState() => _RadioSettingsScreenState();
}
class _RadioSettingsScreenState extends State<RadioSettingsScreen> {
final _frequencyController = TextEditingController();
LoRaBandwidth _bandwidth = LoRaBandwidth.bw125;
LoRaSpreadingFactor _spreadingFactor = LoRaSpreadingFactor.sf7;
LoRaCodingRate _codingRate = LoRaCodingRate.cr4_5;
final _txPowerController = TextEditingController(text: '20');
bool _clientRepeat = false;
int _pathHashByteWidth = 1;
int? _selectedPresetIndex;
_RadioSettingsSnapshot? _lastNonRepeatSnapshot;
String? _frequencyError;
String? _txPowerError;
late _RadioForm _savedForm;
bool get _supportsPathHashMode => widget.connector.supportsPathHashMode;
AppDebugLogService get _appLog =>
Provider.of<AppDebugLogService>(context, listen: false);
@override
void initState() {
super.initState();
// Populate with current settings if available
if (widget.connector.currentFreqHz != null) {
_frequencyController.text = (widget.connector.currentFreqHz! / 1000.0)
.toStringAsFixed(3);
} else {
_frequencyController.text = '915.0';
}
if (widget.connector.currentBwHz != null) {
// Find matching bandwidth enum
final bwValue = widget.connector.currentBwHz!;
for (var bw in LoRaBandwidth.values) {
if (bw.hz == bwValue) {
_bandwidth = bw;
break;
}
}
}
if (widget.connector.currentSf != null) {
// Find matching spreading factor enum
final sfValue = widget.connector.currentSf!;
for (var sf in LoRaSpreadingFactor.values) {
if (sf.value == sfValue) {
_spreadingFactor = sf;
break;
}
}
}
if (widget.connector.currentCr != null) {
// Find matching coding rate enum
final crValue = _toUiCodingRate(widget.connector.currentCr!);
for (var cr in LoRaCodingRate.values) {
if (cr.value == crValue) {
_codingRate = cr;
break;
}
}
}
if (widget.connector.currentTxPower != null) {
_txPowerController.text = widget.connector.currentTxPower.toString();
}
_pathHashByteWidth = widget.connector.pathHashByteWidth;
_clientRepeat = widget.connector.clientRepeat ?? false;
_selectedPresetIndex = _findMatchingPresetIndex();
if (_clientRepeat) {
_lastNonRepeatSnapshot =
_sessionRememberedNonRepeatSnapshot() ??
_inferNonRepeatSnapshotForRepeatEnabled();
_selectedPresetIndex = _findMatchingPresetIndexForSnapshot(
_lastNonRepeatSnapshot!,
);
} else {
_lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection();
}
_savedForm = _currentForm();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_logRadioSettingsState('Page initialized');
});
}
_RadioForm _currentForm() {
final frequencyText = _frequencyController.text.trim();
final frequencyMHz = double.tryParse(frequencyText);
final txPowerText = _txPowerController.text.trim();
return (
frequency: frequencyMHz == null
? frequencyText
: (frequencyMHz * 1000).round(),
bandwidth: _bandwidth,
spreadingFactor: _spreadingFactor,
codingRate: _codingRate,
txPower: int.tryParse(txPowerText) ?? txPowerText,
clientRepeat: _clientRepeat,
pathHashByteWidth: _pathHashByteWidth,
);
}
bool get _hasChanges => _currentForm() != _savedForm;
@override
void dispose() {
_frequencyController.dispose();
_txPowerController.dispose();
super.dispose();
}
void _applyPreset(int index) {
setState(() {
_applyPresetState(index);
});
_logRadioSettingsState(
'Applied preset ${RadioSettings.presets[index].$1} (#$index)',
);
}
int? _findMatchingPresetIndex() {
return _findMatchingPresetIndexForSnapshot(_currentSnapshot());
}
int? _findMatchingPresetIndexForSnapshot(_RadioSettingsSnapshot snapshot) {
for (final i in _visiblePresetIndexes()) {
final preset = RadioSettings.presets[i].$2;
if (preset.frequencyHz == snapshot.frequencyHz &&
preset.bandwidth == snapshot.bandwidth &&
preset.spreadingFactor == snapshot.spreadingFactor &&
preset.codingRate == snapshot.codingRate) {
return i;
}
}
return null;
}
Iterable<int> _visiblePresetIndexes() sync* {
for (var i = 0; i < RadioSettings.presets.length; i++) {
if (_isOffGridPresetIndex(i)) {
continue;
}
yield i;
}
}
_RadioSettingsSnapshot _currentSnapshot() {
final frequencyMHz = double.tryParse(_frequencyController.text) ?? 915.0;
final txPowerDbm = int.tryParse(_txPowerController.text) ?? 20;
return _RadioSettingsSnapshot(
frequencyMHz: frequencyMHz,
bandwidth: _bandwidth,
spreadingFactor: _spreadingFactor,
codingRate: _codingRate,
txPowerDbm: txPowerDbm,
);
}
bool _isOffGridPresetIndex(int? index) {
if (index == null) return false;
return RadioSettings.presets[index].$1.startsWith('Off-Grid ');
}
double _offGridFrequencyForBaseFrequency(double baseFrequencyMHz) {
final baseKHz = (baseFrequencyMHz * 1000).round();
final ranges = widget.connector.allowedRepeatFreqRanges;
final candidates = ranges == null || ranges.isEmpty
? _defaultRepeatFreqsKHz
: {for (final r in ranges) baseKHz.clamp(r.lowKHz, r.highKHz)};
final closestKHz = candidates.reduce(
(a, b) => (a - baseKHz).abs() <= (b - baseKHz).abs() ? a : b,
);
return closestKHz / 1000.0;
}
double _normalFrequencyForBand(double frequencyMHz) {
if (frequencyMHz < 500) return 433.650;
if (frequencyMHz < 900) return 869.432;
return 915.8;
}
_RadioSettingsSnapshot _fallbackNonRepeatSnapshot(
double currentFrequencyMHz,
) {
return _RadioSettingsSnapshot(
frequencyMHz: _normalFrequencyForBand(currentFrequencyMHz),
bandwidth: _bandwidth,
spreadingFactor: _spreadingFactor,
codingRate: _codingRate,
txPowerDbm: int.tryParse(_txPowerController.text) ?? 20,
);
}
_RadioSettingsSnapshot _nonRepeatSnapshotForCurrentSelection() {
final current = _currentSnapshot();
if (!_isOffGridPresetIndex(_selectedPresetIndex)) {
return current;
}
return _fallbackNonRepeatSnapshot(current.frequencyMHz);
}
_RadioSettingsSnapshot? _sessionRememberedNonRepeatSnapshot() {
final snapshot = widget.connector.rememberedNonRepeatRadioState;
if (snapshot == null) return null;
return _RadioSettingsSnapshot.fromMeshCoreSnapshot(snapshot);
}
_RadioSettingsSnapshot _inferNonRepeatSnapshotForRepeatEnabled() {
final current = _currentSnapshot();
for (final i in _visiblePresetIndexes()) {
final preset = RadioSettings.presets[i].$2;
final offGridFreqHz =
(_offGridFrequencyForBaseFrequency(preset.frequencyMHz) * 1000)
.round();
if (offGridFreqHz == current.frequencyHz &&
preset.bandwidth == current.bandwidth &&
preset.spreadingFactor == current.spreadingFactor &&
preset.codingRate == current.codingRate) {
return _RadioSettingsSnapshot(
frequencyMHz: preset.frequencyMHz,
bandwidth: preset.bandwidth,
spreadingFactor: preset.spreadingFactor,
codingRate: preset.codingRate,
txPowerDbm: current.txPowerDbm,
);
}
}
return _fallbackNonRepeatSnapshot(current.frequencyMHz);
}
void _applySnapshot(_RadioSettingsSnapshot snapshot) {
_frequencyController.text = snapshot.frequencyMHz.toStringAsFixed(3);
_bandwidth = snapshot.bandwidth;
_spreadingFactor = snapshot.spreadingFactor;
_codingRate = snapshot.codingRate;
_txPowerController.text = snapshot.txPowerDbm.toString();
}
void _applyPresetState(int index) {
final preset = RadioSettings.presets[index].$2;
final baseSnapshot = _RadioSettingsSnapshot(
frequencyMHz: preset.frequencyMHz,
bandwidth: preset.bandwidth,
spreadingFactor: preset.spreadingFactor,
codingRate: preset.codingRate,
txPowerDbm: preset.txPowerDbm,
);
final frequencyMHz = _clientRepeat
? _offGridFrequencyForBaseFrequency(baseSnapshot.frequencyMHz)
: baseSnapshot.frequencyMHz;
_frequencyController.text = frequencyMHz.toString();
_bandwidth = preset.bandwidth;
_spreadingFactor = preset.spreadingFactor;
_codingRate = preset.codingRate;
_txPowerController.text = preset.txPowerDbm.toString();
_selectedPresetIndex = index;
_lastNonRepeatSnapshot = baseSnapshot;
// Programmatic writes skip TextField.onChanged, so clear any stale
// frequency/TX errors here or Save stays disabled.
_validateFields();
}
void _syncPresetSelection() {
final previousPresetIndex = _selectedPresetIndex;
final previousLastNonRepeat = _lastNonRepeatSnapshot;
if (_clientRepeat) {
final baseSnapshot =
previousLastNonRepeat ?? _inferNonRepeatSnapshotForRepeatEnabled();
if (_bandwidth != baseSnapshot.bandwidth ||
_spreadingFactor != baseSnapshot.spreadingFactor ||
_codingRate != baseSnapshot.codingRate ||
(int.tryParse(_txPowerController.text) ?? 20) !=
baseSnapshot.txPowerDbm) {
_lastNonRepeatSnapshot = _RadioSettingsSnapshot(
frequencyMHz: baseSnapshot.frequencyMHz,
bandwidth: _bandwidth,
spreadingFactor: _spreadingFactor,
codingRate: _codingRate,
txPowerDbm: int.tryParse(_txPowerController.text) ?? 20,
);
}
_selectedPresetIndex = _findMatchingPresetIndexForSnapshot(
_lastNonRepeatSnapshot ?? baseSnapshot,
);
if (previousPresetIndex != _selectedPresetIndex ||
previousLastNonRepeat != _lastNonRepeatSnapshot) {
_logRadioSettingsState(
'Preset match updated while repeat enabled: ${_presetLabel(previousPresetIndex)} -> ${_presetLabel(_selectedPresetIndex)}',
);
}
return;
}
_lastNonRepeatSnapshot = _nonRepeatSnapshotForCurrentSelection();
_selectedPresetIndex = _findMatchingPresetIndexForSnapshot(
_lastNonRepeatSnapshot!,
);
if (previousPresetIndex != _selectedPresetIndex ||
previousLastNonRepeat != _lastNonRepeatSnapshot) {
_logRadioSettingsState(
'Preset sync updated state from ${_presetLabel(previousPresetIndex)} to ${_presetLabel(_selectedPresetIndex)}',
);
}
}
void _handleManualSettingsChanged(String source) {
_logRadioSettingsState('Manual settings edit: $source');
setState(() {
_validateFields();
_syncPresetSelection();
});
}
void _validateFields() {
final l10n = context.l10n;
final freqMHz = double.tryParse(_frequencyController.text);
_frequencyError = (freqMHz == null || freqMHz < 150 || freqMHz > 2500)
? l10n.settings_frequencyInvalid
: null;
final maxTxPower = widget.connector.maxTxPower ?? 22;
final txPower = int.tryParse(_txPowerController.text);
_txPowerError =
(txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower)
? l10n.settings_txPowerInvalidRange(_minTxPowerDbm, maxTxPower)
: null;
}
void _handleClientRepeatChanged(bool enabled) {
_logRadioSettingsState(
'Off-grid repeat toggle requested: $_clientRepeat -> $enabled',
);
setState(() {
final currentSnapshot = _currentSnapshot();
if (enabled) {
if (!_clientRepeat) {
_syncPresetSelection();
}
final baseSnapshot = _lastNonRepeatSnapshot ?? currentSnapshot;
_clientRepeat = true;
_frequencyController.text = _offGridFrequencyForBaseFrequency(
baseSnapshot.frequencyMHz,
).toStringAsFixed(3);
_validateFields();
return;
}
_clientRepeat = false;
_applySnapshot(
_lastNonRepeatSnapshot ??
_fallbackNonRepeatSnapshot(currentSnapshot.frequencyMHz),
);
_validateFields();
_syncPresetSelection();
});
_logRadioSettingsState('Off-grid repeat toggle applied');
}
/// Returns whether the radio applied every change.
Future<bool> _saveSettings() async {
final l10n = context.l10n;
final freqMHz = double.tryParse(_frequencyController.text);
final txPower = int.tryParse(_txPowerController.text);
if (freqMHz == null || freqMHz < 150 || freqMHz > 2500) {
showDismissibleSnackBar(
context,
content: Text(l10n.settings_frequencyInvalid),
);
return false;
}
final maxTxPower = widget.connector.maxTxPower ?? 22;
if (txPower == null || txPower < _minTxPowerDbm || txPower > maxTxPower) {
showDismissibleSnackBar(
context,
content: Text(
l10n.settings_txPowerInvalidRange(_minTxPowerDbm, maxTxPower),
),
);
return false;
}
final freqHz = (freqMHz * 1000).round();
final bwHz = _bandwidth.hz;
final sf = _spreadingFactor.value;
final cr = _codingRate.value;
// if the client repeat isnt null then we know its supported
//otherwise we leave it out of the frame to avoid accidentally enabling
final knownRepeat = widget.connector.clientRepeat != null;
if (knownRepeat) {
if (_clientRepeat && !_isAllowedRepeatFreqKHz(widget.connector, freqHz)) {
showDismissibleSnackBar(
context,
content: Text(l10n.settings_clientRepeatFreqWarning),
);
return false;
}
}
try {
_logRadioSettingsState('Saving radio settings');
final accepted = await widget.connector.setRadioParams(
freqHz,
bwHz,
sf,
cr,
clientRepeat: knownRepeat ? _clientRepeat : null,
);
if (!accepted) {
_logRadioSettingsState('Radio rejected requested settings');
if (!mounted) return false;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_radioSettingsNotApplied),
);
return false;
}
await widget.connector.sendFrame(buildSetRadioTxPowerFrame(txPower));
// 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();
// 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,
sf: sf,
cr: cr,
txPower: txPower,
clientRepeat: knownRepeat ? _clientRepeat : null,
),
onError: (_) => true,
);
if (!radioApplied) {
_logRadioSettingsState('Radio did not apply requested settings');
if (!mounted) return false;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_radioSettingsNotApplied),
);
return false;
}
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 false;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_pathHashModeNotApplied),
);
return false;
}
final rememberedSnapshot = _clientRepeat
? _lastNonRepeatSnapshot
: _currentSnapshot();
if (rememberedSnapshot != null) {
widget.connector.rememberNonRepeatRadioState(
rememberedSnapshot.toMeshCoreSnapshot(),
);
}
if (!mounted) return true;
_logRadioSettingsState('Radio settings saved successfully');
setState(() => _savedForm = _currentForm());
showDismissibleSnackBar(
context,
content: Text(l10n.settings_radioSettingsUpdated),
);
return true;
} catch (e) {
_appLog.warn('Radio settings save failed: $e', tag: 'RadioSettings');
if (!mounted) return false;
// Keep the edits so the user can retry.
showDismissibleSnackBar(
context,
content: Text(l10n.settings_error(e.toString())),
);
return false;
}
}
bool _deviceMatches({
required int freqHz,
required int bwHz,
required int sf,
required int cr,
required int txPower,
required bool? clientRepeat,
}) {
final c = widget.connector;
// Firmware stores freq/bw as float MHz/kHz, so allow 1 unit of rounding.
return c.currentFreqHz != null &&
(c.currentFreqHz! - freqHz).abs() <= 1 &&
c.currentBwHz != null &&
(c.currentBwHz! - bwHz).abs() <= 1 &&
c.currentSf == sf &&
c.currentCr != null &&
_toUiCodingRate(c.currentCr!) == cr &&
c.currentTxPower == txPower &&
(clientRepeat == null || c.clientRepeat == clientRepeat);
}
String _presetLabel(int? index) {
if (index == null) {
return 'custom';
}
return '${RadioSettings.presets[index].$1} (#$index)';
}
String _formatSnapshot(_RadioSettingsSnapshot? snapshot) {
if (snapshot == null) {
return 'null';
}
return '${snapshot.frequencyMHz.toStringAsFixed(3)}MHz/'
'${snapshot.bandwidth.label}/'
'${snapshot.spreadingFactor.label}/'
'${snapshot.codingRate.label}/'
'${snapshot.txPowerDbm}dBm';
}
void _logRadioSettingsState(String message) {
if (!kDebugMode) return;
_appLog.info(
'$message | '
'freq=${_frequencyController.text}MHz '
'bw=${_bandwidth.label} '
'sf=${_spreadingFactor.label} '
'cr=${_codingRate.label} '
'tx=${_txPowerController.text}dBm '
'pathHash=${_pathHashByteWidth}B '
'repeat=$_clientRepeat '
'preset=${_presetLabel(_selectedPresetIndex)} '
'lastNonRepeat=${_formatSnapshot(_lastNonRepeatSnapshot)}',
tag: 'RadioSettings',
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return SaveToRadioPage(
title: l10n.settings_radioSettings,
hasChanges: _hasChanges,
canSave: _frequencyError == null && _txPowerError == null,
onSave: _saveSettings,
children: [
SectionHeader(l10n.settings_radioParameters),
MeshCard(child: _buildPresetField(context)),
MeshCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: _buildParameterFields(context),
),
),
if (widget.connector.clientRepeat != null) ...[
SectionHeader(l10n.settings_clientRepeat),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_offGridText(context, l10n.settings_clientRepeatDescription),
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
secondary: const ThemedIcon(ThemeIconSlot.repeater, size: 24),
title: Text(l10n.settings_clientRepeatSwitch),
value: _clientRepeat,
onChanged: _handleClientRepeatChanged,
),
const Divider(height: 1, indent: 16, endIndent: 16),
_offGridText(context, l10n.settings_clientRepeatNote),
],
),
),
],
],
);
}
/// Explanation text in the Off-Grid card, styled like tile subtitles.
Widget _offGridText(BuildContext context, String text) {
final theme = Theme.of(context);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Text(
text,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
);
}
Widget _buildPresetField(BuildContext context) {
final l10n = context.l10n;
return DropdownButtonFormField<int>(
key: ValueKey<int?>(_selectedPresetIndex),
initialValue: _selectedPresetIndex ?? -1,
isExpanded: true,
decoration: InputDecoration(labelText: l10n.settings_presets),
items: [
if (_selectedPresetIndex == null)
DropdownMenuItem(value: -1, child: Text(l10n.settings_presetCustom)),
for (final i in _visiblePresetIndexes())
DropdownMenuItem(
value: i,
child: Text(
RadioSettings.presets[i].$1,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
onChanged: (index) {
if (index != null && index >= 0) {
_applyPreset(index);
}
},
);
}
List<Widget> _buildParameterFields(BuildContext context) {
final l10n = context.l10n;
return [
TextField(
controller: _frequencyController,
onTapOutside: (_) => FocusScope.of(context).unfocus(),
onChanged: (_) => _handleManualSettingsChanged('frequency'),
decoration: InputDecoration(
labelText: l10n.settings_frequency,
helperText: _clientRepeat
? l10n.settings_clientRepeatFrequencyNote(
_frequencyController.text,
)
: l10n.settings_frequencyHelper,
helperMaxLines: 3,
errorText: _frequencyError,
errorMaxLines: 3,
),
keyboardType: const TextInputType.numberWithOptions(decimal: true),
),
const SizedBox(height: 16),
DropdownButtonFormField<LoRaBandwidth>(
isExpanded: true,
initialValue: _bandwidth,
decoration: InputDecoration(labelText: l10n.settings_bandwidth),
items: LoRaBandwidth.values
.map(
(bw) => DropdownMenuItem(
value: bw,
child: Text(bw.label, overflow: TextOverflow.ellipsis),
),
)
.toList(),
onChanged: (value) {
if (value != null) {
setState(() {
_bandwidth = value;
_syncPresetSelection();
});
_logRadioSettingsState('Manual settings edit: bandwidth');
}
},
),
const SizedBox(height: 16),
DropdownButtonFormField<LoRaSpreadingFactor>(
isExpanded: true,
initialValue: _spreadingFactor,
decoration: InputDecoration(labelText: l10n.settings_spreadingFactor),
items: LoRaSpreadingFactor.values
.map(
(sf) => DropdownMenuItem(
value: sf,
child: Text(sf.label, overflow: TextOverflow.ellipsis),
),
)
.toList(),
onChanged: (value) {
if (value != null) {
setState(() {
_spreadingFactor = value;
_syncPresetSelection();
});
_logRadioSettingsState('Manual settings edit: spreading factor');
}
},
),
const SizedBox(height: 16),
DropdownButtonFormField<LoRaCodingRate>(
isExpanded: true,
initialValue: _codingRate,
decoration: InputDecoration(labelText: l10n.settings_codingRate),
items: LoRaCodingRate.values
.map(
(cr) => DropdownMenuItem(
value: cr,
child: Text(cr.label, overflow: TextOverflow.ellipsis),
),
)
.toList(),
onChanged: (value) {
if (value != null) {
setState(() {
_codingRate = value;
_syncPresetSelection();
});
_logRadioSettingsState('Manual settings edit: coding rate');
}
},
),
const SizedBox(height: 16),
TextField(
controller: _txPowerController,
onTapOutside: (_) => FocusScope.of(context).unfocus(),
onChanged: (_) => _handleManualSettingsChanged('tx power'),
decoration: InputDecoration(
labelText: l10n.settings_txPower,
helperText: l10n.settings_txPowerRangeHelper(
_minTxPowerDbm,
widget.connector.maxTxPower ?? 22,
),
helperMaxLines: 3,
errorText: _txPowerError,
errorMaxLines: 3,
),
keyboardType: TextInputType.number,
),
if (_supportsPathHashMode) ...[
const SizedBox(height: 16),
_buildPathHashField(context),
],
];
}
/// The helper text, with the quoted example IDs ("ab12") in monospace like
/// other hashes. A widget helper has no line limit.
Widget _pathHashHelper(BuildContext context, String text) {
final theme = Theme.of(context);
final style = theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
final mono = MeshTheme.mono(fontSize: style?.fontSize, color: style?.color);
final spans = <TextSpan>[];
var last = 0;
for (final m in RegExp(r'"[^"\n]+"').allMatches(text)) {
spans.add(TextSpan(text: text.substring(last, m.start)));
spans.add(TextSpan(text: m[0], style: mono));
last = m.end;
}
spans.add(TextSpan(text: text.substring(last)));
return Text.rich(TextSpan(style: style, children: spans));
}
Widget _buildPathHashField(BuildContext context) {
final l10n = context.l10n;
// Values are path hash modes (0-2, byte width - 1), matching the
// selector in repeater_settings_screen.
return DropdownButtonFormField<int>(
isExpanded: true,
initialValue: (_pathHashByteWidth - 1).clamp(0, 2).toInt(),
decoration: InputDecoration(
labelText: l10n.repeater_pathHashMode,
helper: _pathHashHelper(context, l10n.settings_pathHashModeHelper),
),
items: [
DropdownMenuItem(
value: 0,
child: Text(
l10n.repeater_pathHashModeOption0,
overflow: TextOverflow.ellipsis,
),
),
DropdownMenuItem(
value: 1,
child: Text(
l10n.repeater_pathHashModeOption1,
overflow: TextOverflow.ellipsis,
),
),
DropdownMenuItem(
value: 2,
child: Text(
l10n.repeater_pathHashModeOption2,
overflow: TextOverflow.ellipsis,
),
),
],
onChanged: (value) {
if (value == null) return;
setState(() => _pathHashByteWidth = value + 1);
_logRadioSettingsState('Manual settings edit: path hash size');
},
);
}
}
class _RadioSettingsSnapshot {
final double frequencyMHz;
final LoRaBandwidth bandwidth;
final LoRaSpreadingFactor spreadingFactor;
final LoRaCodingRate codingRate;
final int txPowerDbm;
const _RadioSettingsSnapshot({
required this.frequencyMHz,
required this.bandwidth,
required this.spreadingFactor,
required this.codingRate,
required this.txPowerDbm,
});
/// Frequency in integer Hz — avoids floating-point comparison issues.
int get frequencyHz => (frequencyMHz * 1000).round();
/// Convert from the connector's raw-int snapshot to UI-enum snapshot.
static _RadioSettingsSnapshot? fromMeshCoreSnapshot(
MeshCoreRadioStateSnapshot snapshot,
) {
final bw = LoRaBandwidth.values
.where((b) => b.hz == snapshot.bwHz)
.firstOrNull;
final sf = LoRaSpreadingFactor.values
.where((s) => s.value == snapshot.sf)
.firstOrNull;
final cr = LoRaCodingRate.values
.where((c) => c.value == _toUiCodingRate(snapshot.cr))
.firstOrNull;
if (bw == null || sf == null || cr == null) return null;
return _RadioSettingsSnapshot(
frequencyMHz: snapshot.freqHz / 1000.0,
bandwidth: bw,
spreadingFactor: sf,
codingRate: cr,
txPowerDbm: snapshot.txPowerDbm,
);
}
/// Convert back to the connector's raw-int snapshot.
MeshCoreRadioStateSnapshot toMeshCoreSnapshot() {
return MeshCoreRadioStateSnapshot(
freqHz: frequencyHz,
bwHz: bandwidth.hz,
sf: spreadingFactor.value,
cr: codingRate.value,
txPowerDbm: txPowerDbm,
);
}
@override
bool operator ==(Object other) {
return other is _RadioSettingsSnapshot &&
frequencyHz == other.frequencyHz &&
bandwidth == other.bandwidth &&
spreadingFactor == other.spreadingFactor &&
codingRate == other.codingRate &&
txPowerDbm == other.txPowerDbm;
}
@override
int get hashCode => Object.hash(
frequencyHz,
bandwidth,
spreadingFactor,
codingRate,
txPowerDbm,
);
}
+25 -803
View File
@@ -1,22 +1,23 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshcore_open/widgets/elements_ui.dart';
import 'package:provider/provider.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import '../theme/mesh_theme.dart';
import '../widgets/app_bar.dart';
import '../helpers/snack_bar_builder.dart';
import '../helpers/utf8_length_limiter.dart';
import '../widgets/mesh_nav_tile.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../widgets/mesh_ui.dart';
import '../widgets/settings_reveal.dart';
import '../widgets/radio_settings_dialog.dart';
import 'about_screen.dart';
import 'app_settings_screen.dart';
import 'contact_settings_screen.dart';
import 'location_settings_screen.dart';
import 'node_name_screen.dart';
import 'privacy_settings_screen.dart';
import 'radio_settings_screen.dart';
import 'app_debug_log_screen.dart';
import 'message_filter_settings_screen.dart';
import 'ble_debug_log_screen.dart';
@@ -38,20 +39,8 @@ class SettingsScreen extends StatefulWidget {
class _SettingsScreenState extends State<SettingsScreen> {
bool _showBatteryVoltage = false;
bool _deviceInfoExpanded = false;
String _appVersion = '';
@override
void initState() {
super.initState();
_loadVersionInfo();
}
Future<void> _loadVersionInfo() async {
final packageInfo = await PackageInfo.fromPlatform();
if (!mounted) return;
setState(() {
_appVersion = '${packageInfo.version} BETA';
});
void _push(BuildContext context, Widget page) {
Navigator.push(context, MaterialPageRoute<void>(builder: (_) => page));
}
@override
@@ -59,11 +48,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
final l10n = context.l10n;
return Scaffold(
appBar: AppBar(
title: AppBarTitle(
l10n.settings_title,
indicators: false,
subtitle: false,
),
// A plain title: AppBarTitle fills the bar and stays left-aligned.
title: AdaptiveAppBarTitle(l10n.settings_title),
centerTitle: true,
bottom: const SyncProgressAppBarBottom(),
),
@@ -186,7 +172,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
const Divider(height: 1, indent: 16),
MeshNavTile(
icon: Icons.download_outlined,
title: l10n.settings_export,
title: l10n.settings_exportData,
subtitle: l10n.settings_exportSubtitle,
onTap: () => Navigator.push(
context,
@@ -210,12 +196,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
padding: EdgeInsets.zero,
child: MeshNavTile(
icon: Icons.info_outline,
title: l10n.settings_about,
subtitle: l10n.settings_aboutVersion(
_appVersion.isEmpty ? l10n.common_loading : _appVersion,
),
showChevron: false,
onTap: () => _showAbout(context),
title: l10n.settings_aboutTheApp,
onTap: () => _push(context, const AboutScreen()),
),
),
],
@@ -549,7 +531,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
subtitle: connected
? connector.selfName ?? l10n.settings_nodeNameNotSet
: offline,
onTap: connected ? () => _editNodeName(context, connector) : null,
onTap: connected
? () => _push(context, const NodeNameScreen())
: null,
),
const Divider(height: 1, indent: 16),
MeshNavTile(
@@ -557,7 +541,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
title: l10n.settings_radioSettings,
subtitle: connected ? l10n.settings_radioSettingsSubtitle : offline,
onTap: connected
? () => _showRadioSettings(context, connector)
? () => _push(context, RadioSettingsScreen(connector: connector))
: null,
),
const Divider(height: 1, indent: 16),
@@ -606,7 +590,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
icon: Icons.location_on_outlined,
title: l10n.settings_location,
subtitle: connected ? l10n.settings_locationSubtitle : offline,
onTap: connected ? () => _editLocation(context, connector) : null,
onTap: connected
? () => _push(context, const LocationSettingsScreen())
: null,
),
const Divider(height: 1, indent: 16),
MeshNavTile(
@@ -614,7 +600,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
title: l10n.settings_contactSettings,
subtitle: connected ? l10n.settings_contactSettingsSubtitle : offline,
onTap: connected
? () => _editAutoAddConfig(context, connector)
? () => _push(context, const ContactSettingsScreen())
: null,
),
const Divider(height: 1, indent: 16),
@@ -622,7 +608,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
icon: Icons.visibility_off_outlined,
title: l10n.settings_privacy,
subtitle: connected ? l10n.settings_privacySubtitle : offline,
onTap: connected ? () => _privacySettings(context, connector) : null,
onTap: connected
? () => _push(context, const PrivacySettingsScreen())
: null,
),
],
);
@@ -707,105 +695,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
Future<void> _editNodeName(
BuildContext context,
MeshCoreConnector connector,
) async {
final l10n = context.l10n;
final name = await showDialog<String>(
context: context,
builder: (_) => _NodeNameDialog(initialName: connector.selfName ?? ''),
);
if (name == null || !context.mounted) return;
if (!_ensureConnected(context, connector)) return;
try {
await connector.setNodeName(name);
await connector.refreshDeviceInfo();
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_nodeNameUpdated),
);
} catch (e) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_error(e.toString())),
);
}
}
void _showRadioSettings(BuildContext context, MeshCoreConnector connector) {
showDialog(
context: context,
builder: (context) => RadioSettingsDialog(connector: connector),
);
}
Future<void> _editLocation(
BuildContext context,
MeshCoreConnector connector,
) async {
final l10n = context.l10n;
final settingsService = context.read<AppSettingsService>();
// Safe access to custom vars - may be null before device responds
final customVars = connector.currentCustomVars ?? {};
final bool hasGPS = customVars.containsKey("gps");
final bool initialGPSEnabled = customVars["gps"] == "1";
final edit = await showDialog<_LocationEdit>(
context: context,
builder: (_) => _LocationDialog(
latitude: connector.selfLatitude,
longitude: connector.selfLongitude,
hasGPS: hasGPS,
initialGPSEnabled: initialGPSEnabled,
initialIntervalSeconds: settingsService.resolvedGpsIntervalSeconds(
customVars,
),
),
);
if (edit == null || !edit.hasChanges || !context.mounted) return;
if (!_ensureConnected(context, connector)) return;
try {
final gpsEnabled = edit.gpsEnabled;
if (gpsEnabled != null) {
await connector.setCustomVar(gpsEnabled ? "gps:1" : "gps:0");
}
final interval = edit.intervalSeconds;
if (interval != null) {
await settingsService.setGpsIntervalSeconds(
interval,
writeToDevice: (value) =>
connector.setCustomVar("gps_interval:$value"),
);
}
final lat = edit.latitude;
final lon = edit.longitude;
if (lat != null && lon != null) {
await connector.setNodeLocation(lat: lat, lon: lon);
}
await connector.refreshDeviceInfo();
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(
edit.clearsLocation
? l10n.settings_locationCleared
: l10n.settings_locationUpdated,
),
);
} catch (e) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_error(e.toString())),
);
}
}
Future<void> _syncTime(
BuildContext context,
MeshCoreConnector connector,
@@ -886,671 +775,4 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
);
}
void _showAbout(BuildContext context) {
final l10n = context.l10n;
showAboutDialog(
context: context,
applicationName: l10n.appTitle,
applicationVersion: _appVersion.isEmpty
? l10n.common_loading
: _appVersion,
applicationLegalese: l10n.settings_aboutLegalese,
children: [
const SizedBox(height: 16),
Text(l10n.settings_aboutDescription),
],
);
}
void _editAutoAddConfig(BuildContext context, MeshCoreConnector connector) {
final l10n = context.l10n;
// The dialog's context is gone once it pops; report through the screen.
final screenContext = context;
bool autoAddChat = false;
bool autoAddRepeater = false;
bool autoAddRoomServer = false;
bool autoAddSensor = false;
bool overwriteOldest = false;
final appSettingsService = context.read<AppSettingsService>();
bool evictDiscoveredContactsEnabled =
appSettingsService.settings.evictDiscoveredContactsEnabled;
bool saving = false;
final connector = context.read<MeshCoreConnector>();
autoAddChat = connector.autoAddUsers ?? false;
autoAddRepeater = connector.autoAddRepeaters ?? false;
autoAddRoomServer = connector.autoAddRoomServers ?? false;
autoAddSensor = connector.autoAddSensors ?? false;
overwriteOldest = connector.autoAddOverwriteOldest ?? false;
showDialog(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog(
title: Text(l10n.contactsSettings_autoAddTitle),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FeatureToggleRow(
title: l10n.contactsSettings_autoAddUsersTitle,
subtitle: l10n.contactsSettings_autoAddUsersSubtitle,
value: autoAddChat,
onChanged: (value) {
setDialogState(() => autoAddChat = value);
},
),
const SizedBox(height: 8),
FeatureToggleRow(
title: l10n.contactsSettings_autoAddRepeatersTitle,
subtitle: l10n.contactsSettings_autoAddRepeatersSubtitle,
value: autoAddRepeater,
onChanged: (value) {
setDialogState(() => autoAddRepeater = value);
},
),
const SizedBox(height: 8),
FeatureToggleRow(
title: l10n.contactsSettings_autoAddRoomServersTitle,
subtitle: l10n.contactsSettings_autoAddRoomServersSubtitle,
value: autoAddRoomServer,
onChanged: (value) {
setDialogState(() => autoAddRoomServer = value);
},
),
const SizedBox(height: 8),
FeatureToggleRow(
title: l10n.contactsSettings_autoAddSensorsTitle,
subtitle: l10n.contactsSettings_autoAddSensorsSubtitle,
value: autoAddSensor,
onChanged: (value) {
setDialogState(() => autoAddSensor = value);
},
),
const Divider(height: 4),
FeatureToggleRow(
title: l10n.contactsSettings_overwriteOldestTitle,
subtitle: l10n.contactsSettings_overwriteOldestSubtitle,
value: overwriteOldest,
onChanged: (value) {
setDialogState(() => overwriteOldest = value);
},
),
const Divider(height: 4),
FeatureToggleRow(
title: l10n.contactsSettings_evictDiscoveredContactsTitle,
subtitle: l10n
.contactsSettings_evictDiscoveredContactsSubtitle(
MeshCoreConnector.maxDiscoveredContacts,
),
value: evictDiscoveredContactsEnabled,
onChanged: (value) {
setDialogState(
() => evictDiscoveredContactsEnabled = value,
);
},
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: saving
? null
: () async {
if (!_ensureConnected(context, connector)) return;
setDialogState(() => saving = true);
try {
await _sendSettings(
connector,
autoAddChat,
autoAddRepeater,
autoAddRoomServer,
autoAddSensor,
overwriteOldest,
);
await appSettingsService
.setEvictDiscoveredContactsEnabled(
evictDiscoveredContactsEnabled,
);
if (evictDiscoveredContactsEnabled) {
await connector.trimDiscoveredContactsToLimit();
}
} catch (e) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_error(e.toString())),
);
setDialogState(() => saving = false);
return;
}
if (!context.mounted) return;
Navigator.pop(context);
showDismissibleSnackBar(
screenContext,
content: Text(l10n.settings_contactSettingsSaved),
);
},
child: Text(l10n.common_save),
),
],
),
),
);
}
Future<void> _sendSettings(
MeshCoreConnector connector,
bool autoAddChat,
bool autoAddRepeater,
bool autoAddRoomServer,
bool autoAddSensor,
bool overwriteOldest,
) async {
final frame = buildSetAutoAddConfigFrame(
autoAddChat: autoAddChat,
autoAddRepeater: autoAddRepeater,
autoAddRoomServer: autoAddRoomServer,
autoAddSensor: autoAddSensor,
overwriteOldest: overwriteOldest,
);
await connector.sendFrame(frame);
await connector.sendFrame(buildGetAutoAddFlagsFrame());
}
}
void _privacySettings(BuildContext context, MeshCoreConnector connector) {
final l10n = context.l10n;
final settingsService = context.read<AppSettingsService>();
int telemetryMode = connector.telemetryModeBase;
int telemetryLocMode = connector.telemetryModeLoc;
int telemetryEnvMode = connector.telemetryModeEnv;
bool advertLocPolicy = connector.advertLocationPolicy == 0 ? false : true;
int multiAcks = connector.multiAcks;
bool autoZeroHopAdvertOnGpsUpdate =
settingsService.settings.autoSendZeroHopAdvertOnGpsUpdate;
final telemModeBase = [
DropdownMenuItem(
value: teleModeDeny,
child: Text(
l10n.settings_denyAll,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
DropdownMenuItem(
value: teleModeAllowFlags,
child: Text(
l10n.settings_allowByContact,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
DropdownMenuItem(
value: teleModeAllowAll,
child: Text(
l10n.settings_allowAll,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
];
showDialog(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (builderContext, setDialogState) => AlertDialog(
insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
title: Text(l10n.settings_privacy),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(l10n.settings_privacySettingsDescription),
const SizedBox(height: 16),
FeatureToggleRow(
title: l10n.settings_advertLocation,
subtitle: l10n.settings_advertLocationSubtitle,
value: advertLocPolicy,
onChanged: (value) {
setDialogState(() => advertLocPolicy = value);
},
),
const SizedBox(height: 8),
FeatureToggleRow(
title: l10n.settings_autoZeroHopAdvertOnGpsUpdate,
subtitle: l10n.settings_autoZeroHopAdvertOnGpsUpdateSubtitle,
value: autoZeroHopAdvertOnGpsUpdate,
enabled: advertLocPolicy,
onChanged: advertLocPolicy
? (value) {
setDialogState(
() => autoZeroHopAdvertOnGpsUpdate = value,
);
}
: null,
),
const SizedBox(height: 8),
FeatureToggleRow(
title: l10n.settings_multiAck,
subtitle: l10n.settings_multiAckSubtitle,
value: multiAcks == 1,
onChanged: (value) {
setDialogState(() => multiAcks = value ? 1 : 0);
},
),
const SizedBox(height: 16),
DropdownButtonFormField<int>(
initialValue: telemetryMode,
isExpanded: true,
decoration: InputDecoration(
labelText: l10n.settings_telemetryBaseMode,
border: const OutlineInputBorder(),
),
items: telemModeBase,
onChanged: (value) {
if (value != null) {
setDialogState(() => telemetryMode = value);
}
},
),
const SizedBox(height: 16),
DropdownButtonFormField<int>(
initialValue: telemetryLocMode,
isExpanded: true,
decoration: InputDecoration(
labelText: l10n.settings_telemetryLocationMode,
border: const OutlineInputBorder(),
),
items: telemModeBase,
onChanged: (value) {
if (value != null) {
setDialogState(() => telemetryLocMode = value);
}
},
),
const SizedBox(height: 16),
DropdownButtonFormField<int>(
initialValue: telemetryEnvMode,
isExpanded: true,
decoration: InputDecoration(
labelText: l10n.settings_telemetryEnvironmentMode,
border: const OutlineInputBorder(),
),
items: telemModeBase,
onChanged: (value) {
if (value != null) {
setDialogState(() => telemetryEnvMode = value);
}
},
),
const SizedBox(height: 8),
Text(
l10n.settings_telemetryPerContactHint,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: () async {
Navigator.pop(dialogContext);
if (!connector.isConnected) {
showDismissibleSnackBar(
context,
content: Text(l10n.settings_notConnectedError),
);
return;
}
try {
await connector.setTelemetryModeBase(
telemetryMode,
telemetryLocMode,
telemetryEnvMode,
advertLocPolicy ? 1 : 0,
multiAcks,
);
await settingsService.setAutoSendZeroHopAdvertOnGpsUpdate(
autoZeroHopAdvertOnGpsUpdate,
);
await connector.refreshDeviceInfo();
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_telemetryModeUpdated),
);
} catch (e) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_error(e.toString())),
);
}
},
child: Text(l10n.common_save),
),
],
),
),
);
}
/// Node-name editor. Owns (and disposes) its controller; pops with the
/// trimmed name on Save, or null on Cancel.
class _NodeNameDialog extends StatefulWidget {
final String initialName;
const _NodeNameDialog({required this.initialName});
@override
State<_NodeNameDialog> createState() => _NodeNameDialogState();
}
class _NodeNameDialogState extends State<_NodeNameDialog> {
late final TextEditingController _controller = TextEditingController(
text: widget.initialName,
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return AlertDialog(
title: Text(l10n.settings_nodeName),
content: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: l10n.settings_nodeNameHint,
border: const OutlineInputBorder(),
),
inputFormatters: const [
Utf8LengthLimitingTextInputFormatter(maxRadioNameBytes),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final name = _controller.text.trim();
return TextButton(
onPressed: name.isEmpty
? null
: () => Navigator.pop(context, name),
child: Text(l10n.common_save),
);
},
),
],
);
}
}
/// What the location dialog asks the screen to apply. Null fields are left
/// unchanged on the device.
class _LocationEdit {
final bool? gpsEnabled;
final int? intervalSeconds;
final double? latitude;
final double? longitude;
final bool clearsLocation;
const _LocationEdit({
this.gpsEnabled,
this.intervalSeconds,
this.latitude,
this.longitude,
this.clearsLocation = false,
});
bool get hasChanges =>
gpsEnabled != null ||
intervalSeconds != null ||
(latitude != null && longitude != null);
}
/// Location / GPS editor. Owns (and disposes) its controllers and validates
/// every field before closing, reporting each error under the field it
/// belongs to.
class _LocationDialog extends StatefulWidget {
final double? latitude;
final double? longitude;
final bool hasGPS;
final bool initialGPSEnabled;
final int initialIntervalSeconds;
const _LocationDialog({
required this.latitude,
required this.longitude,
required this.hasGPS,
required this.initialGPSEnabled,
required this.initialIntervalSeconds,
});
@override
State<_LocationDialog> createState() => _LocationDialogState();
}
class _LocationDialogState extends State<_LocationDialog> {
late final TextEditingController _latController;
late final TextEditingController _lonController;
late final TextEditingController _intervalController;
late bool _isGPSEnabled = widget.initialGPSEnabled;
String? _latError;
String? _lonError;
String? _intervalError;
/// Firmware stores "no location" as 0,0 (the default for a fresh node), so
/// that pair is shown as empty fields rather than a real coordinate.
bool get _hasLocation {
final lat = widget.latitude;
final lon = widget.longitude;
return lat != null && lon != null && !(lat == 0 && lon == 0);
}
@override
void initState() {
super.initState();
_latController = TextEditingController(
text: _hasLocation ? widget.latitude!.toStringAsFixed(6) : '',
);
_lonController = TextEditingController(
text: _hasLocation ? widget.longitude!.toStringAsFixed(6) : '',
);
_intervalController = TextEditingController(
text: widget.initialIntervalSeconds.toString(),
);
}
@override
void dispose() {
_latController.dispose();
_lonController.dispose();
_intervalController.dispose();
super.dispose();
}
void _save() {
final l10n = context.l10n;
// Validate every field before closing so a typo doesn't discard the
// input or leave half the changes applied.
int? interval;
String? intervalError;
if (widget.hasGPS) {
final intervalText = _intervalController.text.trim();
if (intervalText.isNotEmpty) {
interval = int.tryParse(intervalText);
if (interval == null || interval < 60 || interval >= 86400) {
intervalError = l10n.settings_locationIntervalInvalid;
}
}
}
final latText = _latController.text.trim();
final lonText = _lonController.text.trim();
double? lat;
double? lon;
String? latError;
String? lonError;
var clearsLocation = false;
if (latText.isEmpty && lonText.isEmpty) {
// Clearing both fields removes the location. Companion firmware has no
// dedicated "clear" command: CMD_SET_ADVERT_LATLON with 0,0 restores
// the factory default, which firmware and this app treat as unset.
if (_hasLocation) {
lat = 0;
lon = 0;
clearsLocation = true;
}
} else {
// One empty field keeps the device's current value for that axis.
lat = latText.isNotEmpty
? double.tryParse(latText)
: (_hasLocation ? widget.latitude : null);
lon = lonText.isNotEmpty
? double.tryParse(lonText)
: (_hasLocation ? widget.longitude : null);
if (lat == null) {
latError = latText.isEmpty
? l10n.settings_locationBothRequired
: l10n.settings_locationInvalid;
} else if (lat < -90 || lat > 90) {
latError = l10n.settings_locationInvalid;
}
if (lon == null) {
lonError = lonText.isEmpty
? l10n.settings_locationBothRequired
: l10n.settings_locationInvalid;
} else if (lon < -180 || lon > 180) {
lonError = l10n.settings_locationInvalid;
}
}
if (intervalError != null || latError != null || lonError != null) {
setState(() {
_intervalError = intervalError;
_latError = latError;
_lonError = lonError;
});
return;
}
Navigator.pop(
context,
_LocationEdit(
gpsEnabled: widget.hasGPS && _isGPSEnabled != widget.initialGPSEnabled
? _isGPSEnabled
: null,
intervalSeconds: interval,
latitude: lat,
longitude: lon,
clearsLocation: clearsLocation,
),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
const coordinateKeyboard = TextInputType.numberWithOptions(
decimal: true,
signed: true,
);
return AlertDialog(
title: Text(l10n.settings_location),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _latController,
onChanged: (_) {
if (_latError != null) setState(() => _latError = null);
},
decoration: InputDecoration(
labelText: l10n.settings_latitude,
border: const OutlineInputBorder(),
errorText: _latError,
errorMaxLines: 2,
),
keyboardType: coordinateKeyboard,
),
const SizedBox(height: 16),
TextField(
controller: _lonController,
onChanged: (_) {
if (_lonError != null) setState(() => _lonError = null);
},
decoration: InputDecoration(
labelText: l10n.settings_longitude,
border: const OutlineInputBorder(),
helperText: l10n.settings_locationClearHelper,
helperMaxLines: 2,
errorText: _lonError,
errorMaxLines: 2,
),
keyboardType: coordinateKeyboard,
),
if (widget.hasGPS) ...[
const SizedBox(height: 16),
TextField(
controller: _intervalController,
onChanged: (_) {
if (_intervalError != null) {
setState(() => _intervalError = null);
}
},
decoration: InputDecoration(
labelText: l10n.settings_locationIntervalSec,
border: const OutlineInputBorder(),
errorText: _intervalError,
),
keyboardType: const TextInputType.numberWithOptions(
decimal: false,
signed: false,
),
),
const SizedBox(height: 16),
FeatureToggleRow(
title: l10n.settings_locationGPSEnable,
subtitle: l10n.settings_locationGPSEnableSubtitle,
value: _isGPSEnabled,
// Applied on Save so Cancel leaves the device untouched.
onChanged: (value) => setState(() => _isGPSEnabled = value),
),
],
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
TextButton(onPressed: _save, child: Text(l10n.common_save)),
],
);
}
}