Refactor SAR marker handling and add template management

- Updated CompassSarList and DetailedCompassDialog to use marker.displayName instead of marker.type.displayName.
- Enhanced DrawingLayer and DrawingMarkersLayer to support simple mode for drawing visibility and interaction.
- Added toggle switches in DrawingToolbar for showing/hiding received drawings and SAR markers.
- Modified MapMarkers to utilize custom emojis and display names for markers.
- Introduced RecipientSelectorSheet for selecting message recipients with search functionality.
- Refactored SarUpdateSheet to use SAR templates instead of marker types, allowing for emoji and name customization.
- Created SarTemplateEditDialog for adding and editing SAR templates with color selection and preview.
This commit is contained in:
Janez T
2025-10-21 23:44:49 +02:00
parent e9d516b749
commit 021ce21cbe
60 changed files with 8736 additions and 1413 deletions

View File

@@ -8,7 +8,9 @@ import '../providers/app_provider.dart';
import '../widgets/contacts/contact_tile.dart';
class ContactsTab extends StatefulWidget {
const ContactsTab({super.key});
final VoidCallback? onNavigateToMap;
const ContactsTab({super.key, this.onNavigateToMap});
@override
State<ContactsTab> createState() => _ContactsTabState();
@@ -87,6 +89,9 @@ class _ContactsTabState extends State<ContactsTab> {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final appProvider = context.watch<AppProvider>();
final isSimpleMode = appProvider.isSimpleMode;
return Consumer<ContactsProvider>(
builder: (context, contactsProvider, child) {
final chatContacts = contactsProvider.chatContacts;
@@ -143,6 +148,7 @@ class _ContactsTabState extends State<ContactsTab> {
currentPosition: _currentPosition,
calculateDistance: _calculateDistanceInMeters,
formatDistance: _formatDistance,
onNavigateToMap: widget.onNavigateToMap,
),
),
const Divider(height: 32),
@@ -161,6 +167,7 @@ class _ContactsTabState extends State<ContactsTab> {
currentPosition: _currentPosition,
calculateDistance: _calculateDistanceInMeters,
formatDistance: _formatDistance,
onNavigateToMap: widget.onNavigateToMap,
),
),
const Divider(height: 32),
@@ -179,13 +186,14 @@ class _ContactsTabState extends State<ContactsTab> {
currentPosition: _currentPosition,
calculateDistance: _calculateDistanceInMeters,
formatDistance: _formatDistance,
onNavigateToMap: widget.onNavigateToMap,
),
),
const Divider(height: 32),
],
// Channels
if (channels.isNotEmpty) ...[
// Channels (hidden in simple mode)
if (!isSimpleMode && channels.isNotEmpty) ...[
_SectionHeader(
title: l10n.channels,
count: channels.length,
@@ -197,6 +205,7 @@ class _ContactsTabState extends State<ContactsTab> {
currentPosition: _currentPosition,
calculateDistance: _calculateDistanceInMeters,
formatDistance: _formatDistance,
onNavigateToMap: widget.onNavigateToMap,
),
),
],

View File

@@ -581,13 +581,14 @@ class _HomeScreenState extends State<HomeScreen>
controller: _tabController,
children: [
MessagesTab(onNavigateToMap: () => _tabController.animateTo(2)),
const ContactsTab(),
ContactsTab(onNavigateToMap: () => _tabController.animateTo(2)),
MapTab(
onFullscreenChanged: (isFullscreen) {
setState(() {
_isMapFullscreen = isFullscreen;
});
},
onNavigateToMessages: () => _tabController.animateTo(0),
),
],
),
@@ -772,32 +773,35 @@ class _HomeScreenState extends State<HomeScreen>
],
),
),
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),
// 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),
),
),
),
],
],
),
),

View File

