feat: Implement Windows runner for Flutter application

- Added FlutterWindow class to manage the Flutter view within a Win32 window.
- Created main entry point in main.cpp to initialize and run the Flutter application.
- Implemented utility functions for console attachment and command line argument parsing.
- Added resource management for application icon and manifest.
- Enhanced Win32Window class for DPI awareness and theme management.
- Included necessary headers and resource files for building the Windows runner.
This commit is contained in:
Janez T
2025-11-14 09:52:00 +01:00
commit 4577dec95a
314 changed files with 103048 additions and 0 deletions

View File

@@ -0,0 +1,325 @@
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:geolocator/geolocator.dart';
import '../l10n/app_localizations.dart';
import '../providers/contacts_provider.dart';
import '../providers/app_provider.dart';
import '../providers/connection_provider.dart';
import '../widgets/contacts/contact_tile.dart';
import '../widgets/contacts/add_channel_dialog.dart';
class ContactsTab extends StatefulWidget {
final VoidCallback? onNavigateToMap;
const ContactsTab({super.key, this.onNavigateToMap});
@override
State<ContactsTab> createState() => _ContactsTabState();
}
class _ContactsTabState extends State<ContactsTab> {
Position? _currentPosition;
@override
void initState() {
super.initState();
_getCurrentLocation();
// Mark all contacts as viewed when tab is opened
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<ContactsProvider>().markAllAsViewed();
});
}
Future<void> _getCurrentLocation() async {
try {
final position = await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.best,
distanceFilter: 0,
),
);
if (mounted) {
setState(() {
_currentPosition = position;
});
}
} catch (e) {
// Silently fail if location not available
debugPrint('Failed to get location: $e');
}
}
Future<void> _handleRefresh() async {
final appProvider = context.read<AppProvider>();
await appProvider.refresh();
// Also refresh location
await _getCurrentLocation();
}
/// Calculate distance between two points in meters
double _calculateDistanceInMeters(
double lat1,
double lon1,
double lat2,
double lon2,
) {
const R = 6371000; // Earth's radius in meters
final dLat = (lat2 - lat1) * pi / 180;
final dLon = (lon2 - lon1) * pi / 180;
final a =
sin(dLat / 2) * sin(dLat / 2) +
cos(lat1 * pi / 180) *
cos(lat2 * pi / 180) *
sin(dLon / 2) *
sin(dLon / 2);
final c = 2 * atan2(sqrt(a), sqrt(1 - a));
return R * c;
}
/// Format distance for display
String _formatDistance(double meters) {
if (meters < 1000) {
return '${meters.round()}m';
} else if (meters < 10000) {
return '${(meters / 1000).toStringAsFixed(2)}km';
} else {
return '${(meters / 1000).toStringAsFixed(1)}km';
}
}
/// Show the add channel dialog
Future<void> _showAddChannelDialog(BuildContext context) async {
final l10n = AppLocalizations.of(context)!;
await showDialog(
context: context,
builder: (context) => AddChannelDialog(
onCreateChannel: (name, secret) async {
final connectionProvider = context.read<ConnectionProvider>();
try {
await connectionProvider.createChannel(
channelName: name,
channelSecret: secret,
);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.channelCreatedSuccessfully),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.channelCreationFailed(e.toString())),
backgroundColor: Colors.red,
),
);
}
rethrow; // Re-throw to let dialog handle the error state
}
},
),
);
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final appProvider = context.watch<AppProvider>();
final isSimpleMode = appProvider.isSimpleMode;
return Scaffold(
body: Consumer<ContactsProvider>(
builder: (context, contactsProvider, child) {
final chatContacts = contactsProvider.chatContacts;
final repeaters = contactsProvider.repeaters;
final rooms = contactsProvider.rooms;
final channels = contactsProvider.channels;
// Check if there are any displayable contacts (excluding channels)
final hasDisplayableContacts = chatContacts.isNotEmpty ||
repeaters.isNotEmpty ||
rooms.isNotEmpty;
if (!hasDisplayableContacts) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.contacts_outlined,
size: 64,
color: Theme.of(context).disabledColor,
),
const SizedBox(height: 16),
Text(
l10n.noContactsYet,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
l10n.connectToDeviceToLoadContacts,
style: Theme.of(context).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
],
),
);
}
return RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView(
padding: const EdgeInsets.all(8),
children: [
// Team Members (Chat contacts)
if (chatContacts.isNotEmpty) ...[
_SectionHeader(
title: l10n.teamMembers,
count: chatContacts.length,
icon: Icons.people,
),
...chatContacts.map(
(contact) => ContactTile(
contact: contact,
currentPosition: _currentPosition,
calculateDistance: _calculateDistanceInMeters,
formatDistance: _formatDistance,
onNavigateToMap: widget.onNavigateToMap,
),
),
const Divider(height: 32),
],
// Repeaters
if (repeaters.isNotEmpty) ...[
_SectionHeader(
title: l10n.repeaters,
count: repeaters.length,
icon: Icons.router,
),
...repeaters.map(
(contact) => ContactTile(
contact: contact,
currentPosition: _currentPosition,
calculateDistance: _calculateDistanceInMeters,
formatDistance: _formatDistance,
onNavigateToMap: widget.onNavigateToMap,
),
),
const Divider(height: 32),
],
// Rooms
if (rooms.isNotEmpty) ...[
_SectionHeader(
title: l10n.rooms,
count: rooms.length,
icon: Icons.tag,
),
...rooms.map(
(contact) => ContactTile(
contact: contact,
currentPosition: _currentPosition,
calculateDistance: _calculateDistanceInMeters,
formatDistance: _formatDistance,
onNavigateToMap: widget.onNavigateToMap,
),
),
const Divider(height: 32),
],
// Channels (hidden in simple mode)
if (!isSimpleMode) ...[
_SectionHeader(
title: l10n.channels,
count: channels.length,
icon: Icons.broadcast_on_personal,
),
if (channels.isNotEmpty) ...[
...channels.map(
(contact) => ContactTile(
contact: contact,
currentPosition: _currentPosition,
calculateDistance: _calculateDistanceInMeters,
formatDistance: _formatDistance,
onNavigateToMap: widget.onNavigateToMap,
),
),
],
// Add Channel Button (only show when connected)
if (context.watch<ConnectionProvider>().deviceInfo.isConnected)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: OutlinedButton.icon(
onPressed: () => _showAddChannelDialog(context),
icon: const Icon(Icons.add_circle_outline),
label: Text(l10n.addChannel),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
),
),
],
],
),
);
},
),
);
}
}
class _SectionHeader extends StatelessWidget {
final String title;
final int count;
final IconData icon;
const _SectionHeader({
required this.title,
required this.count,
required this.icon,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
Icon(icon, size: 20),
const SizedBox(width: 8),
Text(
title,
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Text(
count.toString(),
style: Theme.of(context).textTheme.labelSmall,
),
),
],
),
);
}
}

View File