@@ -3,6 +3,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import '../services/tile_cache_service.dart';
import '../services/validation_service.dart';
import '../services/mbtiles_service.dart';
@@ -391,6 +393,133 @@ class _MapManagementScreenState extends State<MapManagementScreen> {
}
}
Future<void> _exportTiles() async {
try {
// Check if there are tiles to export
final tileCount = await widget.tileCacheService.getCachedTileCount();
if (tileCount == 0) {
_showError(AppLocalizations.of(context)!.noTilesToExport);
return;
}
if (!mounted) return;
setState(() {
_isLoading = true;
_statusMessage = AppLocalizations.of(context)!.exportingTiles;
});
// Export to temporary directory first (works on all platforms)
final tempDir = await getTemporaryDirectory();
final fileName = 'meshcore_tiles_${DateTime.now().millisecondsSinceEpoch}.fmtc';
final tempFilePath = '${tempDir.path}/$fileName';
final exportedCount = await widget.tileCacheService.exportStore(tempFilePath);
if (!mounted) return;
setState(() {
_isLoading = false;
_statusMessage = null;
});
// Share the file using share_plus (works on all platforms)
final file = File(tempFilePath);
if (await file.exists()) {
// Get the button position for iPad popover
final box = context.findRenderObject() as RenderBox?;
final sharePositionOrigin = box != null
? box.localToGlobal(Offset.zero) & box.size
: null;
final result = await SharePlus.instance.share(
ShareParams(
files: [XFile(tempFilePath)],
subject: 'MeshCore Map Tiles Export',
text: 'Exported $exportedCount map tiles',
sharePositionOrigin: sharePositionOrigin,
),
);
if (mounted) {
if (result.status == ShareResultStatus.success) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.exportSuccess(exportedCount)),
backgroundColor: Colors.green,
),
);
}
}
} else {
_showError('Export file not found');
}
} catch (e) {
if (!mounted) return;
setState(() {
_isLoading = false;
_statusMessage = null;
});
_showError(AppLocalizations.of(context)!.exportFailed(e.toString()));
}
}
Future<void> _importTiles() async {
try {
// Use file picker to select import file
final result = await FilePicker.platform.pickFiles(
dialogTitle: AppLocalizations.of(context)!.selectImportFile,
type: FileType.custom,
allowedExtensions: ['fmtc'],
);
if (result == null || result.files.isEmpty) return;
final filePath = result.files.first.path;
if (filePath == null) return;
if (!mounted) return;
setState(() {
_isLoading = true;
_statusMessage = AppLocalizations.of(context)!.importingTiles;
});
// Optional: Preview stores in archive before importing
try {
final stores = await widget.tileCacheService.listArchiveStores(filePath);
debugPrint('Archive contains stores: $stores');
} catch (e) {
debugPrint('Could not list stores: $e');
}
final importResult = await widget.tileCacheService.importStore(filePath);
if (!mounted) return;
setState(() {
_isLoading = false;
_statusMessage = null;
});
await _loadCacheStats(); // Refresh stats after import
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context)!.importSuccess(importResult['successfulStores'] as int),
),
backgroundColor: Colors.green,
),
);
}
} catch (e) {
if (!mounted) return;
setState(() {
_isLoading = false;
_statusMessage = null;
});
_showError(AppLocalizations.of(context)!.importFailed(e.toString()));
}
}
void _showError(String message) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -424,6 +553,10 @@ class _MapManagementScreenState extends State<MapManagementScreen> {
_buildMbtilesCard(),
const SizedBox(height: 16),
// Import/Export Cached Tiles
_buildImportExportCard(),
const SizedBox(height: 16),
// Download Region
_buildDownloadCard(),
const SizedBox(height: 16),
@@ -636,6 +769,60 @@ class _MapManagementScreenState extends State<MapManagementScreen> {
);
}
Widget _buildImportExportCard() {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
AppLocalizations.of(context)!.importExportCachedTiles,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
AppLocalizations.of(context)!.importExportDescription,
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
const SizedBox(height: 16),
// Export Section
ElevatedButton.icon(
onPressed: _isDownloading || _isLoading ? null : _exportTiles,
icon: const Icon(Icons.file_upload),
label: Text(AppLocalizations.of(context)!.exportTilesToFile),
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(48),
),
),
const SizedBox(height: 8),
Text(
AppLocalizations.of(context)!.exportNote,
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
const SizedBox(height: 16),
// Import Section
ElevatedButton.icon(
onPressed: _isDownloading || _isLoading ? null : _importTiles,
icon: const Icon(Icons.file_download),
label: Text(AppLocalizations.of(context)!.importTilesFromFile),
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(48),
),
),
const SizedBox(height: 8),
Text(
AppLocalizations.of(context)!.importNote,
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
],
),
),
);
}
Widget _buildInfoRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),

View File

@@ -41,10 +41,12 @@ import 'map_management_screen.dart';
class MapTab extends StatefulWidget {
final Function(bool)? onFullscreenChanged;
final VoidCallback? onNavigateToMessages;
const MapTab({
super.key,
this.onFullscreenChanged,
this.onNavigateToMessages,
});
@override
@@ -96,6 +98,15 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
// Access the singleton LocationTrackingService from AppProvider
LocationTrackingService get _locationService => LocationTrackingService();
/// Helper to compare public keys byte-by-byte
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();
@@ -867,17 +878,17 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
builder: (context) => SarUpdateSheet(
prePopulatedPosition: position,
allowLocationUpdate: false, // Don't allow changing to current location
onSend: (sarType, position, notes, roomPublicKey, sendToChannel) async {
await _sendSarMessage(sarType, position, notes, roomPublicKey, sendToChannel);
onSend: (emoji, name, position, roomPublicKey, sendToChannel) async {
await _sendSarMessage(emoji, name, position, roomPublicKey, sendToChannel);
},
),
);
}
Future<void> _sendSarMessage(
SarMarkerType sarType,
String emoji,
String name,
Position position,
String? notes,
Uint8List? roomPublicKey,
bool sendToChannel,
) async {
@@ -907,27 +918,50 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
}
try {
// Format: S:<emoji>:<latitude>,<longitude>
final sarMessage = 'S:${sarType.emoji}:${position.latitude},${position.longitude}';
// Add notes if provided
final fullMessage = notes != null && notes.isNotEmpty
? '$sarMessage $notes'
: sarMessage;
// Format: S:<emoji>:<latitude>,<longitude>:<name>
// Round coordinates to 5 decimal places (~1m accuracy) since most GPS is only that accurate
final sarMessage = 'S:$emoji:${position.latitude.toStringAsFixed(5)},${position.longitude.toStringAsFixed(5)}:$name';
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: fullMessage,
text: sarMessage,
messageId: messageId,
);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('${sarType.displayName} marker broadcast to public channel'),
const SnackBar(
content: Text('SAR marker broadcast to public channel'),
backgroundColor: Colors.orange,
duration: const Duration(seconds: 2),
duration: Duration(seconds: 2),
),
);
} else {
@@ -939,7 +973,7 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
final devicePublicKey = connectionProvider.deviceInfo.publicKey;
final senderPublicKeyPrefix = devicePublicKey?.sublist(0, 6);
// Create sent message object
// Create sent message object with recipient public key for retry support
final sentMessage = Message(
id: messageId,
messageType: MessageType.contact,
@@ -947,20 +981,29 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: timestamp,
text: fullMessage,
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: fullMessage,
text: sarMessage,
messageId: messageId, // Pass message ID so it can be tracked
contact: roomContact, // Include contact for path status logging
);
if (!sentSuccessfully) {
@@ -970,10 +1013,10 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('${sarType.displayName} marker sent to room'),
const SnackBar(
content: Text('SAR marker sent to room'),
backgroundColor: Colors.green,
duration: const Duration(seconds: 2),
duration: Duration(seconds: 2),
),
);
}
@@ -991,10 +1034,17 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
final appProvider = context.watch<AppProvider>();
final isSimpleMode = appProvider.isSimpleMode;
return Consumer3<ContactsProvider, MessagesProvider, DrawingProvider>(
builder: (context, contactsProvider, messagesProvider, drawingProvider, child) {
final contactsWithLocation = contactsProvider.contactsWithLocation;
final sarMarkers = messagesProvider.sarMarkers;
// Filter SAR markers based on visibility toggle
final allSarMarkers = messagesProvider.sarMarkers;
final sarMarkers = drawingProvider.showSarMarkers
? allSarMarkers
: <SarMarker>[];
final center = _calculateCenter(contactsWithLocation, sarMarkers);
return Stack(
@@ -1167,6 +1217,7 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
DrawingLayer(
drawings: drawingProvider.drawings,
previewDrawing: drawingProvider.getPreviewDrawing(),
isSimpleMode: isSimpleMode,
),
MarkerLayer(
markers: [
@@ -1191,12 +1242,9 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
context: context,
mapRotation: _getMapRotation(),
onTap: (marker) {
_showDetailedCompassWithSarMarker(
context,
contactsProvider.contactsWithLocation,
messagesProvider.sarMarkers,
marker,
);
// Navigate to the corresponding message in Messages tab
messagesProvider.navigateToMessage(marker.id);
widget.onNavigateToMessages?.call();
},
),
// User location marker
@@ -1284,9 +1332,17 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
DrawingMarkersLayer(
drawings: drawingProvider.drawings,
showDeleteButtons: drawingProvider.isDrawing,
isSimpleMode: isSimpleMode,
onDeleteDrawing: (drawingId) {
drawingProvider.removeDrawing(drawingId);
},
onTapDrawing: (drawing) {
// Navigate to the corresponding message in Messages tab
if (drawing.messageId != null) {
messagesProvider.navigateToMessage(drawing.messageId!);
widget.onNavigateToMessages?.call();
}
},
),
],
),
@@ -1406,6 +1462,21 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
child: const Icon(Icons.layers),
),
const SizedBox(height: 8),
// In simple mode: show fullscreen button directly
// In normal mode: show options menu (which includes fullscreen)
if (context.watch<AppProvider>().isSimpleMode)
FloatingActionButton.small(
heroTag: 'fullscreen_toggle',
onPressed: () {
setState(() {
_isFullscreen = !_isFullscreen;
});
_saveSettings();
widget.onFullscreenChanged?.call(_isFullscreen);
},
child: Icon(_isFullscreen ? Icons.fullscreen_exit : Icons.fullscreen),
)
else
FloatingActionButton.small(
heroTag: 'options_menu',
onPressed: () => _showOptionsMenu(context),

View File

@@ -1,4 +1,3 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
@@ -8,12 +7,14 @@ import '../providers/contacts_provider.dart';
import '../providers/map_provider.dart';
import '../providers/connection_provider.dart';
import '../models/message.dart';
import '../models/contact.dart';
import '../models/sar_marker.dart';
import '../widgets/messages/sar_update_sheet.dart';
import '../widgets/messages/recipient_selector_sheet.dart';
import '../widgets/contacts/direct_message_sheet.dart';
import '../services/message_destination_preferences.dart';
import '../utils/toast_logger.dart';
import '../l10n/app_localizations.dart';
import '../utils/sar_marker_extensions.dart';
import '../utils/message_extensions.dart';
class MessagesTab extends StatefulWidget {
@@ -28,8 +29,14 @@ class MessagesTab extends StatefulWidget {
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) {
@@ -44,9 +51,21 @@ class _MessagesTabState extends State<MessagesTab> {
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();
// Check for navigation request whenever dependencies change
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkForNavigationRequest();
});
}
@@ -54,21 +73,183 @@ class _MessagesTabState extends State<MessagesTab> {
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;
ToastLogger.success(
context,
'Messages will be sent to: $recipientName',
);
}
/// 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;
@@ -77,37 +258,23 @@ class _MessagesTabState extends State<MessagesTab> {
}
try {
// 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,
);
// 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();
@@ -119,17 +286,104 @@ class _MessagesTabState extends State<MessagesTab> {
}
}
/// 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: (sarType, position, notes, roomPublicKey, sendToChannel) async {
onSend: (emoji, name, position, roomPublicKey, sendToChannel) async {
await _sendSarMessage(
sarType,
emoji,
name,
position,
notes,
roomPublicKey,
sendToChannel,
);
@@ -139,9 +393,9 @@ class _MessagesTabState extends State<MessagesTab> {
}
Future<void> _sendSarMessage(
SarMarkerType sarType,
String emoji,
String name,
Position position,
String? notes,
Uint8List? roomPublicKey,
bool sendToChannel,
) async {
@@ -161,14 +415,10 @@ class _MessagesTabState extends State<MessagesTab> {
}
try {
// Format: S:<emoji>:<latitude>,<longitude>
// Format: S:<emoji>:<latitude>,<longitude>:<name>
// Round coordinates to 5 decimal places (~1m accuracy) since most GPS is only that accurate
final sarMessage =
'S:${sarType.emoji}:${position.latitude},${position.longitude}';
// Add notes if provided
final fullMessage = notes != null && notes.isNotEmpty
? '$sarMessage $notes'
: sarMessage;
'S:$emoji:${position.latitude.toStringAsFixed(5)},${position.longitude.toStringAsFixed(5)}:$name';
if (sendToChannel) {
// Create message ID
@@ -187,7 +437,7 @@ class _MessagesTabState extends State<MessagesTab> {
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: timestamp,
text: fullMessage,
text: sarMessage,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
channelIdx: 0,
@@ -200,14 +450,14 @@ class _MessagesTabState extends State<MessagesTab> {
// Send to public channel (ephemeral, over-the-air only)
await connectionProvider.sendChannelMessage(
channelIdx: 0,
text: fullMessage,
text: sarMessage,
messageId: messageId,
);
if (!mounted) return;
ToastLogger.success(
context,
'${sarType.getLocalizedName(context)} marker broadcast to public channel',
'SAR marker broadcast to public channel',
);
} else {
// Create message ID
@@ -226,7 +476,7 @@ class _MessagesTabState extends State<MessagesTab> {
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: timestamp,
text: fullMessage,
text: sarMessage,
receivedAt: DateTime.now(),
deliveryStatus: MessageDeliveryStatus.sending,
recipientPublicKey: roomPublicKey, // Store recipient for retry
@@ -246,7 +496,7 @@ class _MessagesTabState extends State<MessagesTab> {
// Send SAR message to selected room (persisted and immutable)
final sentSuccessfully = await connectionProvider.sendTextMessage(
contactPublicKey: roomPublicKey!,
text: fullMessage,
text: sarMessage,
messageId: messageId, // Pass message ID so it can be tracked
contact: roomContact, // Include contact for path status logging
);
@@ -259,7 +509,7 @@ class _MessagesTabState extends State<MessagesTab> {
if (!mounted) return;
ToastLogger.success(
context,
'${sarType.getLocalizedName(context)} marker sent to room',
'SAR marker sent to room',
);
}
} catch (e) {
@@ -359,11 +609,13 @@ class _MessagesTabState extends State<MessagesTab> {
),
)
: 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;
// Display system messages with minimal styling
if (message.isSystemMessage) {
@@ -372,6 +624,7 @@ class _MessagesTabState extends State<MessagesTab> {
return _MessageBubble(
message: message,
isHighlighted: isHighlighted,
onTap:
message.isSarMarker &&
message.sarGpsCoordinates != null
@@ -420,7 +673,22 @@ class _MessagesTabState extends State<MessagesTab> {
).colorScheme.onPrimaryContainer,
),
),
const SizedBox(width: 8),
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(
@@ -431,7 +699,9 @@ class _MessagesTabState extends State<MessagesTab> {
maxLengthEnforcement: MaxLengthEnforcement.enforced,
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
hintText: AppLocalizations.of(context)!.typeYourMessage,
hintText: AppLocalizations.of(
context,
)!.typeYourMessage,
hintStyle: const TextStyle(fontSize: 14),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
@@ -448,7 +718,9 @@ class _MessagesTabState extends State<MessagesTab> {
fontSize: 10,
color: _characterCount > _maxCharacters * 0.9
? Colors.orange
: Theme.of(context).textTheme.bodySmall?.color,
: Theme.of(
context,
).textTheme.bodySmall?.color,
),
suffixIcon: IconButton(
icon: Icon(
@@ -481,8 +753,13 @@ class _MessagesTabState extends State<MessagesTab> {
class _MessageBubble extends StatelessWidget {
final Message message;
final VoidCallback? onTap;
final bool isHighlighted;
const _MessageBubble({required this.message, this.onTap});
const _MessageBubble({
required this.message,
this.onTap,
this.isHighlighted = false,
});
/// Helper method to compare two public keys for equality
bool _publicKeysMatch(Uint8List key1, Uint8List key2) {
@@ -604,11 +881,11 @@ class _MessageBubble extends StatelessWidget {
// Copy text option
ListTile(
leading: const Icon(Icons.copy),
title: const Text('Copy text'),
title: Text(AppLocalizations.of(context)!.copyText),
onTap: () {
Clipboard.setData(ClipboardData(text: message.text));
Navigator.pop(context);
ToastLogger.success(context, 'Text copied to clipboard');
ToastLogger.success(context, AppLocalizations.of(context)!.textCopiedToClipboard);
},
),
// Delete message option
@@ -672,8 +949,8 @@ class _MessageBubble extends StatelessWidget {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Delete message'),
content: const Text('Are you sure you want to delete this message?'),
title: Text(l10n.deleteMessage),
content: Text(l10n.deleteMessageConfirmation),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
@@ -684,10 +961,10 @@ class _MessageBubble extends StatelessWidget {
final messagesProvider = context.read<MessagesProvider>();
messagesProvider.deleteMessage(message.id);
Navigator.pop(context);
ToastLogger.info(context, 'Message deleted');
ToastLogger.info(context, l10n.messageDeleted);
},
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('Delete'),
child: Text(l10n.delete),
),
],
),
@@ -820,39 +1097,55 @@ class _MessageBubble extends StatelessWidget {
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: isSarMarker
? _getSarMarkerColor(context, isDarkMode)
: _getMessageBubbleColor(context, isOwnMessage, isDarkMode),
color: isHighlighted
? Theme.of(context).colorScheme.primaryContainer
: isSarMarker
? _getSarMarkerColor(context, isDarkMode)
: _getMessageBubbleColor(context, isOwnMessage, isDarkMode),
borderRadius: BorderRadius.circular(12),
border: isSarMarker
border: isHighlighted
? Border.all(
color: _getSarMarkerBorderColor(context, isDarkMode),
width: 2,
color: Theme.of(context).colorScheme.primary,
width: 3,
)
: isOwnMessage
? Border.all(
color: Theme.of(
context,
).colorScheme.primary.withValues(alpha: 0.3),
width: 1.5,
)
: !message.isRead &&
!message.isSentMessage &&
!message.isSystemMessage
? Border.all(color: Colors.blue, width: 1.5)
: null,
boxShadow: isSarMarker
: isSarMarker
? Border.all(
color: _getSarMarkerBorderColor(context, isDarkMode),
width: 2,
)
: isOwnMessage
? Border.all(
color: Theme.of(
context,
).colorScheme.primary.withValues(alpha: 0.3),
width: 1.5,
)
: !message.isRead &&
!message.isSentMessage &&
!message.isSystemMessage
? Border.all(color: Colors.blue, width: 1.5)
: null,
boxShadow: isHighlighted
? [
BoxShadow(
color: _getSarMarkerBorderColor(
context,
isDarkMode,
).withValues(alpha: 0.3),
blurRadius: 8,
color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.5),
blurRadius: 12,
spreadRadius: 2,
offset: const Offset(0, 2),
),
]
: null,
: isSarMarker
? [
BoxShadow(
color: _getSarMarkerBorderColor(
context,
isDarkMode,
).withValues(alpha: 0.3),
blurRadius: 8,
offset: const Offset(0, 2),
),
]
: null,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -968,7 +1261,8 @@ class _MessageBubble extends StatelessWidget {
Row(
children: [
Text(
message.sarMarkerType!.emoji,
// Use custom emoji if available (for unknown types), otherwise use type emoji
message.sarCustomEmoji ?? message.sarMarkerType!.emoji,
style: const TextStyle(fontSize: 28),
),
const SizedBox(width: 10),
@@ -977,7 +1271,10 @@ class _MessageBubble extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
message.sarMarkerType!.getLocalizedName(context),
// Show template name (sarNotes) if available, otherwise show localized type name
message.sarNotes != null && message.sarNotes!.isNotEmpty
? message.sarNotes!
: message.sarMarkerType!.getLocalizedName(context),
style: Theme.of(context).textTheme.titleSmall
?.copyWith(fontWeight: FontWeight.bold),
),
@@ -997,23 +1294,6 @@ class _MessageBubble extends StatelessWidget {
),
],
),
// Display SAR notes/message if present
if (message.sarNotes != null && message.sarNotes!.isNotEmpty) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceVariant.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(8),
),
child: Text(
message.sarNotes!,
style: Theme.of(context).textTheme.bodySmall,
),
),
],
]
// Regular message content
else

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.name),
),
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.name),
),
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.name,
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,
),
),
);
}
}

View File

@@ -12,6 +12,7 @@ import '../services/locale_preferences.dart';
import '../utils/sample_data_generator.dart';
import '../theme/app_theme.dart';
import '../l10n/app_localizations.dart';
import 'sar_template_management_screen.dart';
class SettingsScreen extends StatefulWidget {
final Function(AppThemeMode) onThemeChanged;
@@ -259,27 +260,27 @@ class _SettingsScreenState extends State<SettingsScreen> {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Row(
title: Row(
children: [
Icon(Icons.settings, size: 24),
SizedBox(width: 12),
Text('Location Permission'),
const Icon(Icons.settings, size: 24),
const SizedBox(width: 12),
Text(AppLocalizations.of(context)!.locationPermission),
],
),
content: const Text(
'Location permission is permanently denied. Please enable it in your device settings to use GPS tracking and location sharing features.',
content: Text(
AppLocalizations.of(context)!.locationPermissionDialogContent,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
child: Text(AppLocalizations.of(context)!.cancel),
),
ElevatedButton(
onPressed: () async {
Navigator.pop(context);
await Geolocator.openAppSettings();
},
child: const Text('Open Settings'),
child: Text(AppLocalizations.of(context)!.openSettings),
),
],
),
@@ -294,8 +295,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
newPermission == LocationPermission.always) {
// Permission granted
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Location permission granted!'),
SnackBar(
content: Text(AppLocalizations.of(context)!.locationPermissionGranted),
backgroundColor: Colors.green,
),
);
@@ -303,10 +304,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
} else {
// Permission denied
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Location permission is required for GPS tracking and location sharing.'),
SnackBar(
content: Text(AppLocalizations.of(context)!.locationPermissionRequiredForGps),
backgroundColor: Colors.orange,
duration: Duration(seconds: 4),
duration: const Duration(seconds: 4),
),
);
}
@@ -314,8 +315,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
// Already granted - show info
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Location permission is already granted.'),
SnackBar(
content: Text(AppLocalizations.of(context)!.locationPermissionAlreadyGranted),
backgroundColor: Colors.blue,
),
);
@@ -433,6 +434,17 @@ class _SettingsScreenState extends State<SettingsScreen> {
await _saveRxTxPreference(value);
},
),
Consumer<AppProvider>(
builder: (context, appProvider, child) => SwitchListTile(
secondary: const Icon(Icons.visibility_off),
title: Text(AppLocalizations.of(context)!.simpleMode),
subtitle: Text(AppLocalizations.of(context)!.simpleModeDescription),
value: appProvider.isSimpleMode,
onChanged: (value) async {
await appProvider.toggleSimpleMode(value);
},
),
),
ListTile(
leading: const Icon(Icons.language),
title: Text(AppLocalizations.of(context)!.language),
@@ -440,18 +452,32 @@ class _SettingsScreenState extends State<SettingsScreen> {
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLanguageDialog(),
),
ListTile(
leading: const Icon(Icons.location_searching),
title: Text(AppLocalizations.of(context)!.sarTemplates),
subtitle: Text(AppLocalizations.of(context)!.manageSarTemplates),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SarTemplateManagementScreen(),
),
);
},
),
const Divider(),
// Permissions Section
_buildSectionHeader('Permissions'),
_buildSectionHeader(AppLocalizations.of(context)!.permissionsSection),
ListTile(
leading: const Icon(Icons.location_on),
title: const Text('Location Permission'),
title: Text(AppLocalizations.of(context)!.locationPermission),
subtitle: FutureBuilder<LocationPermission>(
future: Geolocator.checkPermission(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Text('Checking...');
return Text(AppLocalizations.of(context)!.checking);
}
final permission = snapshot.data!;
String statusText;
@@ -459,23 +485,23 @@ class _SettingsScreenState extends State<SettingsScreen> {
switch (permission) {
case LocationPermission.always:
statusText = 'Granted (Always)';
statusText = AppLocalizations.of(context)!.locationPermissionGrantedAlways;
statusColor = Colors.green;
break;
case LocationPermission.whileInUse:
statusText = 'Granted (While In Use)';
statusText = AppLocalizations.of(context)!.locationPermissionGrantedWhileInUse;
statusColor = Colors.green;
break;
case LocationPermission.denied:
statusText = 'Denied - Tap to request';
statusText = AppLocalizations.of(context)!.locationPermissionDeniedTapToRequest;
statusColor = Colors.orange;
break;
case LocationPermission.deniedForever:
statusText = 'Permanently Denied - Open Settings';
statusText = AppLocalizations.of(context)!.locationPermissionPermanentlyDeniedOpenSettings;
statusColor = Colors.red;
break;
default:
statusText = 'Unknown';
statusText = AppLocalizations.of(context)!.unknown;
statusColor = Colors.grey;
}
@@ -906,7 +932,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
RadioListTile<AppThemeMode>(
title: Row(
children: [
const Text('SAR Navy Blue'),
Text(AppLocalizations.of(context)!.sarNavyBlue),
const SizedBox(width: 8),
Container(
width: 16,
@@ -919,7 +945,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
],
),
subtitle: const Text('Professional/Operations Mode'),
subtitle: Text(AppLocalizations.of(context)!.sarNavyBlueDescription),
value: AppThemeMode.sarNavyBlue,
groupValue: _selectedTheme,
onChanged: (value) {