@@ -0,0 +1,832 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:geolocator/geolocator.dart';
import '../providers/connection_provider.dart';
import '../services/validation_service.dart';
import '../l10n/app_localizations.dart';
class DeviceConfigScreen extends StatefulWidget {
const DeviceConfigScreen({super.key});
@override
State<DeviceConfigScreen> createState() => _DeviceConfigScreenState();
}
class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
late TextEditingController _nameController;
late TextEditingController _latController;
late TextEditingController _lonController;
late TextEditingController _freqController;
late TextEditingController _txPowerController;
bool _telemetryEnabled = false;
String _selectedBandwidth = '62.5 kHz';
int _selectedSpreadingFactor = 8;
int _selectedCodingRate = 8;
final List<String> _bandwidthOptions = [
'7.8 kHz',
'10.4 kHz',
'15.6 kHz',
'20.8 kHz',
'31.25 kHz',
'41.7 kHz',
'62.5 kHz',
'125 kHz',
'250 kHz',
'500 kHz',
];
@override
void initState() {
super.initState();
final deviceInfo = context.read<ConnectionProvider>().deviceInfo;
_nameController = TextEditingController(
text: deviceInfo.selfName ?? deviceInfo.deviceName ?? '',
);
_latController = TextEditingController(
text: deviceInfo.advLat != null
? (deviceInfo.advLat! / 1000000).toStringAsFixed(6)
: '0.0',
);
_lonController = TextEditingController(
text: deviceInfo.advLon != null
? (deviceInfo.advLon! / 1000000).toStringAsFixed(6)
: '0.0',
);
_freqController = TextEditingController(
text: deviceInfo.radioFreq != null
? (deviceInfo.radioFreq! / 1000).toStringAsFixed(3)
: '869.618',
);
_txPowerController = TextEditingController(
text: deviceInfo.txPower?.toString() ?? '20',
);
if (deviceInfo.radioBw != null &&
deviceInfo.radioBw! >= 0 &&
deviceInfo.radioBw! <= 9) {
_selectedBandwidth = _bandwidthFromValue(deviceInfo.radioBw!);
}
if (deviceInfo.radioSf != null &&
deviceInfo.radioSf! >= 7 &&
deviceInfo.radioSf! <= 12) {
_selectedSpreadingFactor = deviceInfo.radioSf!;
}
if (deviceInfo.radioCr != null &&
deviceInfo.radioCr! >= 5 &&
deviceInfo.radioCr! <= 8) {
_selectedCodingRate = deviceInfo.radioCr!;
}
// Check if telemetry is enabled (check if lat/lon are set and not zero)
_telemetryEnabled =
(deviceInfo.advLat != null && deviceInfo.advLat! != 0) ||
(deviceInfo.advLon != null && deviceInfo.advLon! != 0);
}
@override
void dispose() {
_nameController.dispose();
_latController.dispose();
_lonController.dispose();
_freqController.dispose();
_txPowerController.dispose();
super.dispose();
}
String _bandwidthFromValue(int bw) {
switch (bw) {
case 0:
return '7.8 kHz';
case 1:
return '10.4 kHz';
case 2:
return '15.6 kHz';
case 3:
return '20.8 kHz';
case 4:
return '31.25 kHz';
case 5:
return '41.7 kHz';
case 6:
return '62.5 kHz';
case 7:
return '125 kHz';
case 8:
return '250 kHz';
case 9:
return '500 kHz';
default:
return '62.5 kHz';
}
}
int _bandwidthToValue(String bw) {
return _bandwidthOptions.indexOf(bw);
}
Future<void> _savePublicInfo() async {
final connectionProvider = context.read<ConnectionProvider>();
final deviceInfo = connectionProvider.deviceInfo;
final validator = ValidationService();
try {
// Save name
if (_nameController.text.isNotEmpty) {
await connectionProvider.setAdvertName(_nameController.text);
}
// Save position and telemetry settings
if (_telemetryEnabled) {
// Parse and validate coordinates
final latResult = validator.parseLatitude(_latController.text);
if (!latResult.isSuccess) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(latResult.errorMessage!),
backgroundColor: Colors.red,
),
);
}
return;
}
final lonResult = validator.parseLongitude(_lonController.text);
if (!lonResult.isSuccess) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(lonResult.errorMessage!),
backgroundColor: Colors.red,
),
);
}
return;
}
await connectionProvider.setAdvertLatLon(
latitude: latResult.value!,
longitude: lonResult.value!,
);
// Set telemetry modes to "Allow All" (mode 2 for both base and location)
final telemetryModes = 0x0A; // binary: 00001010 (base=2, location=2)
await connectionProvider.setOtherParams(
manualAddContacts: deviceInfo.manualAddContacts == true ? 1 : 0,
telemetryModes: telemetryModes,
advertLocationPolicy: 1,
);
} else {
// Clear position
await connectionProvider.setAdvertLatLon(latitude: 0.0, longitude: 0.0);
// Set telemetry modes to "Deny" (mode 0)
final telemetryModes = 0x00;
await connectionProvider.setOtherParams(
manualAddContacts: deviceInfo.manualAddContacts == true ? 1 : 0,
telemetryModes: telemetryModes,
advertLocationPolicy: 0,
);
}
// Refetch device info to update UI with new settings
await connectionProvider.refreshDeviceInfo();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.save),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.failedToSave(e.toString()),
),
backgroundColor: Colors.red,
),
);
}
}
}
Future<void> _saveRadioSettings() async {
final connectionProvider = context.read<ConnectionProvider>();
final validator = ValidationService();
final deviceInfo = connectionProvider.deviceInfo;
try {
// Parse and validate frequency
final freqResult = validator.parseFrequency(_freqController.text);
if (!freqResult.isSuccess) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(freqResult.errorMessage!),
backgroundColor: Colors.red,
),
);
}
return;
}
// Parse and validate TX power
final txPowerResult = validator.parseTxPower(
_txPowerController.text,
maxPower: deviceInfo.maxTxPower,
);
if (!txPowerResult.isSuccess) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(txPowerResult.errorMessage!),
backgroundColor: Colors.red,
),
);
}
return;
}
// Convert from MHz to kHz for protocol
final freqKhz = (freqResult.value! * 1000).round();
await connectionProvider.setRadioParams(
frequency: freqKhz,
bandwidth: _bandwidthToValue(_selectedBandwidth),
spreadingFactor: _selectedSpreadingFactor,
codingRate: _selectedCodingRate,
);
// Save TX power
await connectionProvider.setTxPower(txPowerResult.value!);
// Refetch device info to update UI with new settings
await connectionProvider.refreshDeviceInfo();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.save),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.failedToSave(e.toString()),
),
backgroundColor: Colors.red,
),
);
}
}
}
Future<void> _useCurrentLocation() async {
try {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.locationServicesDisabled,
),
),
);
}
return;
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.locationPermissionDenied,
),
),
);
}
return;
}
}
if (permission == LocationPermission.deniedForever) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(
context,
)!.locationPermissionPermanentlyDenied,
),
),
);
}
return;
}
Position position = await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.best,
),
);
setState(() {
_latController.text = position.latitude.toStringAsFixed(6);
_lonController.text = position.longitude.toStringAsFixed(6);
_telemetryEnabled = true;
});
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.locationBroadcast(
position.latitude.toStringAsFixed(6),
position.longitude.toStringAsFixed(6),
),
),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.failedToGetLocation(e.toString()),
),
),
);
}
}
}
@override
Widget build(BuildContext context) {
final deviceInfo = context.watch<ConnectionProvider>().deviceInfo;
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: Text(AppLocalizations.of(context)!.settings)),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
// Device Info Card
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
AppLocalizations.of(context)!.deviceInformation,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
_InfoRow(
AppLocalizations.of(context)!.bleName,
deviceInfo.deviceName ??
AppLocalizations.of(context)!.unknown,
),
_InfoRow(
AppLocalizations.of(context)!.meshName,
deviceInfo.selfName ?? AppLocalizations.of(context)!.notSet,
),
_InfoRow(
AppLocalizations.of(context)!.type,
_getDeviceTypeString(context, deviceInfo.deviceType),
),
_InfoRow(
AppLocalizations.of(context)!.model,
deviceInfo.manufacturerModel ??
AppLocalizations.of(context)!.unknown,
),
_InfoRow(
AppLocalizations.of(context)!.version,
deviceInfo.semanticVersion ??
AppLocalizations.of(context)!.unknown,
),
_InfoRow(
AppLocalizations.of(context)!.buildDate,
deviceInfo.firmwareBuildDate ??
AppLocalizations.of(context)!.unknown,
),
_InfoRow(
AppLocalizations.of(context)!.firmware,
'v${deviceInfo.firmwareVersion?.toString() ?? "?"}',
),
_InfoRow(
AppLocalizations.of(context)!.maxContacts,
deviceInfo.maxContacts?.toString() ??
AppLocalizations.of(context)!.unknown,
),
_InfoRow(
AppLocalizations.of(context)!.maxChannels,
deviceInfo.maxChannels?.toString() ??
AppLocalizations.of(context)!.unknown,
),
_CopyableInfoRow(
AppLocalizations.of(context)!.publicKey,
_getPublicKeyHex(deviceInfo.publicKey),
),
],
),
),
),
const SizedBox(height: 24),
// Public Info Section
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
AppLocalizations.of(context)!.publicInfo,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: 8),
IconButton.filled(
onPressed: _savePublicInfo,
icon: const Icon(Icons.save),
tooltip: AppLocalizations.of(context)!.save,
),
],
),
],
),
const SizedBox(height: 16),
// Mesh Network Name
TextField(
controller: _nameController,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.meshNetworkName,
border: const OutlineInputBorder(),
helperText: AppLocalizations.of(
context,
)!.nameBroadcastInMesh,
),
),
const SizedBox(height: 8),
// Telemetry Toggle - Compact version
Row(
children: [
Expanded(
child: Text(
AppLocalizations.of(
context,
)!.telemetryAndLocationSharing,
style: theme.textTheme.bodyMedium,
),
),
Switch(
value: _telemetryEnabled,
onChanged: (value) {
setState(() {
_telemetryEnabled = value;
});
},
),
],
),
// GPS Coordinates (only show if telemetry enabled)
if (_telemetryEnabled) ...[
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: TextField(
controller: _latController,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.lat,
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
signed: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _lonController,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.lon,
border: const OutlineInputBorder(),
isDense: true,
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
signed: true,
),
),
),
const SizedBox(width: 8),
IconButton.filled(
onPressed: _useCurrentLocation,
icon: const Icon(Icons.my_location, size: 20),
tooltip: AppLocalizations.of(
context,
)!.useCurrentLocation,
),
],
),
],
],
),
),
),
const SizedBox(height: 24),
// Radio Settings Section
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
AppLocalizations.of(context)!.radioSettings,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
IconButton.filled(
onPressed: _saveRadioSettings,
icon: const Icon(Icons.save),
tooltip: AppLocalizations.of(context)!.save,
),
],
),
const SizedBox(height: 16),
// LoRa Frequency
TextField(
controller: _freqController,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.frequencyMHz,
border: const OutlineInputBorder(),
helperText: AppLocalizations.of(
context,
)!.frequencyExample,
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
),
const SizedBox(height: 16),
// Bandwidth
DropdownButtonFormField<String>(
initialValue: _selectedBandwidth,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.bandwidth,
border: const OutlineInputBorder(),
),
items: _bandwidthOptions.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
if (newValue != null) {
setState(() {
_selectedBandwidth = newValue;
});
}
},
),
const SizedBox(height: 16),
// Spreading Factor
DropdownButtonFormField<int>(
initialValue: _selectedSpreadingFactor,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.spreadingFactor,
border: const OutlineInputBorder(),
),
items: List.generate(6, (index) => index + 7).map((
int value,
) {
return DropdownMenuItem<int>(
value: value,
child: Text(value.toString()),
);
}).toList(),
onChanged: (int? newValue) {
if (newValue != null) {
setState(() {
_selectedSpreadingFactor = newValue;
});
}
},
),
const SizedBox(height: 16),
// Coding Rate
DropdownButtonFormField<int>(
initialValue: _selectedCodingRate,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.codingRate,
border: const OutlineInputBorder(),
),
items: List.generate(4, (index) => index + 5).map((
int value,
) {
return DropdownMenuItem<int>(
value: value,
child: Text(value.toString()),
);
}).toList(),
onChanged: (int? newValue) {
if (newValue != null) {
setState(() {
_selectedCodingRate = newValue;
});
}
},
),
const SizedBox(height: 16),
// TX Power
TextField(
controller: _txPowerController,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.txPowerDbm,
border: const OutlineInputBorder(),
helperText: AppLocalizations.of(
context,
)!.maxPowerDbm(deviceInfo.maxTxPower ?? 22),
),
keyboardType: TextInputType.number,
),
],
),
),
),
const SizedBox(height: 24),
],
),
);
}
String _getDeviceTypeString(BuildContext context, int? deviceType) {
if (deviceType == null) return AppLocalizations.of(context)!.unknown;
switch (deviceType) {
case 0:
return AppLocalizations.of(context)!.noneUnknown;
case 1:
return AppLocalizations.of(context)!.chatNode;
case 2:
return AppLocalizations.of(context)!.repeater;
case 3:
return AppLocalizations.of(context)!.roomChannel;
default:
return AppLocalizations.of(context)!.typeNumber(deviceType);
}
}
String _getPublicKeyHex(List<int>? publicKey) {
if (publicKey == null || publicKey.isEmpty) return 'N/A';
return publicKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join('');
}
}
class _InfoRow extends StatelessWidget {
final String label;
final String value;
const _InfoRow(this.label, this.value);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 120,
child: Text(
label,
style: const TextStyle(
fontWeight: FontWeight.w500,
color: Colors.grey,
),
),
),
Expanded(
child: Text(
value,
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
],
),
);
}
}
class _CopyableInfoRow extends StatelessWidget {
final String label;
final String value;
const _CopyableInfoRow(this.label, this.value);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 120,
child: Text(
label,
style: const TextStyle(
fontWeight: FontWeight.w500,
color: Colors.grey,
),
),
),
Expanded(
child: GestureDetector(
onTap: () {
Clipboard.setData(ClipboardData(text: value));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(
context,
)!.copiedToClipboardShort(label),
),
duration: const Duration(seconds: 2),
backgroundColor: Colors.green,
),
);
},
child: Row(
children: [
Expanded(
child: Text(
value,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontFamily: 'monospace',
),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
const Icon(Icons.copy, size: 16, color: Colors.grey),
],
),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,865 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:vibration/vibration.dart';
import '../providers/connection_provider.dart';
import '../providers/app_provider.dart';
import '../providers/messages_provider.dart';
import '../providers/contacts_provider.dart';
import '../theme/app_theme.dart';
import 'messages_tab.dart';
import 'contacts_tab.dart';
import 'map_tab.dart';
import 'map_management_screen.dart';
import 'settings_screen.dart';
import 'device_config_screen.dart';
import 'packet_log_screen.dart';
import '../utils/toast_logger.dart';
import '../l10n/app_localizations.dart';
import '../widgets/permission_request_dialog.dart';
import '../widgets/connection_dialog.dart';
class HomeScreen extends StatefulWidget {
final Function(AppThemeMode) onThemeChanged;
final Function(Locale?) onLocaleChanged;
final AppThemeMode currentTheme;
final Locale? currentLocale;
final bool shouldShowPermissionDialog;
const HomeScreen({
super.key,
required this.onThemeChanged,
required this.onLocaleChanged,
required this.currentTheme,
required this.currentLocale,
this.shouldShowPermissionDialog = false,
});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
int _currentIndex = 0;
bool _isMapFullscreen = false;
bool _showRxTxIndicators = true;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
_tabController.addListener(() {
setState(() {
_currentIndex = _tabController.index;
// Exit fullscreen when switching away from map tab
if (_currentIndex != 2) {
_isMapFullscreen = false;
}
});
});
_loadRxTxPreference();
// Show permission dialog after the first frame if needed
if (widget.shouldShowPermissionDialog) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_showPermissionDialog();
});
}
}
Future<void> _loadRxTxPreference() async {
final prefs = await SharedPreferences.getInstance();
if (mounted) {
setState(() {
_showRxTxIndicators = prefs.getBool('show_rx_tx_indicators') ?? true;
});
}
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
void _showPermissionDialog() {
if (!mounted) return;
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => PermissionRequestDialog(
onPermissionsGranted: () {
debugPrint('✅ Location permissions granted');
},
onPermissionsDenied: () {
debugPrint('⚠️ Location permissions denied');
// Show a snackbar to inform the user
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.locationPermissionRequired,
),
duration: const Duration(seconds: 5),
),
);
}
},
),
);
}
Future<void> _advertiseDevice(BuildContext context) async {
final connectionProvider = context.read<ConnectionProvider>();
if (!connectionProvider.deviceInfo.isConnected) {
if (context.mounted) {
ToastLogger.error(
context,
AppLocalizations.of(context)!.deviceNotConnected,
);
}
return;
}
try {
// Check if location services are enabled
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
if (context.mounted) {
ToastLogger.error(
context,
AppLocalizations.of(context)!.locationServicesDisabled,
);
}
return;
}
// Check location permissions
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
if (context.mounted) {
ToastLogger.error(
context,
AppLocalizations.of(context)!.locationPermissionDenied,
);
}
return;
}
}
if (permission == LocationPermission.deniedForever) {
if (context.mounted) {
ToastLogger.error(
context,
AppLocalizations.of(context)!.locationPermissionPermanentlyDenied,
);
}
return;
}
// Get current GPS position
Position? position;
try {
position = await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.best,
distanceFilter: 0,
),
).timeout(const Duration(seconds: 5));
} catch (e) {
debugPrint('❌ Failed to get GPS position: $e');
if (context.mounted) {
ToastLogger.error(
context,
AppLocalizations.of(context)!.failedToGetGpsLocation,
);
}
return;
}
// Update lat/lon on device
await connectionProvider.setAdvertLatLon(
latitude: position.latitude,
longitude: position.longitude,
);
// Small delay to ensure the lat/lon is set
await Future.delayed(const Duration(milliseconds: 100));
// Send flood advertisement
await connectionProvider.sendSelfAdvert(floodMode: true);
} catch (e) {
debugPrint('❌ Failed to advertise device: $e');
if (context.mounted) {
ToastLogger.error(
context,
AppLocalizations.of(context)!.failedToAdvertise(e.toString()),
);
}
}
}
void _showConnectionDialog(BuildContext context) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => const ConnectionDialog(),
);
}
@override
Widget build(BuildContext context) {
// Set localizations for notifications
final messagesProvider = context.read<MessagesProvider>();
final localizations = AppLocalizations.of(context);
if (localizations != null) {
messagesProvider.setLocalizations(localizations);
}
// Determine if we should hide the UI (only in fullscreen on map tab)
final shouldHideUI = _isMapFullscreen && _currentIndex == 2;
return Scaffold(
appBar: shouldHideUI
? null
: AppBar(
title: _buildCompactStatusBar(),
actions: [
Consumer<ConnectionProvider>(
builder: (context, provider, child) {
final isConnected = provider.deviceInfo.isConnected || provider.isSseClientConnected;
if (isConnected) {
return IconButton(
onPressed: () async {
await provider.disconnect();
},
icon: const Icon(Icons.power_settings_new),
tooltip: AppLocalizations.of(context)!.disconnect,
color: Colors.red.shade700,
);
}
return const SizedBox.shrink();
},
),
PopupMenuButton(
icon: const Icon(Icons.more_vert),
itemBuilder: (context) => [
PopupMenuItem(
child: Row(
children: [
const Icon(Icons.map),
const SizedBox(width: 8),
Text(AppLocalizations.of(context)!.mapManagement),
],
),
onTap: () {
Future.delayed(Duration.zero, () {
final appProvider = context.read<AppProvider>();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MapManagementScreen(
tileCacheService: appProvider.tileCacheService,
),
),
);
});
},
),
PopupMenuItem(
child: Row(
children: [
const Icon(Icons.settings),
const SizedBox(width: 8),
Text(AppLocalizations.of(context)!.settings),
],
),
onTap: () {
Future.delayed(Duration.zero, () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SettingsScreen(
onThemeChanged: widget.onThemeChanged,
onLocaleChanged: widget.onLocaleChanged,
currentTheme: widget.currentTheme,
currentLocale: widget.currentLocale,
),
),
);
// Reload preference when returning from settings
_loadRxTxPreference();
});
},
),
],
),
],
),
body: TabBarView(
controller: _tabController,
children: [
MessagesTab(onNavigateToMap: () => _tabController.animateTo(2)),
ContactsTab(onNavigateToMap: () => _tabController.animateTo(2)),
MapTab(
onFullscreenChanged: (isFullscreen) {
setState(() {
_isMapFullscreen = isFullscreen;
});
},
onNavigateToMessages: () => _tabController.animateTo(0),
),
],
),
bottomNavigationBar: shouldHideUI
? null
: Consumer2<MessagesProvider, ContactsProvider>(
builder: (context, messagesProvider, contactsProvider, child) {
final unreadCount = messagesProvider.unreadCount;
final newContactsCount = contactsProvider.newContactsCount;
return Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 4,
offset: const Offset(0, -2),
),
],
),
child: TabBar(
controller: _tabController,
tabs: [
Tab(
icon: _buildTabIconWithBadge(
Icons.message,
unreadCount,
),
text: AppLocalizations.of(context)!.messages,
),
Tab(
icon: _buildTabIconWithBadge(
Icons.contacts,
newContactsCount,
),
text: AppLocalizations.of(context)!.contacts,
),
Tab(
icon: const Icon(Icons.map),
text: AppLocalizations.of(context)!.map,
),
],
),
);
},
),
);
}
Widget _buildCompactStatusBar() {
return Consumer<ConnectionProvider>(
builder: (context, provider, child) {
final deviceInfo = provider.deviceInfo;
final isBleConnected = deviceInfo.isConnected;
final isSseConnected = provider.isSseClientConnected;
final isConnected = isBleConnected || isSseConnected;
if (!isConnected) {
// Disconnected state: show connect button
return Row(
children: [
Expanded(
child: Text(
AppLocalizations.of(context)!.appTitle,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
ElevatedButton.icon(
onPressed: provider.isReconnecting
? null
: () => _showConnectionDialog(context),
icon: provider.isReconnecting
? const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.black54,
),
),
)
: const Icon(Icons.bluetooth, size: 18),
label: Text(
provider.isReconnecting
? '${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts}'
: AppLocalizations.of(context)!.connect,
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.black87,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
if (provider.isReconnecting) ...[
const SizedBox(width: 8),
IconButton(
onPressed: () => provider.cancelReconnection(),
icon: const Icon(Icons.close, size: 20),
tooltip: AppLocalizations.of(context)!.cancelReconnection,
style: IconButton.styleFrom(
backgroundColor: Colors.red.shade700,
foregroundColor: Colors.white,
padding: const EdgeInsets.all(8),
),
),
],
],
);
}
// Connected state: LEFT | CENTER | RIGHT layout
return Row(
children: [
// LEFT: Name + BT/Battery + Cog
Expanded(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
deviceInfo.selfName ??
AppLocalizations.of(context)!.appTitle,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
isSseConnected
? Icons.wifi
: Icons.bluetooth_connected,
color: isSseConnected
? Colors.green
: (deviceInfo.signalRssi != null
? _getSignalColor(deviceInfo.signalRssi!)
: Colors.grey),
size: 13,
),
if (isBleConnected && deviceInfo.signalRssi != null) ...[
const SizedBox(width: 3),
Text(
'${deviceInfo.signalRssi}',
style: TextStyle(
fontSize: 11,
color: _getSignalColor(
deviceInfo.signalRssi!,
),
),
),
],
if (isSseConnected && !isBleConnected) ...[
const SizedBox(width: 3),
Text(
'SSE',
style: const TextStyle(
fontSize: 11,
color: Colors.green,
),
),
],
if (deviceInfo.batteryPercent != null) ...[
const SizedBox(width: 8),
Icon(
_getBatteryIcon(deviceInfo.batteryPercent!),
color: _getBatteryColor(
deviceInfo.batteryPercent!,
),
size: 13,
),
const SizedBox(width: 3),
Text(
'${deviceInfo.batteryPercent!.round()}%',
style: TextStyle(
fontSize: 11,
color: _getBatteryColor(
deviceInfo.batteryPercent!,
),
),
),
],
],
),
],
),
),
// Settings cog - hidden in simple mode
if (!context.watch<AppProvider>().isSimpleMode) ...[
const SizedBox(width: 8),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const DeviceConfigScreen(),
),
);
},
onLongPress: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PacketLogScreen(
bleService: provider.bleService,
),
),
);
},
child: Container(
width: 32,
height: 32,
alignment: Alignment.center,
child: const Icon(Icons.settings, size: 18),
),
),
],
],
),
),
// CENTER: Broadcast button
const SizedBox(width: 8),
FilledButton(
onPressed: () async {
// iOS: Use haptic feedback (always works)
// Android: Try vibration package for better control
try {
if (Theme.of(context).platform == TargetPlatform.iOS) {
// iOS: Try multiple haptic types for reliability
await HapticFeedback.lightImpact();
await Future.delayed(const Duration(milliseconds: 50));
await HapticFeedback.lightImpact();
} else {
// Android vibration
if (await Vibration.hasVibrator() ?? false) {
await Vibration.vibrate(duration: 50);
} else {
await HapticFeedback.mediumImpact();
}
}
} catch (e) {
// Fallback if anything fails
debugPrint('Haptic feedback error: $e');
await HapticFeedback.vibrate();
}
_advertiseDevice(context);
},
style: FilledButton.styleFrom(
backgroundColor: Colors.blue.shade700,
foregroundColor: Colors.white,
padding: const EdgeInsets.all(10),
minimumSize: const Size(40, 40),
shape: const CircleBorder(),
),
child: const Icon(Icons.campaign, size: 20),
),
const SizedBox(width: 8),
// RIGHT: RX/TX indicators
if (_showRxTxIndicators)
GestureDetector(
onLongPress: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PacketLogScreen(bleService: provider.bleService),
),
);
},
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 7,
height: 7,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: provider.rxActivity
? Colors.green
: Colors.grey.withOpacity(0.3),
),
),
const SizedBox(width: 3),
Text(
'RX:${provider.rxPacketCount}',
style: const TextStyle(
fontSize: 10,
color: Colors.grey,
),
),
],
),
const SizedBox(height: 3),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 7,
height: 7,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: provider.txActivity
? Colors.blue
: Colors.grey.withOpacity(0.3),
),
),
const SizedBox(width: 3),
Text(
'TX:${provider.txPacketCount}',
style: const TextStyle(
fontSize: 10,
color: Colors.grey,
),
),
],
),
],
),
)
else
const SizedBox(
width: 52,
), // Placeholder to maintain layout balance
],
);
},
);
}
Widget _buildStatusBar() {
return Consumer<ConnectionProvider>(
builder: (context, provider, child) {
final deviceInfo = provider.deviceInfo;
final isConnected = deviceInfo.isConnected;
return Container(
padding: const EdgeInsets.all(12),
color: Theme.of(context).colorScheme.surface,
child: Column(
children: [
Row(
children: [
// Connection status
Icon(
isConnected
? Icons.bluetooth_connected
: Icons.bluetooth_disabled,
color: isConnected ? Colors.green : Colors.grey,
),
const SizedBox(width: 8),
Expanded(
child: Text(
isConnected
? deviceInfo.displayName ??
AppLocalizations.of(context)!.connect
: AppLocalizations.of(context)!.deviceNotConnected,
style: Theme.of(context).textTheme.bodyMedium,
),
),
// Battery indicator
if (deviceInfo.batteryPercent != null) ...[
Icon(
_getBatteryIcon(deviceInfo.batteryPercent!),
color: _getBatteryColor(deviceInfo.batteryPercent!),
),
const SizedBox(width: 4),
Text(
'${deviceInfo.batteryPercent!.round()}%',
style: Theme.of(context).textTheme.bodySmall,
),
],
// Signal strength
if (deviceInfo.signalRssi != null) ...[
const SizedBox(width: 12),
Icon(
Icons.signal_cellular_alt,
color: _getSignalColor(deviceInfo.signalRssi!),
size: 20,
),
const SizedBox(width: 4),
Text(
'${deviceInfo.signalRssi} dBm',
style: Theme.of(context).textTheme.bodySmall,
),
],
],
),
const SizedBox(height: 8),
// Connection buttons
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: isConnected
? null
: () => _showConnectionDialog(context),
icon: const Icon(Icons.bluetooth_searching, size: 18),
label: Text(AppLocalizations.of(context)!.connect),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 8),
),
),
),
const SizedBox(width: 8),
Expanded(
child: OutlinedButton.icon(
onPressed: !isConnected
? null
: () async {
await provider.disconnect();
},
icon: const Icon(Icons.bluetooth_disabled, size: 18),
label: Text(AppLocalizations.of(context)!.disconnect),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 8),
),
),
),
if (isConnected) ...[
const SizedBox(width: 8),
IconButton(
onPressed: () async {
final appProvider = context.read<AppProvider>();
await appProvider.refresh();
if (context.mounted) {
ToastLogger.success(context, 'Refreshed contacts');
}
},
icon: const Icon(Icons.refresh),
tooltip: 'Refresh',
),
],
],
),
// Error message
if (provider.error != null) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.red.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
const Icon(Icons.error, color: Colors.red, size: 16),
const SizedBox(width: 8),
Expanded(
child: Text(
provider.error!,
style: const TextStyle(
color: Colors.red,
fontSize: 12,
),
),
),
IconButton(
icon: const Icon(Icons.close, size: 16),
onPressed: provider.clearError,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
],
),
),
],
],
),
);
},
);
}
IconData _getBatteryIcon(double percentage) {
if (percentage > 80) return Icons.battery_full;
if (percentage > 50) return Icons.battery_5_bar;
if (percentage > 20) return Icons.battery_3_bar;
return Icons.battery_1_bar;
}
Color _getBatteryColor(double percentage) {
if (percentage > 50) return Colors.green;
if (percentage > 20) return Colors.orange;
return Colors.red;
}
Color _getSignalColor(int rssi) {
if (rssi > -60) return Colors.green;
if (rssi > -70) return Colors.orange;
return Colors.red;
}
/// Build tab icon with badge showing count
Widget _buildTabIconWithBadge(IconData icon, int count) {
if (count == 0) {
return Icon(icon);
}
return Stack(
clipBehavior: Clip.none,
children: [
Icon(icon),
Positioned(
right: -8,
top: -4,
child: Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
constraints: const BoxConstraints(minWidth: 18, minHeight: 18),
child: Text(
count > 99 ? '99+' : count.toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 10,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
),
),
],
);
}
}

File diff suppressed because it is too large Load Diff

2640
lib/screens/map_tab.dart Normal file

File diff suppressed because it is too large Load Diff

10
lib/screens/mcp.json Normal file
View File

@@ -0,0 +1,10 @@
{
"mcpServers": {
"dart": {
"command": "dart",
"args": [
"mcp-server"
]
}
}
}

View File

@@ -0,0 +1,922 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:geolocator/geolocator.dart';
import '../providers/messages_provider.dart';
import '../providers/contacts_provider.dart';
import '../providers/map_provider.dart';
import '../providers/connection_provider.dart';
import '../providers/drawing_provider.dart';
import '../providers/app_provider.dart';
import '../models/message.dart';
import '../models/contact.dart';
import '../widgets/messages/sar_update_sheet.dart';
import '../widgets/messages/recipient_selector_sheet.dart';
import '../widgets/messages/message_bubble.dart';
import '../services/message_destination_preferences.dart';
import '../utils/toast_logger.dart';
import '../l10n/app_localizations.dart';
class MessagesTab extends StatefulWidget {
final VoidCallback onNavigateToMap;
const MessagesTab({super.key, required this.onNavigateToMap});
@override
State<MessagesTab> createState() => _MessagesTabState();
}
class _MessagesTabState extends State<MessagesTab> {
final TextEditingController _textController = TextEditingController();
final FocusNode _focusNode = FocusNode();
final ScrollController _scrollController = ScrollController();
int _characterCount = 0;
static const int _maxCharacters = 160;
String? _highlightedMessageId;
// Message destination state
String _destinationType =
MessageDestinationPreferences.destinationTypeChannel;
Contact? _selectedRecipient;
/// Helper method to compare two public keys for equality
bool _publicKeysMatch(Uint8List key1, Uint8List key2) {
if (key1.length != key2.length) return false;
for (int i = 0; i < key1.length; i++) {
if (key1[i] != key2[i]) return false;
}
return true;
}
@override
void initState() {
super.initState();
_textController.addListener(_updateCharacterCount);
// Load saved message destination
_loadSavedDestination();
// Mark all messages as read when tab is opened
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<MessagesProvider>().markAllAsRead();
_checkForNavigationRequest();
});
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Reload saved destination and check for navigation request whenever dependencies change
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadSavedDestination();
_checkForNavigationRequest();
});
}
@override
void dispose() {
_textController.dispose();
_focusNode.dispose();
_scrollController.dispose();
super.dispose();
}
void _checkForNavigationRequest() {
final messagesProvider = context.read<MessagesProvider>();
final targetMessageId = messagesProvider.targetMessageId;
if (targetMessageId != null) {
_scrollToMessage(targetMessageId);
messagesProvider.clearMessageNavigation();
}
}
void _scrollToMessage(String messageId) {
final messagesProvider = context.read<MessagesProvider>();
final messages = _getFilteredMessages(messagesProvider);
final messageIndex = messages.indexWhere((m) => m.id == messageId);
if (messageIndex != -1 && _scrollController.hasClients) {
// Calculate position - accounting for reverse list
final itemHeight = 80.0; // Approximate height of a message bubble
final targetOffset = messageIndex * itemHeight;
// Scroll to the message
_scrollController.animateTo(
targetOffset,
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut,
);
// Highlight the message briefly
setState(() {
_highlightedMessageId = messageId;
});
// Clear highlight after 2 seconds
Future.delayed(const Duration(seconds: 2), () {
if (mounted) {
setState(() {
_highlightedMessageId = null;
});
}
});
}
}
void _updateCharacterCount() {
setState(() {
_characterCount = _textController.text.length;
});
}
/// Load saved message destination from preferences
Future<void> _loadSavedDestination() async {
final savedDestination =
await MessageDestinationPreferences.getDestination();
if (savedDestination == null || !mounted) {
// Default to public channel
return;
}
final type = savedDestination['type']!;
final publicKey = savedDestination['publicKey'];
setState(() {
_destinationType = type;
});
// If it's a contact or room, try to find it in the contacts list
if (publicKey != null && mounted) {
final contactsProvider = context.read<ContactsProvider>();
final contact = contactsProvider.contacts.where((c) {
return c.publicKeyHex == publicKey;
}).firstOrNull;
if (contact != null) {
setState(() {
_selectedRecipient = contact;
});
} else {
// Contact/room not found, fallback to public channel
debugPrint(
'⚠️ [MessagesTab] Saved recipient not found, falling back to public channel',
);
setState(() {
_destinationType =
MessageDestinationPreferences.destinationTypeChannel;
_selectedRecipient = null;
});
await MessageDestinationPreferences.clearDestination();
}
}
}
/// Show recipient selector bottom sheet
void _showRecipientSelector() {
final contactsProvider = context.read<ContactsProvider>();
// Filter contacts by type
final contacts = contactsProvider.contacts
.where((c) => c.type == ContactType.chat)
.toList();
final rooms = contactsProvider.contacts
.where((c) => c.type == ContactType.room)
.toList();
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => RecipientSelectorSheet(
contacts: contacts,
rooms: rooms,
currentDestinationType: _destinationType,
currentRecipientPublicKey: _selectedRecipient?.publicKeyHex,
onSelect: _onRecipientSelected,
),
);
}
/// Handle recipient selection
Future<void> _onRecipientSelected(String type, Contact? recipient) async {
// Get display name before async gap
final recipientName =
type == MessageDestinationPreferences.destinationTypeChannel
? AppLocalizations.of(context)!.publicChannel
: (recipient?.displayName ?? recipient?.advName ?? 'Unknown');
setState(() {
_destinationType = type;
_selectedRecipient = recipient;
});
// Save to preferences
await MessageDestinationPreferences.setDestination(
type,
recipientPublicKey: recipient?.publicKeyHex,
);
// Show confirmation toast
if (!mounted) return;
}
/// Get icon for current destination type
IconData _getDestinationIcon() {
if (_destinationType ==
MessageDestinationPreferences.destinationTypeChannel) {
return Icons.public;
} else if (_destinationType ==
MessageDestinationPreferences.destinationTypeRoom) {
return Icons.meeting_room;
} else {
return Icons.person;
}
}
/// Get tooltip for destination button
String _getDestinationTooltip() {
final l10n = AppLocalizations.of(context)!;
if (_destinationType ==
MessageDestinationPreferences.destinationTypeChannel) {
return '${l10n.publicChannel} (tap to change)';
} else if (_selectedRecipient != null) {
final recipientName =
_selectedRecipient!.displayName ?? _selectedRecipient!.advName;
return '$recipientName (tap to change)';
}
return 'Select recipient';
}
Future<void> _sendMessage() async {
final text = _textController.text.trim();
if (text.isEmpty) return;
final connectionProvider = context.read<ConnectionProvider>();
final messagesProvider = context.read<MessagesProvider>();
final contactsProvider = context.read<ContactsProvider>();
if (!connectionProvider.deviceInfo.isConnected) {
if (!mounted) return;
ToastLogger.error(context, 'Not connected to device');
return;
}
try {
// Check destination type and send accordingly
if (_destinationType ==
MessageDestinationPreferences.destinationTypeChannel) {
// Send to public channel
await _sendToChannel(text, connectionProvider, messagesProvider);
} else if (_selectedRecipient != null) {
// Send to contact or room
await _sendToRecipient(
text,
connectionProvider,
messagesProvider,
contactsProvider,
);
} else {
// Fallback to public channel if no recipient selected
debugPrint(
'⚠️ [MessagesTab] No recipient selected, falling back to channel',
);
await _sendToChannel(text, connectionProvider, messagesProvider);
}
_textController.clear();
_focusNode.unfocus();
if (!mounted) return;
} catch (e) {
if (!mounted) return;
ToastLogger.error(context, 'Failed to send: $e');
}
}
/// Send message to public channel
Future<void> _sendToChannel(
String text,
ConnectionProvider connectionProvider,
MessagesProvider messagesProvider,
) async {
// Create message ID
final messageId = '${DateTime.now().millisecondsSinceEpoch}_channel_sent';
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
// Get current device's public key (first 6 bytes)
final devicePublicKey = connectionProvider.deviceInfo.publicKey;
final senderPublicKeyPrefix = devicePublicKey?.sublist(0, 6);
// Create sent message object
final sentMessage = Message(
id: messageId,
messageType: MessageType.channel,
senderPublicKeyPrefix: senderPublicKeyPrefix,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: timestamp,
text: text,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
channelIdx: 0,
);
// Add to messages list with "sending" status
messagesProvider.addSentMessage(sentMessage);
// Send to public channel (channel 0)
await connectionProvider.sendChannelMessage(
channelIdx: 0,
text: text,
messageId: messageId,
);
}
/// Send message to contact or room
Future<void> _sendToRecipient(
String text,
ConnectionProvider connectionProvider,
MessagesProvider messagesProvider,
ContactsProvider contactsProvider,
) async {
if (_selectedRecipient == null) return;
// Create message ID
final messageId = '${DateTime.now().millisecondsSinceEpoch}_sent';
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
// Get current device's public key (first 6 bytes)
final devicePublicKey = connectionProvider.deviceInfo.publicKey;
final senderPublicKeyPrefix = devicePublicKey?.sublist(0, 6);
// Create sent message object with recipient public key for retry support
final sentMessage = Message(
id: messageId,
messageType: MessageType.contact,
senderPublicKeyPrefix: senderPublicKeyPrefix,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: timestamp,
text: text,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
recipientPublicKey: _selectedRecipient!.publicKey,
);
// Add to messages list with "sending" status
messagesProvider.addSentMessage(sentMessage);
// Send message to selected recipient
final sentSuccessfully = await connectionProvider.sendTextMessage(
contactPublicKey: _selectedRecipient!.publicKey,
text: text,
messageId: messageId,
contact: _selectedRecipient,
);
if (!sentSuccessfully) {
// Mark message as failed if sending failed
messagesProvider.markMessageFailed(messageId);
}
}
void _showSarDialog() {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => SarUpdateSheet(
onSend:
(
emoji,
name,
position,
roomPublicKey,
sendToChannel,
sendToAllContacts,
colorIndex,
) async {
await _sendSarMessage(
emoji,
name,
position,
roomPublicKey,
sendToChannel,
sendToAllContacts,
colorIndex,
);
},
),
);
}
Future<void> _sendSarMessage(
String emoji,
String name,
Position position,
Uint8List? roomPublicKey,
bool sendToChannel,
bool sendToAllContacts,
int colorIndex,
) async {
final connectionProvider = context.read<ConnectionProvider>();
final messagesProvider = context.read<MessagesProvider>();
if (!connectionProvider.deviceInfo.isConnected) {
if (!mounted) return;
ToastLogger.error(context, 'Not connected to device');
return;
}
if (!sendToChannel && !sendToAllContacts && roomPublicKey == null) {
if (!mounted) return;
ToastLogger.error(context, 'Please select a destination to send SAR marker');
return;
}
try {
// New format: S:<emoji>:<colorIndex>:<latitude>,<longitude>:<name>
// Round coordinates to 5 decimal places (~1m accuracy) since most GPS is only that accurate
final sarMessage =
'S:$emoji:${colorIndex.toString()}:${position.latitude.toStringAsFixed(5)},${position.longitude.toStringAsFixed(5)}:$name';
if (sendToAllContacts) {
// Send to all chat contacts (ContactType.chat)
final contactsProvider = context.read<ContactsProvider>();
final chatContacts = contactsProvider.chatContacts;
if (chatContacts.isEmpty) {
if (!mounted) return;
ToastLogger.error(context, AppLocalizations.of(context)!.noContactsAvailable);
return;
}
// Create a single grouped message instead of multiple individual messages
final groupId = '${DateTime.now().millisecondsSinceEpoch}_group';
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final devicePublicKey = connectionProvider.deviceInfo.publicKey;
final senderPublicKeyPrefix = devicePublicKey?.sublist(0, 6);
// Create recipient list
final recipients = chatContacts.map((contact) {
return MessageRecipient(
publicKey: contact.publicKey,
displayName: contact.displayName,
deliveryStatus: MessageDeliveryStatus.sending,
sentAt: DateTime.now(),
);
}).toList();
// Create single grouped message
final groupedMessage = Message(
id: groupId,
messageType: MessageType.contact,
senderPublicKeyPrefix: senderPublicKeyPrefix,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: timestamp,
text: sarMessage,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
groupId: groupId,
recipients: recipients,
);
// Add the grouped message to the list
messagesProvider.addSentMessage(groupedMessage);
// Send to each contact and track status
int successCount = 0;
for (final contact in chatContacts) {
final individualMessageId = '${groupId}_${contact.publicKeyShort}';
// Register this individual send as part of the grouped message
messagesProvider.registerGroupedMessageSend(
individualMessageId,
groupId,
contact.publicKey,
);
// Send SAR message to contact (with ACK tracking)
final sentSuccessfully = await connectionProvider.sendTextMessage(
contactPublicKey: contact.publicKey,
text: sarMessage,
messageId: individualMessageId,
contact: contact,
);
if (sentSuccessfully) {
successCount++;
} else {
// Update recipient status in grouped message
messagesProvider.updateGroupedMessageRecipientStatus(
groupId,
contact.publicKey,
MessageDeliveryStatus.failed,
);
}
// Add 1 second delay between sends to ensure:
// 1. Different timestamps (messages sent in different seconds)
// 2. Radio has time to fully process previous message and assign ACK tag
// This ensures each message gets a unique ACK tag from the radio
if (contact != chatContacts.last) {
await Future.delayed(const Duration(seconds: 1));
}
}
if (!mounted) return;
ToastLogger.success(
context,
AppLocalizations.of(context)!.sarMarkerSentToContacts(successCount),
);
} else if (sendToChannel) {
// Create message ID
final messageId =
'${DateTime.now().millisecondsSinceEpoch}_channel_sent';
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
// Get current device's public key (first 6 bytes)
final devicePublicKey = connectionProvider.deviceInfo.publicKey;
final senderPublicKeyPrefix = devicePublicKey?.sublist(0, 6);
// Create sent message object
final sentMessage = Message(
id: messageId,
messageType: MessageType.channel,
senderPublicKeyPrefix: senderPublicKeyPrefix,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: timestamp,
text: sarMessage,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
channelIdx: 0,
// SAR marker data is automatically added by SarMessageParser.enhanceMessage in MessagesProvider
);
// Add to messages list with "sending" status
messagesProvider.addSentMessage(sentMessage);
// Send to public channel (ephemeral, over-the-air only)
await connectionProvider.sendChannelMessage(
channelIdx: 0,
text: sarMessage,
messageId: messageId,
);
if (!mounted) return;
} else {
// Create message ID
final messageId = '${DateTime.now().millisecondsSinceEpoch}_sent';
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
// Get current device's public key (first 6 bytes)
final devicePublicKey = connectionProvider.deviceInfo.publicKey;
final senderPublicKeyPrefix = devicePublicKey?.sublist(0, 6);
// Create sent message object with recipient public key for retry support
final sentMessage = Message(
id: messageId,
messageType: MessageType.contact,
senderPublicKeyPrefix: senderPublicKeyPrefix,
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: timestamp,
text: sarMessage,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
recipientPublicKey: roomPublicKey, // Store recipient for retry
// SAR marker data is automatically added by SarMessageParser.enhanceMessage in MessagesProvider
);
// Add to messages list with "sending" status
messagesProvider.addSentMessage(sentMessage);
// Look up the room contact for path logging
final contactsProvider = context.read<ContactsProvider>();
final roomContact = contactsProvider.contacts.where((c) {
return c.publicKey.length >= roomPublicKey!.length &&
_publicKeysMatch(c.publicKey, roomPublicKey);
}).firstOrNull;
// Send SAR message to selected room (persisted and immutable)
final sentSuccessfully = await connectionProvider.sendTextMessage(
contactPublicKey: roomPublicKey!,
text: sarMessage,
messageId: messageId, // Pass message ID so it can be tracked
contact: roomContact, // Include contact for path status logging
);
if (!sentSuccessfully) {
// Mark message as failed if sending failed
messagesProvider.markMessageFailed(messageId);
}
if (!mounted) return;
ToastLogger.success(context, 'SAR marker sent to room');
}
} catch (e) {
if (!mounted) return;
ToastLogger.error(context, 'Failed to send SAR marker: $e');
}
}
/// Handle pull-to-refresh for manual message sync
/// This is a FALLBACK mechanism - messages are normally synced automatically via PUSH_CODE_MSG_WAITING
Future<void> _handleRefresh() async {
final connectionProvider = context.read<ConnectionProvider>();
if (!connectionProvider.deviceInfo.isConnected) {
if (!mounted) return;
ToastLogger.warning(context, 'Not connected - cannot sync messages');
return;
}
try {
debugPrint(
'🔄 [MessagesTab] Manual refresh triggered - syncing messages',
);
if (!mounted) return;
} catch (e) {
debugPrint('❌ [MessagesTab] Sync error: $e');
if (!mounted) return;
ToastLogger.error(context, 'Sync failed: $e');
}
}
List<Message> _getFilteredMessages(MessagesProvider messagesProvider) {
// Get all recent messages
final allMessages = messagesProvider.getRecentMessages(count: 100);
// Get simple mode setting from AppProvider
final appProvider = context.read<AppProvider>();
final isSimpleMode = appProvider.isSimpleMode;
List<Message> filteredMessages;
// If public channel is selected, show ALL messages
if (_destinationType ==
MessageDestinationPreferences.destinationTypeChannel &&
_selectedRecipient == null) {
filteredMessages = allMessages;
}
// If a contact or room is selected, filter by recipient
else if ((_destinationType ==
MessageDestinationPreferences.destinationTypeContact ||
_destinationType ==
MessageDestinationPreferences.destinationTypeRoom) &&
_selectedRecipient != null) {
filteredMessages = allMessages.where((message) {
// Include messages sent TO this recipient
if (message.recipientPublicKey != null &&
message.recipientPublicKey!.length >= 6 &&
_selectedRecipient!.publicKey.length >= 6) {
// Compare first 6 bytes (public key prefix)
final recipientPrefix = message.recipientPublicKey!.sublist(0, 6);
final selectedPrefix = _selectedRecipient!.publicKey.sublist(0, 6);
if (_publicKeysMatch(recipientPrefix, selectedPrefix)) {
return true;
}
}
// Include messages received FROM this recipient
if (message.senderPublicKeyPrefix != null &&
message.senderPublicKeyPrefix!.length >= 6 &&
_selectedRecipient!.publicKey.length >= 6) {
final senderPrefix = message.senderPublicKeyPrefix!.sublist(0, 6);
final selectedPrefix = _selectedRecipient!.publicKey.sublist(0, 6);
if (_publicKeysMatch(senderPrefix, selectedPrefix)) {
return true;
}
}
return false;
}).toList();
} else {
// Default: show all messages (fallback case)
filteredMessages = allMessages;
}
// In simple mode, filter out system messages (toast logs)
if (isSimpleMode) {
filteredMessages = filteredMessages
.where((message) => !message.isSystemMessage)
.toList();
}
return filteredMessages;
}
@override
Widget build(BuildContext context) {
return Consumer<MessagesProvider>(
builder: (context, messagesProvider, child) {
final messages = _getFilteredMessages(messagesProvider);
return Column(
children: [
// Messages list with pull-to-refresh
Expanded(
child: RefreshIndicator(
onRefresh: _handleRefresh,
child: messages.isEmpty
? LayoutBuilder(
builder: (context, constraints) =>
SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: constraints.maxHeight,
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.message_outlined,
size: 64,
color: Theme.of(context).disabledColor,
),
const SizedBox(height: 16),
Text(
AppLocalizations.of(
context,
)!.noMessagesYet,
style: Theme.of(
context,
).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
AppLocalizations.of(
context,
)!.pullDownToSync,
style: Theme.of(
context,
).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
],
),
),
),
),
)
: ListView.builder(
controller: _scrollController,
reverse: true,
padding: const EdgeInsets.all(8),
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
final isHighlighted =
message.id == _highlightedMessageId;
return MessageBubble(
message: message,
isHighlighted: isHighlighted,
onNavigateToMap: widget.onNavigateToMap,
onTap:
message.isSarMarker &&
message.sarGpsCoordinates != null
? () {
final mapProvider = context
.read<MapProvider>();
mapProvider.navigateToLocation(
location: message.sarGpsCoordinates!,
zoom: 15.0,
);
widget.onNavigateToMap();
}
: message.isDrawing && message.drawingId != null
? () {
debugPrint('🗺️ [MessagesTab] Drawing tapped! ID: ${message.drawingId}');
final mapProvider = context
.read<MapProvider>();
final drawingProvider = context
.read<DrawingProvider>();
mapProvider.navigateToDrawing(
message.drawingId!,
drawingProvider,
);
widget.onNavigateToMap();
}
: null,
);
},
),
),
),
// Message input area
Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
border: Border(
top: BorderSide(
color: Theme.of(context).dividerColor,
width: 1,
),
),
),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// SAR quick action button
IconButton(
icon: const Icon(Icons.add_location_alt),
tooltip: AppLocalizations.of(context)!.sendSarMarker,
onPressed: _showSarDialog,
style: IconButton.styleFrom(
backgroundColor: Theme.of(
context,
).colorScheme.primaryContainer,
foregroundColor: Theme.of(
context,
).colorScheme.onPrimaryContainer,
),
),
const SizedBox(width: 4),
// Destination switcher button
IconButton(
icon: Icon(_getDestinationIcon()),
tooltip: _getDestinationTooltip(),
onPressed: _showRecipientSelector,
style: IconButton.styleFrom(
backgroundColor:
_destinationType ==
MessageDestinationPreferences
.destinationTypeChannel
? Theme.of(
context,
).colorScheme.surfaceContainerHighest
: Theme.of(context).colorScheme.secondaryContainer,
foregroundColor:
_destinationType ==
MessageDestinationPreferences
.destinationTypeChannel
? Theme.of(context).colorScheme.onSurface
: Theme.of(context).colorScheme.onSecondaryContainer,
),
),
const SizedBox(width: 4),
// Text field with embedded send button
Expanded(
child: TextField(
controller: _textController,
focusNode: _focusNode,
maxLength: _maxCharacters,
maxLines: null,
maxLengthEnforcement: MaxLengthEnforcement.enforced,
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
hintText: AppLocalizations.of(context)!.typeYourMessage,
hintStyle: const TextStyle(fontSize: 14),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 10,
),
isDense: true,
counterText: _characterCount >= 150
? '$_characterCount/$_maxCharacters'
: '',
counterStyle: TextStyle(
fontSize: 10,
color: _characterCount > _maxCharacters * 0.9
? Colors.orange
: Theme.of(context).textTheme.bodySmall?.color,
),
suffixIcon: IconButton(
icon: Icon(
Icons.send_rounded,
size: 22,
color: _textController.text.trim().isEmpty
? Theme.of(context).disabledColor
: Theme.of(context).colorScheme.primary,
),
onPressed: _textController.text.trim().isEmpty
? null
: _sendMessage,
tooltip: 'Send',
),
),
textInputAction: TextInputAction.send,
onSubmitted: (_) => _sendMessage(),
),
),
],
),
),
],
);
},
);
}
}

View File

@@ -0,0 +1,577 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:share_plus/share_plus.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import '../models/ble_packet_log.dart';
import '../services/meshcore_ble_service.dart';
import '../l10n/app_localizations.dart';
class PacketLogScreen extends StatefulWidget {
final MeshCoreBleService bleService;
const PacketLogScreen({
super.key,
required this.bleService,
});
@override
State<PacketLogScreen> createState() => _PacketLogScreenState();
}
class _PacketLogScreenState extends State<PacketLogScreen> {
bool _autoScroll = true;
final ScrollController _scrollController = ScrollController();
String _searchQuery = '';
PacketDirection? _filterDirection;
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
List<BlePacketLog> get _filteredLogs {
var logs = widget.bleService.packetLogs;
// Filter by direction
if (_filterDirection != null) {
logs = logs.where((log) => log.direction == _filterDirection).toList();
}
// Filter by search query
if (_searchQuery.isNotEmpty) {
final query = _searchQuery.toLowerCase();
logs = logs.where((log) {
return log.hexData.toLowerCase().contains(query) ||
(log.description?.toLowerCase().contains(query) ?? false) ||
log.summary.toLowerCase().contains(query);
}).toList();
}
return logs;
}
Future<void> _exportLogs(BuildContext context) async {
try {
final logs = _filteredLogs;
if (logs.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No logs to export')),
);
}
return;
}
// Create CSV content
final buffer = StringBuffer();
buffer.writeln('Timestamp,Direction,Size (bytes),Opcode Name,Code,Hex Data,Description');
for (final log in logs) {
buffer.writeln(log.toCsvRow());
}
// Save to temporary file
final tempDir = await getTemporaryDirectory();
final file = File('${tempDir.path}/ble_packets_${DateTime.now().millisecondsSinceEpoch}.csv');
await file.writeAsString(buffer.toString());
// Share the file
await Share.shareXFiles(
[XFile(file.path)],
subject: 'MeshCore BLE Packet Logs',
text: 'Exported ${logs.length} BLE packets from MeshCore SAR app',
);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Export failed: $e')),
);
}
}
}
Future<void> _exportAsText(BuildContext context) async {
try {
final logs = _filteredLogs;
if (logs.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No logs to export')),
);
}
return;
}
// Create text content
final buffer = StringBuffer();
buffer.writeln('MeshCore BLE Packet Logs');
buffer.writeln('=' * 80);
buffer.writeln('Exported: ${DateTime.now().toIso8601String()}');
buffer.writeln('Total packets: ${logs.length}');
buffer.writeln('=' * 80);
buffer.writeln();
for (final log in logs) {
buffer.writeln(log.toLogString());
}
// Save to temporary file
final tempDir = await getTemporaryDirectory();
final file = File('${tempDir.path}/ble_packets_${DateTime.now().millisecondsSinceEpoch}.txt');
await file.writeAsString(buffer.toString());
// Share the file
await Share.shareXFiles(
[XFile(file.path)],
subject: 'MeshCore BLE Packet Logs',
text: 'Exported ${logs.length} BLE packets from MeshCore SAR app',
);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Export failed: $e')),
);
}
}
}
void _copyToClipboard(BuildContext context, BlePacketLog log) {
Clipboard.setData(ClipboardData(text: log.hexData));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Hex data copied to clipboard'),
duration: Duration(seconds: 1),
),
);
}
void _clearLogs(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(AppLocalizations.of(context)!.clearAllData),
content: const Text('Are you sure you want to clear all packet logs? This cannot be undone.'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(AppLocalizations.of(context)!.cancel),
),
TextButton(
onPressed: () {
widget.bleService.clearPacketLogs();
Navigator.pop(context);
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Packet logs cleared')),
);
},
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: Text(AppLocalizations.of(context)!.clear),
),
],
),
);
}
@override
Widget build(BuildContext context) {
final logs = _filteredLogs;
return Scaffold(
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('BLE Packet Logs'),
Text(
'${logs.length} packets',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
actions: [
// Direction filter
PopupMenuButton<PacketDirection?>(
icon: Icon(_filterDirection == null
? Icons.filter_list
: _filterDirection == PacketDirection.rx
? Icons.arrow_downward
: Icons.arrow_upward),
tooltip: 'Filter by direction',
onSelected: (direction) {
setState(() {
_filterDirection = direction;
});
},
itemBuilder: (context) => [
PopupMenuItem(
value: null,
child: Row(
children: [
Icon(Icons.filter_list,
color: _filterDirection == null ? Theme.of(context).colorScheme.primary : null),
const SizedBox(width: 8),
Text('All',
style: TextStyle(
fontWeight: _filterDirection == null ? FontWeight.bold : FontWeight.normal)),
],
),
),
PopupMenuItem(
value: PacketDirection.rx,
child: Row(
children: [
Icon(Icons.arrow_downward,
color: _filterDirection == PacketDirection.rx
? Theme.of(context).colorScheme.primary
: null),
const SizedBox(width: 8),
Text('RX (Received)',
style: TextStyle(
fontWeight:
_filterDirection == PacketDirection.rx ? FontWeight.bold : FontWeight.normal)),
],
),
),
PopupMenuItem(
value: PacketDirection.tx,
child: Row(
children: [
Icon(Icons.arrow_upward,
color: _filterDirection == PacketDirection.tx
? Theme.of(context).colorScheme.primary
: null),
const SizedBox(width: 8),
Text('TX (Sent)',
style: TextStyle(
fontWeight:
_filterDirection == PacketDirection.tx ? FontWeight.bold : FontWeight.normal)),
],
),
),
],
),
// Auto-scroll toggle
IconButton(
icon: Icon(_autoScroll ? Icons.vertical_align_bottom : Icons.vertical_align_center),
tooltip: _autoScroll ? 'Disable auto-scroll' : 'Enable auto-scroll',
onPressed: () {
setState(() {
_autoScroll = !_autoScroll;
});
},
),
// Export menu
PopupMenuButton(
icon: const Icon(Icons.share),
tooltip: 'Export logs',
itemBuilder: (context) => [
const PopupMenuItem(
value: 'csv',
child: Row(
children: [
Icon(Icons.table_chart),
SizedBox(width: 8),
Text('Export as CSV'),
],
),
),
const PopupMenuItem(
value: 'txt',
child: Row(
children: [
Icon(Icons.text_snippet),
SizedBox(width: 8),
Text('Export as Text'),
],
),
),
],
onSelected: (value) {
if (value == 'csv') {
_exportLogs(context);
} else if (value == 'txt') {
_exportAsText(context);
}
},
),
// Clear logs
IconButton(
icon: const Icon(Icons.delete_outline),
tooltip: 'Clear logs',
onPressed: () => _clearLogs(context),
),
],
),
body: Column(
children: [
// Search bar
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
decoration: InputDecoration(
hintText: 'Search logs...',
prefixIcon: const Icon(Icons.search),
suffixIcon: _searchQuery.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() {
_searchQuery = '';
});
},
)
: null,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
),
onChanged: (value) {
setState(() {
_searchQuery = value;
});
},
),
),
// Logs list
Expanded(
child: logs.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.list_alt,
size: 64,
color: Colors.grey[400],
),
const SizedBox(height: 16),
Text(
_searchQuery.isNotEmpty || _filterDirection != null
? 'No matching packets found'
: 'No packets logged yet',
style: TextStyle(
fontSize: 16,
color: Colors.grey[600],
),
),
if (_searchQuery.isNotEmpty || _filterDirection != null) ...[
const SizedBox(height: 8),
TextButton.icon(
onPressed: () {
setState(() {
_searchQuery = '';
_filterDirection = null;
});
},
icon: const Icon(Icons.clear_all),
label: const Text('Clear filters'),
),
],
],
),
)
: ListView.builder(
controller: _scrollController,
itemCount: logs.length,
itemBuilder: (context, index) {
final log = logs[index];
// Auto-scroll to bottom
if (_autoScroll && index == logs.length - 1) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
});
}
return _PacketLogCard(
log: log,
onCopy: () => _copyToClipboard(context, log),
);
},
),
),
],
),
);
}
}
class _PacketLogCard extends StatelessWidget {
final BlePacketLog log;
final VoidCallback onCopy;
const _PacketLogCard({
required this.log,
required this.onCopy,
});
@override
Widget build(BuildContext context) {
final isRx = log.direction == PacketDirection.rx;
final directionColor = isRx ? Colors.green : Colors.blue;
return Card(
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: ExpansionTile(
leading: CircleAvatar(
backgroundColor: directionColor.withOpacity(0.2),
child: Icon(
isRx ? Icons.arrow_downward : Icons.arrow_upward,
color: directionColor,
size: 20,
),
),
title: Row(
children: [
Text(
isRx ? 'RX' : 'TX',
style: TextStyle(
fontWeight: FontWeight.bold,
color: directionColor,
fontSize: 12,
),
),
const SizedBox(width: 8),
Flexible(
child: Text(
log.responseCode != null ? log.opcodeName : 'N/A',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
),
overflow: TextOverflow.ellipsis,
),
),
],
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
Text(
'${log.rawData.length} bytes • ${_formatTimestamp(log.timestamp)}',
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
],
),
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Hex data
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Hex: ',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.grey[700],
),
),
Expanded(
child: SelectableText(
log.hexData,
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 12,
),
),
),
IconButton(
icon: const Icon(Icons.copy, size: 18),
tooltip: 'Copy hex data',
onPressed: onCopy,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
],
),
const SizedBox(height: 8),
// Metadata
Wrap(
spacing: 16,
runSpacing: 8,
children: [
_InfoChip(
icon: Icons.schedule,
label: log.timestamp.toIso8601String(),
),
_InfoChip(
icon: Icons.data_usage,
label: '${log.rawData.length} bytes',
),
if (log.responseCode != null)
_InfoChip(
icon: Icons.tag,
label: log.opcodeDescription,
),
// Show RSSI and SNR for LOG_RX_DATA packets
if (log.logRxDataInfo?.rssiDbm != null)
_InfoChip(
icon: Icons.signal_cellular_alt,
label: 'RSSI: ${log.logRxDataInfo!.rssiDbm} dBm',
),
if (log.logRxDataInfo?.snrDb != null)
_InfoChip(
icon: Icons.waves,
label: 'SNR: ${log.logRxDataInfo!.snrDb!.toStringAsFixed(1)} dB',
),
],
),
],
),
),
],
),
);
}
String _formatTimestamp(DateTime timestamp) {
final now = DateTime.now();
final diff = now.difference(timestamp);
if (diff.inSeconds < 60) {
return '${diff.inSeconds}s ago';
} else if (diff.inMinutes < 60) {
return '${diff.inMinutes}m ago';
} else if (diff.inHours < 24) {
return '${diff.inHours}h ago';
} else {
return '${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}:${timestamp.second.toString().padLeft(2, '0')}';
}
}
}
class _InfoChip extends StatelessWidget {
final IconData icon;
final String label;
const _InfoChip({
required this.icon,
required this.label,
});
@override
Widget build(BuildContext context) {
return Chip(
avatar: Icon(icon, size: 16),
label: Text(
label,
style: const TextStyle(fontSize: 11),
),
padding: const EdgeInsets.all(4),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
}
}

View File

@@ -0,0 +1,450 @@
import 'package:flutter/material.dart';
import '../models/sar_template.dart';
import '../services/sar_template_service.dart';
import '../widgets/sar/sar_template_edit_dialog.dart';
import '../l10n/app_localizations.dart';
/// Screen for managing SAR templates
class SarTemplateManagementScreen extends StatefulWidget {
const SarTemplateManagementScreen({super.key});
@override
State<SarTemplateManagementScreen> createState() => _SarTemplateManagementScreenState();
}
class _SarTemplateManagementScreenState extends State<SarTemplateManagementScreen> {
final SarTemplateService _templateService = SarTemplateService();
bool _isLoading = false;
@override
void initState() {
super.initState();
_initializeService();
}
Future<void> _initializeService() async {
if (!_templateService.isInitialized) {
setState(() => _isLoading = true);
await _templateService.initialize();
if (mounted) {
setState(() => _isLoading = false);
}
}
}
Future<void> _addTemplate() async {
await showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => SarTemplateEditDialog(
onSave: (template) async {
await _templateService.addTemplate(template);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.templateAdded),
backgroundColor: Colors.green,
),
);
}
},
),
);
}
Future<void> _editTemplate(SarTemplate template) async {
await showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => SarTemplateEditDialog(
template: template,
onSave: (updatedTemplate) async {
await _templateService.updateTemplate(template.id, updatedTemplate);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.templateUpdated),
backgroundColor: Colors.green,
),
);
}
},
),
);
}
Future<void> _deleteTemplate(SarTemplate template) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(AppLocalizations.of(context)!.deleteTemplate),
content: Text(
AppLocalizations.of(context)!.deleteTemplateConfirmation(template.getLocalizedName(context)),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text(AppLocalizations.of(context)!.cancel),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: Text(AppLocalizations.of(context)!.delete),
),
],
),
);
if (confirmed == true) {
await _templateService.deleteTemplate(template.id);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.templateDeleted),
backgroundColor: Colors.orange,
),
);
}
}
}
Future<void> _importFromClipboard() async {
setState(() => _isLoading = true);
try {
final importedCount = await _templateService.importFromClipboard();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.templatesImported(importedCount)),
backgroundColor: importedCount > 0 ? Colors.green : Colors.orange,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.importFailed(e.toString())),
backgroundColor: Colors.red,
),
);
}
} finally {
if (mounted) {
setState(() => _isLoading = false);
}
}
}
Future<void> _exportToClipboard() async {
try {
await _templateService.exportToClipboard();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.templatesExported(_templateService.templateCount),
),
backgroundColor: Colors.green,
action: SnackBarAction(
label: AppLocalizations.of(context)!.ok,
textColor: Colors.white,
onPressed: () {},
),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.exportFailed(e.toString())),
backgroundColor: Colors.red,
),
);
}
}
}
Future<void> _resetToDefaults() async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(AppLocalizations.of(context)!.resetToDefaults),
content: Text(AppLocalizations.of(context)!.resetToDefaultsConfirmation),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text(AppLocalizations.of(context)!.cancel),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: Text(AppLocalizations.of(context)!.reset),
),
],
),
);
if (confirmed == true) {
await _templateService.resetToDefaults();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.resetComplete),
backgroundColor: Colors.green,
),
);
}
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final l10n = AppLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(
title: Text(l10n.sarTemplates),
actions: [
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
tooltip: 'More options',
onSelected: (value) {
switch (value) {
case 'import':
_importFromClipboard();
break;
case 'export':
_exportToClipboard();
break;
case 'reset':
_resetToDefaults();
break;
}
},
itemBuilder: (context) => [
PopupMenuItem(
value: 'import',
child: ListTile(
leading: const Icon(Icons.download),
title: Text(l10n.importFromClipboard),
contentPadding: EdgeInsets.zero,
),
),
PopupMenuItem(
value: 'export',
child: ListTile(
leading: const Icon(Icons.upload),
title: Text(l10n.exportToClipboard),
contentPadding: EdgeInsets.zero,
),
),
const PopupMenuDivider(),
PopupMenuItem(
value: 'reset',
child: ListTile(
leading: const Icon(Icons.restart_alt),
title: Text(l10n.resetToDefaults),
contentPadding: EdgeInsets.zero,
),
),
],
),
],
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: ListenableBuilder(
listenable: _templateService,
builder: (context, child) {
final templates = _templateService.templates;
if (templates.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.location_searching,
size: 64,
color: colorScheme.onSurface.withValues(alpha: 0.3),
),
const SizedBox(height: 16),
Text(
l10n.noTemplates,
style: theme.textTheme.titleMedium?.copyWith(
color: colorScheme.onSurface.withValues(alpha: 0.6),
),
),
const SizedBox(height: 8),
Text(
l10n.tapAddToCreate,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurface.withValues(alpha: 0.5),
),
),
],
),
);
}
return ListView.builder(
itemCount: templates.length,
itemBuilder: (context, index) {
final template = templates[index];
return _TemplateListItem(
template: template,
onTap: () => _editTemplate(template),
onDelete: () => _deleteTemplate(template),
);
},
);
},
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _addTemplate,
icon: const Icon(Icons.add),
label: Text(l10n.addTemplate),
),
);
}
}
/// Template list item widget
class _TemplateListItem extends StatelessWidget {
final SarTemplate template;
final VoidCallback onTap;
final VoidCallback onDelete;
const _TemplateListItem({
required this.template,
required this.onTap,
required this.onDelete,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return Dismissible(
key: Key(template.id),
direction: DismissDirection.endToStart,
background: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 20),
child: const Icon(Icons.delete, color: Colors.white),
),
confirmDismiss: (direction) async {
// Show confirmation dialog
return await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(AppLocalizations.of(context)!.deleteTemplate),
content: Text(
AppLocalizations.of(context)!.deleteTemplateConfirmation(template.getLocalizedName(context)),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text(AppLocalizations.of(context)!.cancel),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: Text(AppLocalizations.of(context)!.delete),
),
],
),
);
},
onDismissed: (direction) => onDelete(),
child: ListTile(
onTap: onTap,
leading: Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: template.color,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: template.color.withValues(alpha: 0.3),
blurRadius: 4,
spreadRadius: 1,
),
],
),
child: Center(
child: Text(
template.emoji,
style: const TextStyle(fontSize: 24),
),
),
),
title: Row(
children: [
Text(
template.getLocalizedName(context),
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
if (template.isDefault) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.blue.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: Colors.blue.withValues(alpha: 0.5),
),
),
child: Text(
'DEFAULT',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.blue.shade700,
),
),
),
],
],
),
subtitle: template.description.isNotEmpty
? Text(
template.description,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurface.withValues(alpha: 0.6),
),
)
: Text(
template.toSarMessage(),
style: TextStyle(
fontFamily: 'monospace',
fontSize: 12,
color: colorScheme.onSurface.withValues(alpha: 0.5),
),
),
trailing: IconButton(
icon: const Icon(Icons.delete_outline),
color: Colors.red,
onPressed: onDelete,
),
),
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,399 @@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../services/wizard_preferences.dart';
/// Welcome wizard screen to introduce new users to the app
class WelcomeWizardScreen extends StatefulWidget {
final VoidCallback? onCompleted;
const WelcomeWizardScreen({super.key, this.onCompleted});
@override
State<WelcomeWizardScreen> createState() => _WelcomeWizardScreenState();
}
class _WelcomeWizardScreenState extends State<WelcomeWizardScreen> {
final PageController _pageController = PageController();
int _currentPage = 0;
static const int _totalPages = 6;
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
void _onPageChanged(int page) {
setState(() {
_currentPage = page;
});
}
void _nextPage() {
if (_currentPage < _totalPages - 1) {
_pageController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
} else {
_completeWizard();
}
}
void _previousPage() {
if (_currentPage > 0) {
_pageController.previousPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
}
Future<void> _completeWizard() async {
await WizardPreferences.setWizardCompleted(true);
if (mounted) {
widget.onCompleted?.call();
}
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return Scaffold(
body: SafeArea(
child: Column(
children: [
// Top bar with skip button
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
if (_currentPage > 0)
TextButton.icon(
onPressed: _previousPage,
icon: const Icon(Icons.arrow_back),
label: Text(l10n.wizardBack),
)
else
const SizedBox(width: 80),
if (_currentPage < _totalPages - 1)
TextButton(
onPressed: _completeWizard,
child: Text(l10n.wizardSkip),
)
else
const SizedBox(width: 80),
],
),
),
// Page view with wizard content
Expanded(
child: PageView(
controller: _pageController,
onPageChanged: _onPageChanged,
children: [
_buildWelcomePage(context, l10n, colorScheme),
_buildConnectingPage(context, l10n, colorScheme),
_buildSimpleModePage(context, l10n, colorScheme),
_buildChannelPage(context, l10n, colorScheme),
_buildContactsPage(context, l10n, colorScheme),
_buildMapPage(context, l10n, colorScheme),
],
),
),
// Page indicators
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(
_totalPages,
(index) => Container(
margin: const EdgeInsets.symmetric(horizontal: 4.0),
width: _currentPage == index ? 12.0 : 8.0,
height: _currentPage == index ? 12.0 : 8.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _currentPage == index
? colorScheme.primary
: colorScheme.outline.withValues(alpha: 0.3),
),
),
),
),
),
// Next/Get Started button
Padding(
padding: const EdgeInsets.all(16.0),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _nextPage,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: Text(
_currentPage < _totalPages - 1
? l10n.wizardNext
: l10n.wizardGetStarted,
style: const TextStyle(fontSize: 16),
),
),
),
),
],
),
),
);
}
Widget _buildWelcomePage(
BuildContext context,
AppLocalizations l10n,
ColorScheme colorScheme,
) {
return _buildPage(
icon: Icons.waving_hand,
iconColor: Colors.orange,
title: l10n.wizardWelcomeTitle,
description: l10n.wizardWelcomeDescription,
colorScheme: colorScheme,
);
}
Widget _buildConnectingPage(
BuildContext context,
AppLocalizations l10n,
ColorScheme colorScheme,
) {
return _buildPage(
icon: Icons.bluetooth_searching,
iconColor: Colors.blue,
title: l10n.wizardConnectingTitle,
description: l10n.wizardConnectingDescription,
features: [
_FeatureItem(
icon: Icons.radio,
text: l10n.wizardConnectingFeature1,
),
_FeatureItem(
icon: Icons.link,
text: l10n.wizardConnectingFeature2,
),
_FeatureItem(
icon: Icons.wifi_off,
text: l10n.wizardConnectingFeature3,
),
],
colorScheme: colorScheme,
);
}
Widget _buildSimpleModePage(
BuildContext context,
AppLocalizations l10n,
ColorScheme colorScheme,
) {
return _buildPage(
icon: Icons.toggle_on,
iconColor: Colors.green,
title: l10n.wizardSimpleModeTitle,
description: l10n.wizardSimpleModeDescription,
features: [
_FeatureItem(
icon: Icons.check_circle_outline,
text: l10n.wizardSimpleModeFeature1,
),
_FeatureItem(
icon: Icons.settings,
text: l10n.wizardSimpleModeFeature2,
),
],
colorScheme: colorScheme,
);
}
Widget _buildChannelPage(
BuildContext context,
AppLocalizations l10n,
ColorScheme colorScheme,
) {
return _buildPage(
icon: Icons.campaign,
iconColor: Colors.purple,
title: l10n.wizardChannelTitle,
description: l10n.wizardChannelDescription,
features: [
_FeatureItem(
icon: Icons.public,
text: l10n.wizardChannelFeature1,
),
_FeatureItem(
icon: Icons.groups,
text: l10n.wizardChannelFeature2,
),
_FeatureItem(
icon: Icons.send,
text: l10n.wizardChannelFeature3,
),
],
colorScheme: colorScheme,
);
}
Widget _buildContactsPage(
BuildContext context,
AppLocalizations l10n,
ColorScheme colorScheme,
) {
return _buildPage(
icon: Icons.people,
iconColor: Colors.teal,
title: l10n.wizardContactsTitle,
description: l10n.wizardContactsDescription,
features: [
_FeatureItem(
icon: Icons.person_add,
text: l10n.wizardContactsFeature1,
),
_FeatureItem(
icon: Icons.chat,
text: l10n.wizardContactsFeature2,
),
_FeatureItem(
icon: Icons.battery_std,
text: l10n.wizardContactsFeature3,
),
],
colorScheme: colorScheme,
);
}
Widget _buildMapPage(
BuildContext context,
AppLocalizations l10n,
ColorScheme colorScheme,
) {
return _buildPage(
icon: Icons.map,
iconColor: Colors.red,
title: l10n.wizardMapTitle,
description: l10n.wizardMapDescription,
features: [
_FeatureItem(
icon: Icons.location_on,
text: l10n.wizardMapFeature1,
),
_FeatureItem(
icon: Icons.person_pin_circle,
text: l10n.wizardMapFeature2,
),
_FeatureItem(
icon: Icons.offline_pin,
text: l10n.wizardMapFeature3,
),
_FeatureItem(
icon: Icons.draw,
text: l10n.wizardMapFeature4,
),
],
colorScheme: colorScheme,
);
}
Widget _buildPage({
required IconData icon,
required Color iconColor,
required String title,
required String description,
List<_FeatureItem>? features,
required ColorScheme colorScheme,
}) {
return SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 20),
// Icon
Container(
padding: const EdgeInsets.all(24.0),
decoration: BoxDecoration(
color: iconColor.withValues(alpha: 0.1),
shape: BoxShape.circle,
),
child: Icon(
icon,
size: 80,
color: iconColor,
),
),
const SizedBox(height: 32),
// Title
Text(
title,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
color: colorScheme.onSurface,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
// Description
Text(
description,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: colorScheme.onSurface.withValues(alpha: 0.7),
height: 1.5,
),
textAlign: TextAlign.center,
),
if (features != null && features.isNotEmpty) ...[
const SizedBox(height: 32),
// Features list
...features.map((feature) => Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
children: [
Icon(
feature.icon,
color: colorScheme.primary,
size: 24,
),
const SizedBox(width: 16),
Expanded(
child: Text(
feature.text,
style:
Theme.of(context).textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurface,
),
),
),
],
),
)),
],
const SizedBox(height: 20),
],
),
);
}
}
class _FeatureItem {
final IconData icon;
final String text;
_FeatureItem({required this.icon, required this.text});
}