Compare commits

...
Author SHA1 Message Date
stopflock 00b9348b8f version, changelog 2026-09-04 14:59:43 -05:00
stopflock 142389771e Merge pull request #195 from reb1995/add-notifications-android-and-background-fixes
Fix notifications and enable background data fetch while app is not focused.
2026-09-04 13:24:30 -05:00
Ryan Brown 8439d9bbb6 Fix late background alerts and cache starvation
- Increase background refresh threshold: Raised the edge distance check in GpsController from 1000m to 2500m to guarantee new Overpass data is fetched well before the user drives out of the cached bounding box.

- Fix bounding box race condition: Added await to the background fetch handler in MapView so tracking bounds only shift forward after the network request successfully finishes.

- Make debounced fetches awaitable: Refactored fetchAndUpdate in NodeProviderWithCache to return a Future<void> using a Completer, bridging the 400ms debounce timer.

- Prevent hanging futures: Added state checks for _activeCompleter to instantly resolve canceled network requests during rapid map panning, preventing fatal StateError crashes and infinite UI hangs.
2026-08-28 12:03:39 -04:00
Ryan Brown 3f118a77c4 Fix branch after android testing. Add background data refresh, not just location refresh.
Tested on a Pixel 10 Pro. These changes were needed to work on real hardware. Also, which background location updating was working, the data was not refreshing in the background. This also adds that. It will pull nodes in a 5km area around your location and update when you within 1km of the area. These values may need to be adjusted if there is increased load on the servers.
2026-08-27 10:55:11 -07:00
Joeseph Ferland 51037f3710 feat: Added Notifications to app 2026-08-27 10:55:11 -07:00
stopflock 2c64fe610e Merge pull request #187 from anthony-at-pieces/fix/issue-157-direction-notation
Fix direction notation edit detection
2026-08-25 12:40:06 -05:00
stopflock af2ff1e940 Merge pull request #193 from FoggedLens/changeset_tracking
add changeset comment tracking and message notification bubble on startup
2026-08-24 18:55:20 -05:00
stopflock 7722dcaabe fix unnecessary cast 2026-08-24 18:16:36 -05:00
stopflock 0e359f2aa9 add changeset comment tracking and message notification bubble on startup 2026-08-24 18:03:03 -05:00
Anthony Maio 60e7e59ae9 fix: detect direction notation edits 2026-08-16 18:33:57 -04:00
stopflock bdc5399c9f disable dev mode 2026-08-04 21:44:23 -05:00
stopflock eb6a409b92 disable auto-open details sheet 2026-08-04 21:44:10 -05:00
stopflock 1909a3b5f1 version, changelog, enable dev modes 2026-08-04 11:56:29 -05:00
stopflock 7c5d066362 Fix node constrainment when part of a way/relation 2026-08-03 20:21:19 -05:00
stopflock b231b48ac1 add localize tool - reliably check, read, and write language files 2026-08-01 11:30:49 -05:00
stopflock 0e1e9cb2ff fix deeplinks 2026-07-31 21:35:01 -05:00
stopflock a808a4f37e notice about any in-flight submissions when enabling queue pause or offline mode 2026-07-26 18:54:53 -05:00
stopflock 0887d1ef44 disable dev mode before release 2026-07-26 15:20:19 -05:00
stopflock 0c6cf467fe add trap for potential async context issue found by linter 2026-07-26 04:05:54 -05:00
stopflock c787589205 temp enable dev mode 2026-07-26 03:46:29 -05:00
stopflock 837f59bfde auto-open tags sheet for submissions (pending testing/feedback) 2026-07-26 03:46:00 -05:00
stopflock 8148ad55c2 node tags sheet no longer behaves poorly when viewing a node during submission 2026-07-26 02:58:35 -05:00
stopflock dfcc64e96e offline options globally toggleable 2026-07-25 20:40:15 -05:00
stopflock 6f017fd6c1 version, changelog 2026-07-25 19:28:32 -05:00
stopflock 78f1ef58de selectable/copyable node tags, pending submission status on details sheet, "view on osm" button styling 2026-07-25 19:27:11 -05:00
stopflock 3e2c9c5b9e add option to hide zoom controls and indicator 2026-07-25 18:04:54 -05:00
stopflock dd93ac64b6 changelog 2026-07-25 17:44:18 -05:00
stopflock 096fb5868b require delete reason, give options 2026-07-25 17:43:41 -05:00
stopflock 974204bd91 prevent deletes without being logged in 2026-07-25 17:11:39 -05:00
stopflock 6a0d4cd8f7 Merge pull request #182 from FoggedLens/location-fixes
Location fixes
2026-07-25 16:47:28 -05:00
stopflock af2a08bf3d better limits for min/max zoom validations, separate lat+lon validation, less verbose comments 2026-07-25 16:42:38 -05:00
stopflock dd8c9b88cc bump version and changelog 2026-07-25 16:32:25 -05:00
stopflock 1cfca663a6 catch and correct possible bad values for lat/lon, add tests 2026-07-25 16:32:08 -05:00
stopflock b9110c1670 Merge pull request #177 from reb1995/Fix-172-Sanitize-tags
Fixes 172: Sanitize tags when editing or creating a node
2026-07-17 14:48:34 -05:00
Ryan Brown 36675508e8 Sanitize tags. 2026-07-16 19:23:42 -04:00
stopflock 9a0928d22d version bump 2026-07-15 21:58:29 -05:00
stopflock b3001927c6 Merge pull request #176 from FoggedLens/no-429-splitting
No 429 splitting, bring back query reduction
2026-07-15 21:39:25 -05:00
stopflock b9d82d6de7 change mock node color to green 2026-07-15 21:29:54 -05:00
stopflock 38eee8d125 Bring back profile subsumption elimination for overpass queries 2026-07-15 21:20:44 -05:00
stopflock f8632b6a06 remove extraneous unreferenced file 2026-07-15 19:39:06 -05:00
stopflock be2fe84db5 first pass 2026-07-15 18:01:29 -05:00
stopflock 2cddcbef7d forgot a file - maybe why suspected locations not updating 2026-07-15 16:29:55 -05:00
stopflock 60c17c41bf Merge pull request #174 from FoggedLens/overpass-load-2
fuck me
2026-07-14 14:32:48 -05:00
stopflock ee8ead6695 fuck me 2026-07-14 14:32:27 -05:00
stopflock 4d6bea8cfe Merge pull request #173 from FoggedLens/reduce-overpass-query-heaviness
out skel -> out ids
2026-07-14 14:22:57 -05:00
stopflock 25c1611fd3 out skel -> out ids 2026-07-14 14:21:39 -05:00
66 changed files with 3916 additions and 788 deletions

No files matched your search

+10 -13
View File
@@ -297,26 +297,23 @@ These are internal app tags, not OSM tags. The underscore prefix makes this expl
- **Sandbox (OSM API)**: Zoom ≥ 13 (stricter due to bbox limits)
**Smart error handling & splitting:**
- **50k node limit**: Automatically splits query into 4 quadrants, recursively up to 3 levels deep
- **Timeout errors**: Also triggers splitting (dense areas with many profiles)
- **Rate limiting**: Extended backoff (30s), no splitting (would make it worse)
- **Surgical detection**: Only splits on actual limit errors, not network issues
- **50k node limit**: Automatically splits query into 4 quadrants, recursively up to 3 levels deep. This is a deterministic result-set size limit, so shrinking the queried area is the correct fix.
- **Timeout errors**: Treated as a plain retryable network error — no splitting. Timeouts usually indicate server load or an expensive query, not "too much area", so firing off more sub-requests would only add load to an already-struggling server.
- **Rate limiting (HTTP 429)**: Extended backoff (30s), no splitting (would make it worse). Still surfaces the same "slow" status indicator as the node-limit-splitting case, so the user sees consistent feedback either way.
- **Surgical detection**: Only splits on the actual 50k node limit, not timeouts or other network issues.
**Query optimization & deduplication:**
- **Pre-fetch limit**: 4x user's display limit (e.g., 1000 nodes for 250 display limit)
- **Profile deduplication**: Automatically removes redundant profiles from queries using subsumption analysis
- **User-initiated detection**: Only reports loading status for user-facing operations
- **Background operations**: Pre-fetch runs silently, doesn't trigger loading states
**Profile subsumption optimization (v2.1.1+):**
To reduce Overpass query complexity, profiles are deduplicated before query generation:
**Query optimization & deduplication (in `OverpassService._buildQuery`):**
Profiles are deduplicated before query generation via subsumption analysis:
- **Subsumption rule**: Profile A subsumes profile B if all of A's non-empty tags exist in B with identical values
- **Example**: `Generic ALPR` (tags: `man_made=surveillance, surveillance:type=ALPR`) subsumes `Flock` (same tags + `manufacturer=Flock Safety`)
- **Result**: Default profile set reduces from ~11 to ~2 query clauses (Generic ALPR + Generic Gunshot)
- **UI unchanged**: All enabled profiles still used for post-query filtering and display matching
- **UI unchanged**: All enabled profiles still used for post-query filtering and display matching (see `NodeProviderWithCache._matchesAnyProfile`), independent of which clauses were sent to Overpass
- **Safety fallback**: if dedup would remove every profile (e.g. all profiles have only empty tags), the original full list is used instead of sending an empty query
**Why this approach:**
Dense urban areas (SF, NYC) with many profiles enabled can easily exceed both 50k node limits and 25s timeouts. Profile deduplication reduces query complexity by ~80% for default setups, while automatic splitting handles remaining edge cases. Surgical error detection avoids unnecessary API load from network issues.
Dense urban areas (SF, NYC) with many profiles enabled can easily exceed both 50k node limits and 45s timeouts. Profile deduplication reduces query complexity by ~80% for default setups. Surgical error detection avoids unnecessary API load from network issues.
### 6. Uploader Service Architecture (Refactored v1.5.3)
+33
View File
@@ -10,6 +10,26 @@
<!-- Notification permission for proximity alerts -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<!-- Background location for proximity alerts. Android stops delivering
location to a backgrounded app within a few minutes unless it is
running a foreground service, so geolocator is given a
ForegroundNotificationConfig while proximity alerts are enabled -
that starts its GeolocatorLocationService (already declared by the
geolocator_android plugin manifest) and keeps the stream alive.
FOREGROUND_SERVICE_LOCATION is required from Android 14 onward.
Deliberately NOT declaring ACCESS_BACKGROUND_LOCATION: the foreground
service covers our case without it, and merely listing it in the
manifest makes geolocator append it to the very first permission
request - which Android 11+ silently denies, because foreground and
background location cannot be asked for in one prompt. That would
degrade first-run permissions for every user, including those who
never turn proximity alerts on. It also drags in the Play Store
background-location declaration review. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:name="${applicationName}"
android:label="DeFlock"
@@ -30,6 +50,19 @@
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme" />
<!-- Disable Flutter's implicit deep-link routing so that
app_links/DeepLinkService is the sole handler of incoming
deflockapp:// URIs. Without this, Flutter's engine also
tries to auto-convert the URI into a Navigator route
(e.g. "/add?p=...") which conflicts with the navigation
DeepLinkService performs, causing screens pushed by
DeepLinkService to be immediately buried by a duplicate
HomeScreen route. -->
<meta-data
android:name="flutter_deeplinking_enabled"
android:value="false" />
<!-- Launcher intent -->
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
+36
View File
@@ -1,4 +1,40 @@
{
"2.11.1": {
"content": [
"• Fix FOV-only edits not registering as a change",
"• Notify on changeset comments and show a popup bubble on launch"
]
},
"2.11.0": {
"content": [
"• Further improve node loading performance",
"• Fix node constrainment when part of a way/relation",
"• Show submission status in details sheet",
"• Fix profile import links not opening"
]
},
"2.10.5": {
"content": [
"• Make node tags selectable / copyable",
"• Add status indicator to details sheet for pending nodes",
"• Global toggle for offline features",
"• Auto-open details sheet for new add/edit/deletes"
]
},
"2.10.4": {
"content": [
"• Catch and correct a couple rare map bounds issues",
"• Prevent queueing a deletion without being logged in",
"• Require a reason for deletion, provide options in a dropdown",
"• Add option to hide zoom controls in advanced settings"
]
},
"2.10.3": {
"content": [
"• Data loading performance improvements",
"• Node marker when submitting now green for visibility"
]
},
"2.10.2": {
"content": [
"• Added tap and hold gesture on empty map area to add a node at that location",
+11
View File
@@ -1,5 +1,6 @@
import Flutter
import UIKit
import UserNotifications
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
@@ -7,6 +8,16 @@ import UIKit
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Required by flutter_local_notifications: the plugin implements
// userNotificationCenter(_:willPresent:withCompletionHandler:), which is
// what allows a notification to appear while the app is in the foreground.
// iOS only calls it on the registered delegate, and the plugin does not
// register itself — without this line, foreground notifications are
// silently suppressed by the system.
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
+23
View File
@@ -2,8 +2,19 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- Disable Flutter's implicit deep-link routing so that
app_links/DeepLinkService is the sole handler of incoming
deflockapp:// URIs. Without this, Flutter's engine also tries
to auto-convert the URI into a Navigator route (e.g.
"/add?p=...") which conflicts with the navigation
DeepLinkService performs, causing screens pushed by
DeepLinkService to be immediately buried by a duplicate
HomeScreen route. -->
<key>FlutterDeepLinkingEnabled</key>
<false/>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
@@ -43,6 +54,8 @@
<true/>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app optionally uses your location to center the map on your current position and provide proximity alerts for nearby surveillance devices. These features are entirely optional.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app optionally uses your location in the background so proximity alerts can warn you about nearby surveillance devices while the app is not on screen. This feature is entirely optional.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app optionally uses your location to show nearby cameras by centering the map on your location.</string>
<key>UIApplicationSceneManifest</key>
@@ -68,6 +81,16 @@
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<!-- Required for proximity alerts. Without the "location" background mode
iOS suspends the app the moment it leaves the screen, the CoreLocation
stream stops delivering, and no alert can ever fire while backgrounded.
Only armed at runtime: GpsController sets
allowBackgroundLocationUpdates on the stream solely while the user has
proximity alerts turned on. -->
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
+77 -2
View File
@@ -64,6 +64,12 @@ class AppState extends ChangeNotifier {
VoidCallback? _tutorialCompletionCallback; // Callback when tutorial is completed
Timer? _messageCheckTimer;
// Node ID to auto-focus (open the details sheet for) after a submit/edit/delete
// completes, when kAutoOpenNodeSheetAfterSubmit is enabled. Consumed (read once
// and cleared) by HomeScreen after picking it up.
int? _pendingFocusNodeId;
AppState() {
instance = this;
_authState = AuthState();
@@ -157,6 +163,10 @@ class AppState extends ChangeNotifier {
UploadMode get uploadMode => _settingsState.uploadMode;
FollowMeMode get followMeMode => _settingsState.followMeMode;
bool get keepScreenAwake => _settingsState.keepScreenAwake;
bool get hideZoomControls => _settingsState.hideZoomControls;
bool get offlineFeaturesEnabled => _settingsState.offlineFeaturesEnabled;
bool get proximityAlertsEnabled => _settingsState.proximityAlertsEnabled;
int get proximityAlertDistance => _settingsState.proximityAlertDistance;
@@ -166,6 +176,8 @@ class AppState extends ChangeNotifier {
// Messages state
int? get unreadMessageCount => _messagesState.unreadCount;
bool get hasUnreadMessages => _messagesState.hasUnreadMessages;
bool get hasUnreadChangesetComments => _messagesState.hasUnreadChangesetComments;
bool get hasUnreadNotifications => _messagesState.hasUnreadNotifications;
bool get isCheckingMessages => _messagesState.isChecking;
// Tile provider state
@@ -178,6 +190,13 @@ class AppState extends ChangeNotifier {
int get pendingCount => _uploadQueueState.pendingCount;
List<PendingUpload> get pendingUploads => _uploadQueueState.pendingUploads;
/// True if any queue item currently has an open changeset that hasn't
/// been closed yet (creating changeset, uploading node, or closing
/// changeset). Used to gate enabling offline mode / pausing the upload
/// queue so in-flight submissions can finish first.
bool get hasInFlightUploads => pendingUploads.any((u) => u.isActivelyProcessing);
// Suspected location state
SuspectedLocation? get selectedSuspectedLocation => _suspectedLocationState.selectedLocation;
bool get suspectedLocationsEnabled => _suspectedLocationState.isEnabled;
@@ -314,6 +333,7 @@ class AppState extends ChangeNotifier {
final accessToken = await _authState.getAccessToken();
await _messagesState.checkMessages(
accessToken: accessToken,
username: isLoggedIn ? username : null,
uploadMode: uploadMode,
forceRefresh: forceRefresh,
);
@@ -323,10 +343,24 @@ class AppState extends ChangeNotifier {
return _messagesState.getMessagesUrl(uploadMode);
}
/// URL of the specific changeset with unread comments, on OSM's website,
/// or null if there are no unread changeset comments.
String? getUnreadChangesetUrl() {
return _messagesState.getUnreadChangesetUrl(uploadMode);
}
void clearMessages() {
_messagesState.clearMessages();
}
/// Mark changeset comments as read (called when user views the changeset on OSM)
Future<void> markChangesetCommentsRead() async {
await _messagesState.markChangesetCommentsRead(
username: isLoggedIn ? username : null,
uploadMode: uploadMode,
);
}
/// Check if the current OAuth token has required scopes for message notifications
/// Returns true if re-authentication is needed
Future<bool> needsReauthForMessages() async {
@@ -580,24 +614,44 @@ class AppState extends ChangeNotifier {
void commitSession() {
final session = _sessionState.commitSession();
if (session != null) {
_uploadQueueState.addFromSession(session, uploadMode: uploadMode);
final upload = _uploadQueueState.addFromSession(session, uploadMode: uploadMode);
_startUploader();
if (kAutoOpenNodeSheetAfterSubmit && upload.tempNodeId != null) {
_pendingFocusNodeId = upload.tempNodeId;
}
}
}
void commitEditSession() {
final session = _sessionState.commitEditSession();
if (session != null) {
_uploadQueueState.addFromEditSession(session, uploadMode: uploadMode);
final upload = _uploadQueueState.addFromEditSession(session, uploadMode: uploadMode);
_startUploader();
if (kAutoOpenNodeSheetAfterSubmit && upload.tempNodeId != null) {
_pendingFocusNodeId = upload.tempNodeId;
}
}
}
void deleteNode(OsmNode node, {String? changesetComment}) {
_uploadQueueState.addFromNodeDeletion(node, uploadMode: uploadMode, changesetComment: changesetComment);
_startUploader();
if (kAutoOpenNodeSheetAfterSubmit) {
_pendingFocusNodeId = node.id;
}
}
/// Consume (read once and clear) the node ID pending auto-focus, if any.
/// Used by HomeScreen to reopen the node details sheet right after a
/// submit/edit/delete completes, when [kAutoOpenNodeSheetAfterSubmit] is
/// enabled. Returns null if no focus is pending.
int? consumePendingFocusNodeId() {
final id = _pendingFocusNodeId;
_pendingFocusNodeId = null;
return id;
}
// ---------- Search Methods ----------
Future<void> search(String query) async {
await _searchState.search(query);
@@ -685,6 +739,27 @@ class AppState extends ChangeNotifier {
await _settingsState.setKeepScreenAwake(enabled);
}
Future<void> setHideZoomControls(bool enabled) async {
await _settingsState.setHideZoomControls(enabled);
}
/// Set the master "offline features enabled" toggle. When disabling,
/// also forces offlineMode off (if it was on) and cancels any active
/// area downloads, so we never end up "in offline mode" with the
/// feature disabled. Does NOT delete existing offline area data — that
/// is a separate, explicit user choice handled by the UI.
Future<void> setOfflineFeaturesEnabled(bool enabled) async {
await _settingsState.setOfflineFeaturesEnabled(enabled);
if (!enabled) {
if (offlineMode) {
await setOfflineMode(false);
}
await OfflineAreaService().cancelActiveDownloads();
}
}
Future<void> setPauseQueueProcessing(bool enabled) async {
await _settingsState.setPauseQueueProcessing(enabled);
if (!enabled) {
+15 -8
View File
@@ -64,6 +64,13 @@ const Duration kChangesetCloseMaxRetryDelay = Duration(minutes: 5); // Cap at 5
const Duration kChangesetAutoCloseTimeout = Duration(minutes: 59); // Give up and trust OSM auto-close
const double kChangesetCloseBackoffMultiplier = 2.0;
// How long to keep the "Submission Complete" confirmation visible in the
// in-flight upload wait dialog (shown when the user enables offline mode or
// pauses the upload queue while a submission is actively in progress) before
// automatically dismissing and applying the requested setting change.
const Duration kInFlightUploadCompleteDisplayDuration = Duration(seconds: 2);
// Overpass API configuration
const Duration kOverpassQueryTimeout = Duration(seconds: 45); // Timeout for Overpass API queries (was 25s hardcoded)
@@ -82,6 +89,9 @@ const bool kEnableNodeEdits = true; // Set to false to temporarily disable node
// Node extraction features - set to false to hide extract functionality for constrained nodes
const bool kEnableNodeExtraction = false; // Set to true to enable extract from way/relation feature (WIP)
// Auto-open tags sheet after add/edit/delete, so the user can watch upload status update live.
const bool kAutoOpenNodeSheetAfterSubmit = false; // Set to true to enable auto-focus behavior
// Profile FOV features - set to false to restrict profiles to 360° FOV only
const bool kEnableNon360FOVs = false; // Set to true to allow custom FOV values in profiles
@@ -99,13 +109,10 @@ const Duration kMarkerTapTimeout = Duration(milliseconds: 250);
const Duration kMapLongPressTimeout = Duration(milliseconds: 600); // Duration to trigger "add node here" on empty map area
const Duration kDebounceCameraRefresh = Duration(milliseconds: 500);
// Pre-fetch area configuration
const double kPreFetchAreaExpansionMultiplier = 3.0; // Expand visible bounds by this factor for pre-fetching
const double kNodeRenderingBoundsExpansion = 1.3; // Expand visible bounds by this factor for node rendering to prevent edge blinking
const double kRouteProximityThresholdMeters = 500.0; // Distance threshold for determining if user is near route when resuming navigation
const double kResumeNavigationZoomLevel = 16.0; // Zoom level when resuming navigation
const int kPreFetchZoomLevel = 10; // Always pre-fetch at this zoom level for consistent area sizes
const int kMaxPreFetchSplitDepth = 3; // Maximum recursive splits when hitting Overpass node limit
// Data refresh configuration
const int kDataRefreshIntervalSeconds = 60; // Refresh cached data after this many seconds
@@ -165,11 +172,11 @@ const int kAbsoluteMaxTileCount = 50000;
const int kAbsoluteMaxZoom = 23;
// Node icon configuration
const double kNodeIconDiameter = 18.0;
const double _kNodeRingThicknessBase = 2.5;
const double kNodeDotOpacity = 0.3; // Opacity for the grey dot interior
const double kNodeIconDiameter = 17.0;
const double _kNodeRingThicknessBase = 2.6;
const double kNodeDotOpacity = 0.28; // Opacity for the grey dot interior
const Color kNodeRingColorReal = Color(0xFF3036F0); // Real nodes from OSM - blue
const Color kNodeRingColorMock = Color(0xD0FFFFFF); // Add node mock point - white
const Color kNodeRingColorMock = Color(0xE044BB55); // Add node mock point - white
const Color kNodeRingColorPending = Color(0xD09C27B0); // Submitted/pending nodes - purple
const Color kNodeRingColorEditing = Color(0xD0FF9800); // Node being edited - orange
const Color kNodeRingColorPendingEdit = Color(0xD0757575); // Original node with pending edit - grey
+49 -7
View File
@@ -75,12 +75,20 @@
"advancedSettingsSubtitle": "Leistungs-, Warnungs- und Kachelanbieter-Einstellungen",
"proximityAlerts": "Näherungswarnungen",
"keepScreenAwake": "Bildschirm Aktiv Lassen",
"networkStatusIndicator": "Netzwerkstatus-Anzeige"
"networkStatusIndicator": "Netzwerkstatus-Anzeige",
"hideZoomControls": "Zoom-Steuerung Ausblenden",
"enableOfflineFeatures": "Offline-Funktionen Aktivieren",
"enableOfflineFeaturesTitle": "Offline-Funktionen aktivieren",
"enableOfflineFeaturesSubtitle": "Herunterladen und Nutzen von Offline-Kartenbereichen erlauben. Wenn deaktiviert, sind Offline-Modus und heruntergeladene Bereiche nicht verfügbar."
},
"keepScreenAwake": {
"title": "Bildschirm während der App-Nutzung aktiv lassen",
"subtitle": "Verhindert, dass sich der Bildschirm während der Nutzung der App automatisch ausschaltet"
},
"hideZoomControls": {
"title": "Zoom-Steuerung ausblenden",
"subtitle": "Blendet die +/- Zoom-Schaltflächen und die Zoomstufen-Anzeige aus. Sie können weiterhin mit Fingergesten zoomen."
},
"proximityAlerts": {
"getNotified": "Benachrichtigung erhalten beim Annähern an Überwachungsgeräte",
"batteryUsage": "Verbraucht zusätzlich Batterie für kontinuierliche Standortüberwachung",
@@ -91,7 +99,13 @@
"enableNotifications": "Benachrichtigungen Aktivieren",
"checkingPermissions": "Berechtigungen prüfen...",
"alertDistance": "Warnentfernung: ",
"rangeInfo": "Bereich: {}-{} {} (Standard: {})"
"rangeInfo": "Bereich: {}-{} {} (Standard: {})",
"backgroundServiceTitle": "Näherungswarnungen aktiv",
"backgroundServiceText": "Sucht nach Überwachungsgeräten in der Nähe",
"backgroundServiceChannel": "Überwachung von Näherungswarnungen",
"openSettings": "Einstellungen öffnen",
"blockedTitle": "Benachrichtigungen sind blockiert",
"blockedMessage": "Benachrichtigungen für DeFlock sind deaktiviert. Aktiviere sie in den Systemeinstellungen, um Näherungswarnungen zu erhalten."
},
"node": {
"title": "Knoten #{}",
@@ -101,8 +115,23 @@
"deleteQueuedForUpload": "Knoten-Löschung zum Upload eingereiht",
"confirmDeleteTitle": "Knoten löschen",
"confirmDeleteMessage": "Sind Sie sicher, dass Sie Knoten #{} löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.",
"deleteReasonLabel": "Grund für Löschung (Optional)",
"deleteReasonHint": "z.B. Gerät entfernt, falsche Position, Duplikat..."
"deleteReasonLabel": "Grund für Löschung",
"deleteReasonSelectHint": "Auswählen...",
"deleteReasonDeviceRemoved": "Gerät entfernt",
"deleteReasonDuplicateNode": "Doppelter Knoten",
"deleteReasonMisidentifiedInfra": "Falsch identifizierte Infrastruktur",
"deleteReasonSpamVandalism": "Spam/Vandalismus",
"deleteReasonCustom": "Benutzerdefiniert..",
"deleteReasonHint": "Bitte Grund beschreiben...",
"mustBeLoggedInToDelete": "Sie müssen mit einem OpenStreetMap-Konto angemeldet sein, um Kartendaten beizutragen.",
"uploadPending": "Ausstehender Upload",
"uploadCreatingChangeset": "Changeset wird erstellt...",
"uploadUploading": "Wird hochgeladen...",
"uploadClosingChangeset": "Changeset wird geschlossen...",
"uploadError": "Upload fehlgeschlagen",
"uploadComplete": "Upload abgeschlossen",
"viewInQueue": "In Warteschlange anzeigen",
"deletedSuccessfully": "Dieser Knoten wurde erfolgreich von OpenStreetMap gelöscht."
},
"addNode": {
"profile": "Profil",
@@ -207,7 +236,12 @@
"reauthExplanation": "Sie müssen Ihre Authentifizierung aktualisieren, um OSM-Nachrichtenbenachrichtigungen über die App zu erhalten.",
"reauthBenefit": "Dies ermöglicht Benachrichtigungspunkte, wenn Sie ungelesene Nachrichten auf OpenStreetMap haben.",
"reauthNow": "Jetzt machen",
"reauthLater": "Später"
"newChangesetComments": "Neuer Changeset-Kommentar",
"newChangesetCommentsSubtitle": "Jemand hat einen oder mehrere Ihrer Changesets kommentiert",
"reauthLater": "Später",
"unreadNotificationsTitle": "Sie haben ungelesene Benachrichtigungen",
"unreadNotificationsMessage": "Sie haben ungelesene OSM-Nachrichten und/oder neue Kommentare zu Ihren Changesets.",
"unreadNotificationsView": "Jetzt ansehen"
},
"queue": {
"title": "Upload-Warteschlange",
@@ -242,7 +276,11 @@
"closingChangeset": " (Changeset schließen...)",
"processingPaused": "Warteschlangenverarbeitung pausiert",
"pausedDueToOffline": "Upload-Verarbeitung ist pausiert, da der Offline-Modus aktiviert ist.",
"pausedByUser": "Upload-Verarbeitung ist manuell pausiert."
"pausedByUser": "Upload-Verarbeitung ist manuell pausiert.",
"inFlightWaitTitle": "Übermittlung wird abgeschlossen",
"inFlightWaitMessage": "Eine Übermittlung läuft gerade und muss abgeschlossen werden, bevor diese Einstellung angewendet werden kann. Dies sollte nur einen Moment dauern.",
"inFlightCompleteTitle": "Übermittlung Abgeschlossen",
"inFlightCompleteMessage": "Ihre Übermittlung wurde erfolgreich abgeschlossen. Ihre Einstellung wird jetzt angewendet."
},
"tileProviders": {
"title": "Kachel-Anbieter",
@@ -389,7 +427,11 @@
"refreshNodesSubtitle": "Knotendaten für diesen Bereich erneut abrufen",
"startRefresh": "Aktualisierung starten",
"refreshStarted": "Aktualisierung gestartet!",
"refreshFailed": "Aktualisierung fehlgeschlagen: {}"
"refreshFailed": "Aktualisierung fehlgeschlagen: {}",
"disableConfirmTitle": "Vorhandene Offline-Bereichsdaten löschen?",
"disableConfirmMessage": "Sie haben bereits Offline-Bereichsdaten. Das Deaktivieren der Offline-Funktionen verhindert, dass die App diese verwendet. Möchten Sie diese Daten für den Fall behalten, dass Sie die Offline-Funktionen später wieder aktivieren, oder sie jetzt löschen, um Speicherplatz freizugeben?",
"keepData": "Daten Behalten",
"deleteData": "Daten Löschen"
},
"refineTagsSheet": {
"title": "Tags Verfeinern",
+50 -8
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Performance, alerts, and tile provider settings",
"proximityAlerts": "Proximity Alerts",
"networkStatusIndicator": "Network Status Indicator",
"keepScreenAwake": "Keep Screen Awake"
"keepScreenAwake": "Keep Screen Awake",
"hideZoomControls": "Hide Zoom Controls",
"enableOfflineFeatures": "Enable Offline Features",
"enableOfflineFeaturesTitle": "Enable offline features",
"enableOfflineFeaturesSubtitle": "Allow downloading and using offline map areas. When disabled, offline mode and downloaded areas are unavailable."
},
"keepScreenAwake": {
"title": "Keep screen awake while using app",
"subtitle": "Prevents the screen from turning off automatically while using the app"
},
"hideZoomControls": {
"title": "Hide zoom controls",
"subtitle": "Hide the +/- zoom buttons and zoom level indicator. You can still zoom with pinch gestures."
},
"proximityAlerts": {
"getNotified": "Get notified when approaching surveillance devices",
"batteryUsage": "Uses extra battery for continuous location monitoring",
@@ -128,7 +136,13 @@
"enableNotifications": "Enable Notifications",
"checkingPermissions": "Checking permissions...",
"alertDistance": "Alert distance: ",
"rangeInfo": "Range: {}-{} {} (default: {})"
"rangeInfo": "Range: {}-{} {} (default: {})",
"backgroundServiceTitle": "Proximity alerts active",
"backgroundServiceText": "Watching for nearby surveillance devices",
"backgroundServiceChannel": "Proximity Alert Monitoring",
"openSettings": "Open Settings",
"blockedTitle": "Notifications are blocked",
"blockedMessage": "Notifications are turned off for DeFlock. Enable them in your system settings to receive proximity alerts."
},
"node": {
"title": "Node #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "Node deletion queued for upload",
"confirmDeleteTitle": "Delete Node",
"confirmDeleteMessage": "Are you sure you want to delete node #{}? This action cannot be undone.",
"deleteReasonLabel": "Reason for Deletion (Optional)",
"deleteReasonHint": "e.g., device removed, incorrect location, duplicate..."
"deleteReasonLabel": "Reason for Deletion",
"deleteReasonSelectHint": "Select...",
"deleteReasonDeviceRemoved": "Device removed",
"deleteReasonDuplicateNode": "Duplicate node",
"deleteReasonMisidentifiedInfra": "Misidentified infra",
"deleteReasonSpamVandalism": "Spam/vandalism",
"deleteReasonCustom": "Custom..",
"deleteReasonHint": "Please describe the reason...",
"mustBeLoggedInToDelete": "You must be logged in with an OpenStreetMap account to contribute map data.",
"uploadPending": "Pending upload",
"uploadCreatingChangeset": "Creating changeset...",
"uploadUploading": "Uploading...",
"uploadClosingChangeset": "Closing changeset...",
"uploadError": "Upload failed",
"uploadComplete": "Upload complete",
"viewInQueue": "View in Queue",
"deletedSuccessfully": "This node was successfully deleted from OpenStreetMap."
},
"addNode": {
"profile": "Profile",
@@ -240,11 +269,16 @@
"viewMessages": "View Messages on OSM",
"unreadMessagesCount": "You have {} unread messages",
"noUnreadMessages": "No unread messages",
"newChangesetComments": "New Changeset Comment",
"newChangesetCommentsSubtitle": "Someone commented on one or more of your changesets",
"reauthRequired": "Refresh Authentication",
"reauthExplanation": "You must refresh your authentication to receive OSM message notifications through the app.",
"reauthBenefit": "This will enable notification dots when you have unread messages on OpenStreetMap.",
"reauthNow": "Do That Now",
"reauthLater": "Later"
"reauthLater": "Later",
"unreadNotificationsTitle": "You Have Unread Notifications",
"unreadNotificationsMessage": "You have unread OSM messages and/or new comments on your changesets.",
"unreadNotificationsView": "View Now"
},
"queue": {
"title": "Upload Queue",
@@ -279,7 +313,11 @@
"closingChangeset": " (Closing changeset...)",
"processingPaused": "Queue Processing Paused",
"pausedDueToOffline": "Upload processing is paused because offline mode is enabled.",
"pausedByUser": "Upload processing is manually paused."
"pausedByUser": "Upload processing is manually paused.",
"inFlightWaitTitle": "Finishing Submission",
"inFlightWaitMessage": "A submission is currently in progress and needs to finish before this setting can be applied. This should only take a moment.",
"inFlightCompleteTitle": "Submission Complete",
"inFlightCompleteMessage": "Your submission finished successfully. Applying your setting now."
},
"tileProviders": {
"title": "Tile Providers",
@@ -289,7 +327,7 @@
"needsApiKey": "Needs API key",
"editProvider": "Edit Provider",
"addProvider": "Add Provider",
"deleteProvider": "Delete Provider",
"deleteProvider": "Delete Provider",
"deleteProviderConfirm": "Are you sure you want to delete \"{}\"?",
"clearCaches": "Clear Caches",
"clearCachesConfirm": "Clear all tile caches for \"{}\"? This will free up storage space but tiles will need to be downloaded again when viewing those areas.",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Re-fetch node data for this area",
"startRefresh": "Start Refresh",
"refreshStarted": "Refresh started!",
"refreshFailed": "Refresh failed: {}"
"refreshFailed": "Refresh failed: {}",
"disableConfirmTitle": "Delete Existing Offline Area Data?",
"disableConfirmMessage": "You have existing offline area data. Disabling offline features will stop the app from using it. Would you like to keep this data on disk in case you re-enable offline features later, or delete it now to free up storage space?",
"keepData": "Keep Data",
"deleteData": "Delete Data"
},
"refineTagsSheet": {
"title": "Refine Tags",
+49 -7
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Configuración de rendimiento, alertas y proveedores de teselas",
"proximityAlerts": "Alertas de Proximidad",
"keepScreenAwake": "Mantener la Pantalla Encendida",
"networkStatusIndicator": "Indicador de Estado de Red"
"networkStatusIndicator": "Indicador de Estado de Red",
"hideZoomControls": "Ocultar Controles de Zoom",
"enableOfflineFeatures": "Activar Funciones sin Conexión",
"enableOfflineFeaturesTitle": "Activar funciones sin conexión",
"enableOfflineFeaturesSubtitle": "Permitir descargar y usar áreas de mapa sin conexión. Si se desactiva, el modo sin conexión y las áreas descargadas no estarán disponibles."
},
"keepScreenAwake": {
"title": "Mantener la pantalla encendida mientras se usa la app",
"subtitle": "Evita que la pantalla se apague automáticamente mientras se usa la app"
},
"hideZoomControls": {
"title": "Ocultar controles de zoom",
"subtitle": "Oculta los botones de zoom +/- y el indicador de nivel de zoom. Aún puedes hacer zoom con gestos de pellizco."
},
"proximityAlerts": {
"getNotified": "Recibe notificaciones al acercarte a dispositivos de vigilancia",
"batteryUsage": "Usa batería extra para monitoreo continuo de ubicación",
@@ -128,7 +136,13 @@
"enableNotifications": "Habilitar Notificaciones",
"checkingPermissions": "Verificando permisos...",
"alertDistance": "Distancia de alerta: ",
"rangeInfo": "Rango: {}-{} {} (predeterminado: {})"
"rangeInfo": "Rango: {}-{} {} (predeterminado: {})",
"backgroundServiceTitle": "Alertas de proximidad activas",
"backgroundServiceText": "Buscando dispositivos de vigilancia cercanos",
"backgroundServiceChannel": "Monitoreo de alertas de proximidad",
"openSettings": "Abrir ajustes",
"blockedTitle": "Las notificaciones están bloqueadas",
"blockedMessage": "Las notificaciones están desactivadas para DeFlock. Actívalas en los ajustes del sistema para recibir alertas de proximidad."
},
"node": {
"title": "Nodo #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "Eliminación de nodo en cola para subir",
"confirmDeleteTitle": "Eliminar Nodo",
"confirmDeleteMessage": "¿Estás seguro de que quieres eliminar el nodo #{}? Esta acción no se puede deshacer.",
"deleteReasonLabel": "Razón para Eliminación (Opcional)",
"deleteReasonHint": "ej. dispositivo removido, ubicación incorrecta, duplicado..."
"deleteReasonLabel": "Razón para Eliminación",
"deleteReasonSelectHint": "Seleccionar...",
"deleteReasonDeviceRemoved": "Dispositivo removido",
"deleteReasonDuplicateNode": "Nodo duplicado",
"deleteReasonMisidentifiedInfra": "Infraestructura mal identificada",
"deleteReasonSpamVandalism": "Spam/vandalismo",
"deleteReasonCustom": "Personalizado..",
"deleteReasonHint": "Por favor describa la razón...",
"mustBeLoggedInToDelete": "Debes iniciar sesión con una cuenta de OpenStreetMap para contribuir con datos del mapa.",
"uploadPending": "Subida pendiente",
"uploadCreatingChangeset": "Creando changeset...",
"uploadUploading": "Subiendo...",
"uploadClosingChangeset": "Cerrando changeset...",
"uploadError": "Error al subir",
"uploadComplete": "Subida completada",
"viewInQueue": "Ver en la Cola",
"deletedSuccessfully": "Este nodo fue eliminado con éxito de OpenStreetMap."
},
"addNode": {
"profile": "Perfil",
@@ -244,7 +273,12 @@
"reauthExplanation": "Debes actualizar tu autenticación para recibir notificaciones de mensajes OSM a través de la aplicación.",
"reauthBenefit": "Esto habilitará puntos de notificación cuando tengas mensajes sin leer en OpenStreetMap.",
"reauthNow": "Hazlo Ahora",
"reauthLater": "Más Tarde"
"newChangesetComments": "Nuevo Comentario en Changeset",
"newChangesetCommentsSubtitle": "Alguien comentó en uno o más de tus changesets",
"reauthLater": "Más Tarde",
"unreadNotificationsTitle": "Tienes Notificaciones Sin Leer",
"unreadNotificationsMessage": "Tienes mensajes de OSM sin leer y/o nuevos comentarios en tus changesets.",
"unreadNotificationsView": "Ver Ahora"
},
"queue": {
"title": "Cola de Subida",
@@ -279,7 +313,11 @@
"closingChangeset": " (Cerrando changeset...)",
"processingPaused": "Procesamiento de Cola Pausado",
"pausedDueToOffline": "El procesamiento de subida está pausado porque el modo sin conexión está habilitado.",
"pausedByUser": "El procesamiento de subida está pausado manualmente."
"pausedByUser": "El procesamiento de subida está pausado manualmente.",
"inFlightWaitTitle": "Finalizando Envío",
"inFlightWaitMessage": "Actualmente hay un envío en curso que debe finalizar antes de que se pueda aplicar esta configuración. Esto solo debería tomar un momento.",
"inFlightCompleteTitle": "Envío Completado",
"inFlightCompleteMessage": "Su envío finalizó exitosamente. Aplicando su configuración ahora."
},
"tileProviders": {
"title": "Proveedores de Tiles",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Volver a obtener datos de nodos para esta área",
"startRefresh": "Iniciar Actualización",
"refreshStarted": "¡Actualización iniciada!",
"refreshFailed": "Actualización falló: {}"
"refreshFailed": "Actualización falló: {}",
"disableConfirmTitle": "¿Eliminar Datos de Áreas sin Conexión Existentes?",
"disableConfirmMessage": "Ya tiene datos de áreas sin conexión existentes. Desactivar las funciones sin conexión evitará que la app los use. ¿Desea conservar estos datos en el dispositivo por si reactiva las funciones sin conexión más tarde, o eliminarlos ahora para liberar espacio de almacenamiento?",
"keepData": "Conservar Datos",
"deleteData": "Eliminar Datos"
},
"refineTagsSheet": {
"title": "Refinar Etiquetas",
+49 -7
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Paramètres de performance, alertes et fournisseurs de tuiles",
"proximityAlerts": "Alertes de Proximité",
"keepScreenAwake": "Maintenir l'écran Allumé",
"networkStatusIndicator": "Indicateur de Statut Réseau"
"networkStatusIndicator": "Indicateur de Statut Réseau",
"hideZoomControls": "Masquer les Contrôles de Zoom",
"enableOfflineFeatures": "Activer les Fonctionnalités Hors Ligne",
"enableOfflineFeaturesTitle": "Activer les fonctionnalités hors ligne",
"enableOfflineFeaturesSubtitle": "Autoriser le téléchargement et l'utilisation de zones de carte hors ligne. Si désactivé, le mode hors ligne et les zones téléchargées ne seront pas disponibles."
},
"keepScreenAwake": {
"title": "Maintenir l'écran allumé lors de l'utilisation de l'application",
"subtitle": "Empêche l'écran de s'éteindre automatiquement pendant l'utilisation de l'application"
},
"hideZoomControls": {
"title": "Masquer les contrôles de zoom",
"subtitle": "Masque les boutons de zoom +/- et l'indicateur de niveau de zoom. Vous pouvez toujours zoomer avec des gestes de pincement."
},
"proximityAlerts": {
"getNotified": "Recevoir des notifications en s'approchant de dispositifs de surveillance",
"batteryUsage": "Utilise de la batterie supplémentaire pour la surveillance continue de la localisation",
@@ -128,7 +136,13 @@
"enableNotifications": "Activer les Notifications",
"checkingPermissions": "Vérification des autorisations...",
"alertDistance": "Distance d'alerte : ",
"rangeInfo": "Plage : {}-{} {} (par défaut : {})"
"rangeInfo": "Plage : {}-{} {} (par défaut : {})",
"backgroundServiceTitle": "Alertes de proximité actives",
"backgroundServiceText": "Recherche d'appareils de surveillance à proximité",
"backgroundServiceChannel": "Surveillance des alertes de proximité",
"openSettings": "Ouvrir les réglages",
"blockedTitle": "Les notifications sont bloquées",
"blockedMessage": "Les notifications sont désactivées pour DeFlock. Activez-les dans les réglages du système pour recevoir les alertes de proximité."
},
"node": {
"title": "Nœud #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "Suppression de nœud mise en file pour envoi",
"confirmDeleteTitle": "Supprimer le Nœud",
"confirmDeleteMessage": "Êtes-vous sûr de vouloir supprimer le nœud #{} ? Cette action ne peut pas être annulée.",
"deleteReasonLabel": "Raison de Suppression (Optionnel)",
"deleteReasonHint": "ex. appareil retiré, emplacement incorrect, doublon..."
"deleteReasonLabel": "Raison de Suppression",
"deleteReasonSelectHint": "Sélectionner...",
"deleteReasonDeviceRemoved": "Appareil retiré",
"deleteReasonDuplicateNode": "Nœud dupliqué",
"deleteReasonMisidentifiedInfra": "Infrastructure mal identifiée",
"deleteReasonSpamVandalism": "Spam/vandalisme",
"deleteReasonCustom": "Personnalisé..",
"deleteReasonHint": "Veuillez décrire la raison...",
"mustBeLoggedInToDelete": "Vous devez être connecté avec un compte OpenStreetMap pour contribuer aux données cartographiques.",
"uploadPending": "Téléchargement en attente",
"uploadCreatingChangeset": "Création du changeset...",
"uploadUploading": "Téléchargement en cours...",
"uploadClosingChangeset": "Fermeture du changeset...",
"uploadError": "Échec du téléchargement",
"uploadComplete": "Téléchargement terminé",
"viewInQueue": "Voir dans la File d'Attente",
"deletedSuccessfully": "Ce nœud a été supprimé avec succès d'OpenStreetMap."
},
"addNode": {
"profile": "Profil",
@@ -244,7 +273,12 @@
"reauthExplanation": "Vous devez actualiser votre authentification pour recevoir des notifications de messages OSM via l'application.",
"reauthBenefit": "Cela activera les points de notification lorsque vous avez des messages non lus sur OpenStreetMap.",
"reauthNow": "Le Faire Maintenant",
"reauthLater": "Plus Tard"
"newChangesetComments": "Nouveau Commentaire de Changeset",
"newChangesetCommentsSubtitle": "Quelqu'un a commenté un ou plusieurs de vos changesets",
"reauthLater": "Plus Tard",
"unreadNotificationsTitle": "Vous Avez des Notifications Non Lues",
"unreadNotificationsMessage": "Vous avez des messages OSM non lus et/ou de nouveaux commentaires sur vos changesets.",
"unreadNotificationsView": "Voir Maintenant"
},
"queue": {
"title": "File de Téléchargement",
@@ -279,7 +313,11 @@
"closingChangeset": " (Fermeture du changeset...)",
"processingPaused": "Traitement de la File d'Attente Interrompu",
"pausedDueToOffline": "Le traitement des téléversements est interrompu car le mode hors ligne est activé.",
"pausedByUser": "Le traitement des téléversements est interrompu manuellement."
"pausedByUser": "Le traitement des téléversements est interrompu manuellement.",
"inFlightWaitTitle": "Finalisation de la Soumission",
"inFlightWaitMessage": "Une soumission est actuellement en cours et doit se terminer avant que ce paramètre puisse être appliqué. Cela ne devrait prendre qu'un instant.",
"inFlightCompleteTitle": "Soumission Terminée",
"inFlightCompleteMessage": "Votre soumission s'est terminée avec succès. Application de votre paramètre maintenant."
},
"tileProviders": {
"title": "Fournisseurs de Tuiles",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Récupérer à nouveau les données de nœuds pour cette zone",
"startRefresh": "Démarrer l'Actualisation",
"refreshStarted": "Actualisation démarrée !",
"refreshFailed": "Actualisation échouée : {}"
"refreshFailed": "Actualisation échouée : {}",
"disableConfirmTitle": "Supprimer les Données de Zones Hors Ligne Existantes ?",
"disableConfirmMessage": "Vous avez déjà des données de zones hors ligne. Désactiver les fonctionnalités hors ligne empêchera l'application de les utiliser. Souhaitez-vous conserver ces données sur l'appareil au cas où vous réactiveriez les fonctionnalités hors ligne plus tard, ou les supprimer maintenant pour libérer de l'espace de stockage ?",
"keepData": "Conserver les Données",
"deleteData": "Supprimer les Données"
},
"refineTagsSheet": {
"title": "Affiner les Étiquettes",
+49 -7
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Impostazioni di prestazioni, avvisi e fornitori di tessere",
"proximityAlerts": "Avvisi di Prossimità",
"keepScreenAwake": "Mantieni lo Schermo Attivo",
"networkStatusIndicator": "Indicatore di Stato di Rete"
"networkStatusIndicator": "Indicatore di Stato di Rete",
"hideZoomControls": "Nascondi Controlli Zoom",
"enableOfflineFeatures": "Abilita Funzionalità Offline",
"enableOfflineFeaturesTitle": "Abilita funzionalità offline",
"enableOfflineFeaturesSubtitle": "Consenti il download e l'uso di aree mappa offline. Se disabilitato, la modalità offline e le aree scaricate non saranno disponibili."
},
"keepScreenAwake": {
"title": "Mantieni lo schermo attivo durante l'utilizzo dell'app",
"subtitle": "Impedisce allo schermo di spegnersi automaticamente durante l'utilizzo dell'app"
},
"hideZoomControls": {
"title": "Nascondi i controlli dello zoom",
"subtitle": "Nasconde i pulsanti di zoom +/- e l'indicatore del livello di zoom. Puoi ancora usare i gesti di pizzico per lo zoom."
},
"proximityAlerts": {
"getNotified": "Ricevi notifiche quando ti avvicini a dispositivi di sorveglianza",
"batteryUsage": "Utilizza batteria extra per il monitoraggio continuo della posizione",
@@ -128,7 +136,13 @@
"enableNotifications": "Abilita Notifiche",
"checkingPermissions": "Controllo autorizzazioni...",
"alertDistance": "Distanza di avviso: ",
"rangeInfo": "Intervallo: {}-{} {} (predefinito: {})"
"rangeInfo": "Intervallo: {}-{} {} (predefinito: {})",
"backgroundServiceTitle": "Avvisi di prossimità attivi",
"backgroundServiceText": "Ricerca di dispositivi di sorveglianza nelle vicinanze",
"backgroundServiceChannel": "Monitoraggio avvisi di prossimità",
"openSettings": "Apri impostazioni",
"blockedTitle": "Le notifiche sono bloccate",
"blockedMessage": "Le notifiche sono disattivate per DeFlock. Attivale nelle impostazioni di sistema per ricevere gli avvisi di prossimità."
},
"node": {
"title": "Nodo #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "Eliminazione nodo in coda per il caricamento",
"confirmDeleteTitle": "Elimina Nodo",
"confirmDeleteMessage": "Sei sicuro di voler eliminare il nodo #{}? Questa azione non può essere annullata.",
"deleteReasonLabel": "Motivo per Eliminazione (Opzionale)",
"deleteReasonHint": "es. dispositivo rimosso, posizione errata, duplicato..."
"deleteReasonLabel": "Motivo per Eliminazione",
"deleteReasonSelectHint": "Seleziona...",
"deleteReasonDeviceRemoved": "Dispositivo rimosso",
"deleteReasonDuplicateNode": "Nodo duplicato",
"deleteReasonMisidentifiedInfra": "Infrastruttura identificata erroneamente",
"deleteReasonSpamVandalism": "Spam/vandalismo",
"deleteReasonCustom": "Personalizzato..",
"deleteReasonHint": "Descrivi il motivo...",
"mustBeLoggedInToDelete": "Devi aver effettuato l'accesso con un account OpenStreetMap per contribuire ai dati della mappa.",
"uploadPending": "Caricamento in sospeso",
"uploadCreatingChangeset": "Creazione changeset...",
"uploadUploading": "Caricamento...",
"uploadClosingChangeset": "Chiusura changeset...",
"uploadError": "Caricamento fallito",
"uploadComplete": "Caricamento completato",
"viewInQueue": "Visualizza in Coda",
"deletedSuccessfully": "Questo nodo è stato eliminato con successo da OpenStreetMap."
},
"addNode": {
"profile": "Profilo",
@@ -244,7 +273,12 @@
"reauthExplanation": "Devi aggiornare la tua autenticazione per ricevere notifiche di messaggi OSM tramite l'app.",
"reauthBenefit": "Questo abiliterà i punti di notifica quando hai messaggi non letti su OpenStreetMap.",
"reauthNow": "Fallo Ora",
"reauthLater": "Più Tardi"
"newChangesetComments": "Nuovo Commento al Changeset",
"newChangesetCommentsSubtitle": "Qualcuno ha commentato uno o più dei tuoi changeset",
"reauthLater": "Più Tardi",
"unreadNotificationsTitle": "Hai Notifiche Non Lette",
"unreadNotificationsMessage": "Hai messaggi OSM non letti e/o nuovi commenti sui tuoi changeset.",
"unreadNotificationsView": "Visualizza Ora"
},
"queue": {
"title": "Coda di Upload",
@@ -279,7 +313,11 @@
"closingChangeset": " (Chiusura changeset...)",
"processingPaused": "Elaborazione Coda Sospesa",
"pausedDueToOffline": "L'elaborazione dei caricamenti è sospesa perché la modalità offline è abilitata.",
"pausedByUser": "L'elaborazione dei caricamenti è sospesa manualmente."
"pausedByUser": "L'elaborazione dei caricamenti è sospesa manualmente.",
"inFlightWaitTitle": "Completamento Invio",
"inFlightWaitMessage": "Un invio è attualmente in corso e deve terminare prima che questa impostazione possa essere applicata. Questo dovrebbe richiedere solo un momento.",
"inFlightCompleteTitle": "Invio Completato",
"inFlightCompleteMessage": "Il tuo invio è terminato con successo. Applicazione della tua impostazione in corso."
},
"tileProviders": {
"title": "Fornitori di Tile",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Ricarica i dati dei nodi per quest'area",
"startRefresh": "Avvia Aggiornamento",
"refreshStarted": "Aggiornamento avviato!",
"refreshFailed": "Aggiornamento fallito: {}"
"refreshFailed": "Aggiornamento fallito: {}",
"disableConfirmTitle": "Eliminare i Dati delle Aree Offline Esistenti?",
"disableConfirmMessage": "Hai già dati di aree offline esistenti. Disabilitare le funzionalità offline impedirà all'app di usarli. Vuoi conservare questi dati sul dispositivo nel caso in cui riattivi le funzionalità offline in seguito, oppure eliminarli ora per liberare spazio di archiviazione?",
"keepData": "Conserva Dati",
"deleteData": "Elimina Dati"
},
"refineTagsSheet": {
"title": "Affina Tag",
+50 -8
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Prestaties, waarschuwingen en tile provider instellingen",
"proximityAlerts": "Nabijheids Waarschuwingen",
"keepScreenAwake": "Scherm Actief Houden",
"networkStatusIndicator": "Netwerk Status Indicator"
"networkStatusIndicator": "Netwerk Status Indicator",
"hideZoomControls": "Zoomknoppen Verbergen",
"enableOfflineFeatures": "Offline Functies Inschakelen",
"enableOfflineFeaturesTitle": "Offline functies inschakelen",
"enableOfflineFeaturesSubtitle": "Sta het downloaden en gebruiken van offline kaartgebieden toe. Indien uitgeschakeld, zijn offline modus en gedownloade gebieden niet beschikbaar."
},
"keepScreenAwake": {
"title": "Houd het scherm actief tijdens het gebruik van de app",
"subtitle": "Voorkomt dat het scherm automatisch uitschakelt tijdens het gebruik van de app"
},
"hideZoomControls": {
"title": "Zoomknoppen verbergen",
"subtitle": "Verbergt de +/- zoomknoppen en de zoomniveau-indicator. U kunt nog steeds zoomen met knijpgebaren."
},
"proximityAlerts": {
"getNotified": "Krijg meldingen wanneer u surveillance apparaten nadert",
"batteryUsage": "Gebruikt extra batterij voor continue locatie monitoring",
@@ -128,7 +136,13 @@
"enableNotifications": "Schakel Meldingen In",
"checkingPermissions": "Toestemmingen controleren...",
"alertDistance": "Waarschuwingsafstand: ",
"rangeInfo": "Bereik: {}-{} {} (standaard: {})"
"rangeInfo": "Bereik: {}-{} {} (standaard: {})",
"backgroundServiceTitle": "Nabijheidswaarschuwingen actief",
"backgroundServiceText": "Zoekt naar bewakingsapparatuur in de buurt",
"backgroundServiceChannel": "Monitoring van nabijheidswaarschuwingen",
"openSettings": "Instellingen openen",
"blockedTitle": "Meldingen zijn geblokkeerd",
"blockedMessage": "Meldingen zijn uitgeschakeld voor DeFlock. Schakel ze in via je systeeminstellingen om nabijheidswaarschuwingen te ontvangen."
},
"node": {
"title": "Node #{}",
@@ -136,10 +150,25 @@
"queuedForUpload": "Node in wachtrij geplaatst voor upload",
"editQueuedForUpload": "Node bewerking in wachtrij geplaatst voor upload",
"deleteQueuedForUpload": "Node verwijdering in wachtrij geplaatst voor upload",
"confirmDeleteTitle": "Verwijder Node",
"confirmDeleteTitle": "Verwijder Node",
"confirmDeleteMessage": "Weet u zeker dat u node #{} wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.",
"deleteReasonLabel": "Reden voor Verwijdering (Optioneel)",
"deleteReasonHint": "bijv. apparaat verwijderd, onjuiste locatie, duplicaat..."
"deleteReasonLabel": "Reden voor Verwijdering",
"deleteReasonSelectHint": "Selecteer...",
"deleteReasonDeviceRemoved": "Apparaat verwijderd",
"deleteReasonDuplicateNode": "Dubbele node",
"deleteReasonMisidentifiedInfra": "Verkeerd geïdentificeerde infrastructuur",
"deleteReasonSpamVandalism": "Spam/vandalisme",
"deleteReasonCustom": "Aangepast..",
"deleteReasonHint": "Beschrijf de reden...",
"mustBeLoggedInToDelete": "U moet ingelogd zijn met een OpenStreetMap-account om kaartgegevens bij te dragen.",
"uploadPending": "Upload in behandeling",
"uploadCreatingChangeset": "Changeset maken...",
"uploadUploading": "Uploaden...",
"uploadClosingChangeset": "Changeset sluiten...",
"uploadError": "Upload mislukt",
"uploadComplete": "Upload voltooid",
"viewInQueue": "Bekijk in Wachtrij",
"deletedSuccessfully": "Deze node is succesvol verwijderd van OpenStreetMap."
},
"addNode": {
"profile": "Profiel",
@@ -244,7 +273,12 @@
"reauthExplanation": "U moet uw authenticatie verversen om OSM bericht meldingen te ontvangen via de app.",
"reauthBenefit": "Dit zal melding stippen inschakelen wanneer u ongelezen berichten heeft op OpenStreetMap.",
"reauthNow": "Doe Dat Nu",
"reauthLater": "Later"
"newChangesetComments": "Nieuwe Changeset-opmerking",
"newChangesetCommentsSubtitle": "Iemand heeft commentaar gegeven op een of meer van uw changesets",
"reauthLater": "Later",
"unreadNotificationsTitle": "U Heeft Ongelezen Meldingen",
"unreadNotificationsMessage": "U heeft ongelezen OSM-berichten en/of nieuwe opmerkingen op uw changesets.",
"unreadNotificationsView": "Nu Bekijken"
},
"queue": {
"title": "Upload Wachtrij",
@@ -279,7 +313,11 @@
"closingChangeset": " (Changeset sluiten...)",
"processingPaused": "Wachtrij Verwerking Gepauzeerd",
"pausedDueToOffline": "Upload verwerking is gepauzeerd omdat offline modus is ingeschakeld.",
"pausedByUser": "Upload verwerking is handmatig gepauzeerd."
"pausedByUser": "Upload verwerking is handmatig gepauzeerd.",
"inFlightWaitTitle": "Indiening Wordt Afgerond",
"inFlightWaitMessage": "Er is momenteel een indiening bezig die moet worden afgerond voordat deze instelling kan worden toegepast. Dit zou maar een moment moeten duren.",
"inFlightCompleteTitle": "Indiening Voltooid",
"inFlightCompleteMessage": "Uw indiening is succesvol afgerond. Uw instelling wordt nu toegepast."
},
"tileProviders": {
"title": "Tile Providers",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Haal node gegevens opnieuw op voor dit gebied",
"startRefresh": "Start Verversen",
"refreshStarted": "Verversen gestart!",
"refreshFailed": "Verversen mislukt: {}"
"refreshFailed": "Verversen mislukt: {}",
"disableConfirmTitle": "Bestaande Offline Gebiedsgegevens Verwijderen?",
"disableConfirmMessage": "U heeft al bestaande offline gebiedsgegevens. Het uitschakelen van offline functies zal voorkomen dat de app deze gebruikt. Wilt u deze gegevens op het apparaat bewaren voor het geval u offline functies later weer inschakelt, of ze nu verwijderen om opslagruimte vrij te maken?",
"keepData": "Gegevens Behouden",
"deleteData": "Gegevens Verwijderen"
},
"refineTagsSheet": {
"title": "Verfijn Tags",
+49 -7
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Wydajność, alerty i ustawienia dostawców kafelków",
"proximityAlerts": "Alerty Bliskości",
"keepScreenAwake": "Nie Wygaszaj Ekranu",
"networkStatusIndicator": "Wskaźnik Stanu Sieci"
"networkStatusIndicator": "Wskaźnik Stanu Sieci",
"hideZoomControls": "Ukryj Kontrolki Zoomu",
"enableOfflineFeatures": "Włącz Funkcje Offline",
"enableOfflineFeaturesTitle": "Włącz funkcje offline",
"enableOfflineFeaturesSubtitle": "Zezwól na pobieranie i korzystanie z map offline. Jeśli wyłączone, tryb offline i pobrane obszary będą niedostępne."
},
"keepScreenAwake": {
"title": "Nie wygaszaj ekranu podczas korzystania z aplikacji",
"subtitle": "Zapobiega automatycznemu wygaszaniu ekranu podczas korzystania z aplikacji"
},
"hideZoomControls": {
"title": "Ukryj kontrolki zoomu",
"subtitle": "Ukrywa przyciski zoomu +/- oraz wskaźnik poziomu powiększenia. Nadal możesz powiększać za pomocą gestów szczypania."
},
"proximityAlerts": {
"getNotified": "Otrzymuj powiadomienia przy zbliżaniu się do urządzeń nadzoru",
"batteryUsage": "Używa dodatkowej baterii do ciągłego monitorowania lokalizacji",
@@ -128,7 +136,13 @@
"enableNotifications": "Włącz Powiadomienia",
"checkingPermissions": "Sprawdzanie uprawnień...",
"alertDistance": "Odległość alertu: ",
"rangeInfo": "Zakres: {}-{} {} (domyślnie: {})"
"rangeInfo": "Zakres: {}-{} {} (domyślnie: {})",
"backgroundServiceTitle": "Alerty o bliskości aktywne",
"backgroundServiceText": "Wyszukiwanie pobliskich urządzeń monitorujących",
"backgroundServiceChannel": "Monitorowanie alertów o bliskości",
"openSettings": "Otwórz ustawienia",
"blockedTitle": "Powiadomienia są zablokowane",
"blockedMessage": "Powiadomienia dla DeFlock są wyłączone. Włącz je w ustawieniach systemowych, aby otrzymywać alerty o bliskości."
},
"node": {
"title": "Węzeł #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "Usuwanie węzła umieszczone w kolejce do przesłania",
"confirmDeleteTitle": "Usuń Węzeł",
"confirmDeleteMessage": "Czy na pewno chcesz usunąć węzeł #{}? Tej akcji nie można cofnąć.",
"deleteReasonLabel": "Powód Usunięcia (Opcjonalny)",
"deleteReasonHint": "np. urządzenie usunięte, nieprawidłowa lokalizacja, duplikat..."
"deleteReasonLabel": "Powód Usunięcia",
"deleteReasonSelectHint": "Wybierz...",
"deleteReasonDeviceRemoved": "Urządzenie usunięte",
"deleteReasonDuplicateNode": "Zduplikowany węzeł",
"deleteReasonMisidentifiedInfra": "Błędnie zidentyfikowana infrastruktura",
"deleteReasonSpamVandalism": "Spam/wandalizm",
"deleteReasonCustom": "Niestandardowy..",
"deleteReasonHint": "Opisz powód...",
"mustBeLoggedInToDelete": "Musisz być zalogowany na konto OpenStreetMap, aby dodawać dane do mapy.",
"uploadPending": "Przesyłanie oczekujące",
"uploadCreatingChangeset": "Tworzenie zestawu zmian...",
"uploadUploading": "Przesyłanie...",
"uploadClosingChangeset": "Zamykanie zestawu zmian...",
"uploadError": "Przesyłanie nie powiodło się",
"uploadComplete": "Przesyłanie zakończone",
"viewInQueue": "Zobacz w Kolejce",
"deletedSuccessfully": "Ten węzeł został pomyślnie usunięty z OpenStreetMap."
},
"addNode": {
"profile": "Profil",
@@ -244,7 +273,12 @@
"reauthExplanation": "Musisz odświeżyć uwierzytelnienie, aby otrzymywać powiadomienia o wiadomościach OSM przez aplikację.",
"reauthBenefit": "To włączy kropki powiadomień, gdy masz nieprzeczytane wiadomości w OpenStreetMap.",
"reauthNow": "Zrób To Teraz",
"reauthLater": "Później"
"newChangesetComments": "Nowy Komentarz do Zestawu Zmian",
"newChangesetCommentsSubtitle": "Ktoś skomentował jeden lub więcej Twoich zestawów zmian",
"reauthLater": "Później",
"unreadNotificationsTitle": "Masz Nieprzeczytane Powiadomienia",
"unreadNotificationsMessage": "Masz nieprzeczytane wiadomości OSM i/lub nowe komentarze do Twoich zestawów zmian.",
"unreadNotificationsView": "Zobacz Teraz"
},
"queue": {
"title": "Kolejka Przesyłania",
@@ -279,7 +313,11 @@
"closingChangeset": " (Zamykanie zestawu zmian...)",
"processingPaused": "Przetwarzanie Kolejki Wstrzymane",
"pausedDueToOffline": "Przetwarzanie przesyłania jest wstrzymane, ponieważ tryb offline jest włączony.",
"pausedByUser": "Przetwarzanie przesyłania jest ręcznie wstrzymane."
"pausedByUser": "Przetwarzanie przesyłania jest ręcznie wstrzymane.",
"inFlightWaitTitle": "Kończenie Przesyłania",
"inFlightWaitMessage": "Przesyłanie jest obecnie w toku i musi zostać zakończone, zanim to ustawienie będzie mogło zostać zastosowane. To powinno zająć tylko chwilę.",
"inFlightCompleteTitle": "Przesyłanie Zakończone",
"inFlightCompleteMessage": "Twoje przesyłanie zakończyło się pomyślnie. Stosowanie ustawienia teraz."
},
"tileProviders": {
"title": "Dostawcy Kafelków",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Pobierz ponownie dane węzłów dla tego obszaru",
"startRefresh": "Rozpocznij Odświeżanie",
"refreshStarted": "Odświeżanie rozpoczęte!",
"refreshFailed": "Odświeżanie nie powiodło się: {}"
"refreshFailed": "Odświeżanie nie powiodło się: {}",
"disableConfirmTitle": "Usunąć Istniejące Dane Obszarów Offline?",
"disableConfirmMessage": "Masz już istniejące dane obszarów offline. Wyłączenie funkcji offline uniemożliwi aplikacji ich używanie. Czy chcesz zachować te dane na urządzeniu na wypadek ponownego włączenia funkcji offline później, czy usunąć je teraz, aby zwolnić miejsce na dysku?",
"keepData": "Zachowaj Dane",
"deleteData": "Usuń Dane"
},
"refineTagsSheet": {
"title": "Doprecyzuj Tagi",
+49 -7
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Configurações de desempenho, alertas e provedores de mapas",
"proximityAlerts": "Alertas de Proximidade",
"keepScreenAwake": "Manter Ecrã Ativa",
"networkStatusIndicator": "Indicador de Status de Rede"
"networkStatusIndicator": "Indicador de Status de Rede",
"hideZoomControls": "Ocultar Controlos de Zoom",
"enableOfflineFeatures": "Ativar Funcionalidades Offline",
"enableOfflineFeaturesTitle": "Ativar funcionalidades offline",
"enableOfflineFeaturesSubtitle": "Permitir descarregar e usar áreas de mapa offline. Se desativado, o modo offline e as áreas descarregadas não estarão disponíveis."
},
"keepScreenAwake": {
"title": "Manter o ecrã ativo durante o uso do app",
"subtitle": "Impede que o ecrã se desligue automaticamente enquanto a app estiver em uso"
},
"hideZoomControls": {
"title": "Ocultar controlos de zoom",
"subtitle": "Oculta os botões de zoom +/- e o indicador de nível de zoom. Ainda pode ampliar com gestos de pinça."
},
"proximityAlerts": {
"getNotified": "Receba notificações ao se aproximar de dispositivos de vigilância",
"batteryUsage": "Usa bateria extra para monitoramento contínuo de localização",
@@ -128,7 +136,13 @@
"enableNotifications": "Habilitar Notificações",
"checkingPermissions": "Verificando permissões...",
"alertDistance": "Distância de alerta: ",
"rangeInfo": "Faixa: {}-{} {} (padrão: {})"
"rangeInfo": "Faixa: {}-{} {} (padrão: {})",
"backgroundServiceTitle": "Alertas de proximidade ativos",
"backgroundServiceText": "Procurando dispositivos de vigilância próximos",
"backgroundServiceChannel": "Monitoramento de alertas de proximidade",
"openSettings": "Abrir configurações",
"blockedTitle": "As notificações estão bloqueadas",
"blockedMessage": "As notificações estão desativadas para o DeFlock. Ative-as nas configurações do sistema para receber alertas de proximidade."
},
"node": {
"title": "Nó #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "Exclusão de nó na fila para envio",
"confirmDeleteTitle": "Excluir Nó",
"confirmDeleteMessage": "Tem certeza de que deseja excluir o nó #{}? Esta ação não pode ser desfeita.",
"deleteReasonLabel": "Motivo para Exclusão (Opcional)",
"deleteReasonHint": "ex. dispositivo removido, localização incorreta, duplicado..."
"deleteReasonLabel": "Motivo para Exclusão",
"deleteReasonSelectHint": "Selecionar...",
"deleteReasonDeviceRemoved": "Dispositivo removido",
"deleteReasonDuplicateNode": "Nó duplicado",
"deleteReasonMisidentifiedInfra": "Infraestrutura mal identificada",
"deleteReasonSpamVandalism": "Spam/vandalismo",
"deleteReasonCustom": "Personalizado..",
"deleteReasonHint": "Descreva o motivo...",
"mustBeLoggedInToDelete": "Você precisa estar conectado com uma conta do OpenStreetMap para contribuir com dados do mapa.",
"uploadPending": "Envio pendente",
"uploadCreatingChangeset": "Criando changeset...",
"uploadUploading": "Enviando...",
"uploadClosingChangeset": "Fechando changeset...",
"uploadError": "Falha no envio",
"uploadComplete": "Envio concluído",
"viewInQueue": "Ver na Fila",
"deletedSuccessfully": "Este nó foi excluído com sucesso do OpenStreetMap."
},
"addNode": {
"profile": "Perfil",
@@ -244,7 +273,12 @@
"reauthExplanation": "Você deve atualizar sua autenticação para receber notificações de mensagens OSM através do aplicativo.",
"reauthBenefit": "Isso habilitará pontos de notificação quando você tiver mensagens não lidas no OpenStreetMap.",
"reauthNow": "Fazer Agora",
"reauthLater": "Mais Tarde"
"newChangesetComments": "Novo Comentário no Changeset",
"newChangesetCommentsSubtitle": "Alguém comentou em um ou mais dos seus changesets",
"reauthLater": "Mais Tarde",
"unreadNotificationsTitle": "Você Tem Notificações Não Lidas",
"unreadNotificationsMessage": "Você tem mensagens OSM não lidas e/ou novos comentários nos seus changesets.",
"unreadNotificationsView": "Ver Agora"
},
"queue": {
"title": "Fila de Upload",
@@ -279,7 +313,11 @@
"closingChangeset": " (Fechando changeset...)",
"processingPaused": "Processamento da Fila Pausado",
"pausedDueToOffline": "O processamento de upload está pausado porque o modo offline está habilitado.",
"pausedByUser": "O processamento de upload está pausado manualmente."
"pausedByUser": "O processamento de upload está pausado manualmente.",
"inFlightWaitTitle": "Finalizando Envio",
"inFlightWaitMessage": "Atualmente há um envio em andamento que precisa terminar antes que esta configuração possa ser aplicada. Isso deve levar apenas um momento.",
"inFlightCompleteTitle": "Envio Concluído",
"inFlightCompleteMessage": "Seu envio foi concluído com sucesso. Aplicando sua configuração agora."
},
"tileProviders": {
"title": "Provedores de Tiles",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Buscar novamente os dados dos nós para esta área",
"startRefresh": "Iniciar Atualização",
"refreshStarted": "Atualização iniciada!",
"refreshFailed": "Atualização falhou: {}"
"refreshFailed": "Atualização falhou: {}",
"disableConfirmTitle": "Eliminar Dados de Áreas Offline Existentes?",
"disableConfirmMessage": "Já tem dados de áreas offline existentes. Desativar as funcionalidades offline impedirá que a app os utilize. Deseja manter estes dados no dispositivo caso reative as funcionalidades offline mais tarde, ou eliminá-los agora para libertar espaço de armazenamento?",
"keepData": "Manter Dados",
"deleteData": "Eliminar Dados"
},
"refineTagsSheet": {
"title": "Refinar Tags",
+49 -7
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Performans, uyarılar ve döşeme sağlayıcı ayarları",
"proximityAlerts": "Yakınlık Uyarıları",
"keepScreenAwake": "Ekranı Açık Tut",
"networkStatusIndicator": "Ağ Durumu Göstergesi"
"networkStatusIndicator": "Ağ Durumu Göstergesi",
"hideZoomControls": "Yakınlaştırma Kontrollerini Gizle",
"enableOfflineFeatures": "Çevrimdışı Özellikleri Etkinleştir",
"enableOfflineFeaturesTitle": "Çevrimdışı özellikleri etkinleştir",
"enableOfflineFeaturesSubtitle": "Çevrimdışı harita alanlarını indirmeye ve kullanmaya izin ver. Devre dışı bırakılırsa, çevrimdışı mod ve indirilen alanlar kullanılamaz."
},
"keepScreenAwake": {
"title": "Uygulamayı kullanırken ekranı açık tut",
"subtitle": "Uygulamayı kullanırken ekranın otomatik olarak kapanmasını engeller"
},
"hideZoomControls": {
"title": "Yakınlaştırma kontrollerini gizle",
"subtitle": "+/- yakınlaştırma düğmelerini ve yakınlaştırma seviyesi göstergesini gizler. Yine de kıstırma hareketleriyle yakınlaştırabilirsiniz."
},
"proximityAlerts": {
"getNotified": "Gözetleme cihazlarına yaklaşırken bildirim al",
"batteryUsage": "Sürekli konum izleme için ekstra batarya kullanır",
@@ -128,7 +136,13 @@
"enableNotifications": "Bildirimleri Etkinleştir",
"checkingPermissions": "İzinler kontrol ediliyor...",
"alertDistance": "Uyarı mesafesi: ",
"rangeInfo": "Aralık: {}-{} {} (varsayılan: {})"
"rangeInfo": "Aralık: {}-{} {} (varsayılan: {})",
"backgroundServiceTitle": "Yakınlık uyarıları etkin",
"backgroundServiceText": "Yakındaki gözetim cihazları aranıyor",
"backgroundServiceChannel": "Yakınlık Uyarısı İzleme",
"openSettings": "Ayarları aç",
"blockedTitle": "Bildirimler engellendi",
"blockedMessage": "DeFlock için bildirimler kapalı. Yakınlık uyarıları almak için sistem ayarlarından etkinleştirin."
},
"node": {
"title": "Düğüm #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "Düğüm silme işlemi yükleme için sıraya alındı",
"confirmDeleteTitle": "Düğümü Sil",
"confirmDeleteMessage": "#{} düğümünü silmek istediğinizden emin misiniz? Bu işlem geri alınamaz.",
"deleteReasonLabel": "Silme Nedeni (İsteğe Bağlı)",
"deleteReasonHint": "örn. cihaz kaldırıldı, yanlış konum, duplikat..."
"deleteReasonLabel": "Silme Nedeni",
"deleteReasonSelectHint": "Seçin...",
"deleteReasonDeviceRemoved": "Cihaz kaldırıldı",
"deleteReasonDuplicateNode": "Yinelenen düğüm",
"deleteReasonMisidentifiedInfra": "Yanlış tanımlanmış altyapı",
"deleteReasonSpamVandalism": "Spam/vandalizm",
"deleteReasonCustom": "Özel..",
"deleteReasonHint": "Lütfen nedeni açıklayın...",
"mustBeLoggedInToDelete": "Harita verilerine katkıda bulunmak için bir OpenStreetMap hesabıyla oturum açmış olmanız gerekir.",
"uploadPending": "Yükleme bekliyor",
"uploadCreatingChangeset": "Değişiklik seti oluşturuluyor...",
"uploadUploading": "Yükleniyor...",
"uploadClosingChangeset": "Değişiklik seti kapatılıyor...",
"uploadError": "Yükleme başarısız oldu",
"uploadComplete": "Yükleme tamamlandı",
"viewInQueue": "Sırada Görüntüle",
"deletedSuccessfully": "Bu düğüm OpenStreetMap'ten başarıyla silindi."
},
"addNode": {
"profile": "Profil",
@@ -244,7 +273,12 @@
"reauthExplanation": "Uygulama üzerinden OSM mesaj bildirimlerini alabilmek için kimlik doğrulamanızı yenilemeniz gerekir.",
"reauthBenefit": "Bu, OpenStreetMap'te okunmamış mesajlarınız olduğunda bildirim noktalarını etkinleştirecek.",
"reauthNow": "Şimdi Yap",
"reauthLater": "Sonra"
"newChangesetComments": "Yeni Değişiklik Kümesi Yorumu",
"newChangesetCommentsSubtitle": "Biri değişiklik kümelerinizden birine veya birkaçına yorum yaptı",
"reauthLater": "Sonra",
"unreadNotificationsTitle": "Okunmamış Bildirimleriniz Var",
"unreadNotificationsMessage": "Okunmamış OSM mesajlarınız ve/veya değişiklik kümelerinize yapılan yeni yorumlar var.",
"unreadNotificationsView": "Şimdi Görüntüle"
},
"queue": {
"title": "Yükleme Kuyruğu",
@@ -279,7 +313,11 @@
"closingChangeset": " (Değişiklik seti kapatılıyor...)",
"processingPaused": "Kuyruk İşleme Duraklatıldı",
"pausedDueToOffline": "Çevrimdışı mod etkin olduğu için yükleme işleme duraklatıldı.",
"pausedByUser": "Yükleme işleme manuel olarak duraklatıldı."
"pausedByUser": "Yükleme işleme manuel olarak duraklatıldı.",
"inFlightWaitTitle": "Gönderim Tamamlanıyor",
"inFlightWaitMessage": "Şu anda devam eden bir gönderim var ve bu ayar uygulanmadan önce tamamlanması gerekiyor. Bu sadece bir an sürmelidir.",
"inFlightCompleteTitle": "Gönderim Tamamlandı",
"inFlightCompleteMessage": "Gönderiminiz başarıyla tamamlandı. Ayarınız şimdi uygulanıyor."
},
"tileProviders": {
"title": "Döşeme Sağlayıcıları",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Bu alan için düğüm verisini yeniden getir",
"startRefresh": "Yenilemeyi Başlat",
"refreshStarted": "Yenileme başladı!",
"refreshFailed": "Yenileme başarısız: {}"
"refreshFailed": "Yenileme başarısız: {}",
"disableConfirmTitle": "Mevcut Çevrimdışı Alan Verileri Silinsin mi?",
"disableConfirmMessage": "Zaten mevcut çevrimdışı alan verileriniz var. Çevrimdışı özellikleri devre dışı bırakmak, uygulamanın bunları kullanmasını engelleyecektir. Daha sonra çevrimdışı özellikleri tekrar etkinleştirme ihtimaline karşı bu verileri cihazda saklamak mı istersiniz, yoksa depolama alanını boşaltmak için şimdi silmek mi istersiniz?",
"keepData": "Verileri Sakla",
"deleteData": "Verileri Sil"
},
"refineTagsSheet": {
"title": "Etiketleri Düzenle",
+49 -7
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "Продуктивність, сповіщення та налаштування постачальників плиток",
"proximityAlerts": "Сповіщення Про Близькість",
"keepScreenAwake": "Тримати екран активним",
"networkStatusIndicator": "Індикатор Стану Мережі"
"networkStatusIndicator": "Індикатор Стану Мережі",
"hideZoomControls": "Приховати Елементи Керування Масштабом",
"enableOfflineFeatures": "Увімкнути Офлайн-Функції",
"enableOfflineFeaturesTitle": "Увімкнути офлайн-функції",
"enableOfflineFeaturesSubtitle": "Дозволити завантаження та використання офлайн-областей карти. Якщо вимкнено, офлайн-режим і завантажені області будуть недоступні."
},
"keepScreenAwake": {
"title": "Тримати екран активним під час використання програми",
"subtitle": "Запобігає автоматичному вимкненню екрана під час використання програми"
},
"hideZoomControls": {
"title": "Приховати елементи керування масштабом",
"subtitle": "Приховує кнопки масштабування +/- та індикатор рівня масштабу. Ви все ще можете масштабувати жестами."
},
"proximityAlerts": {
"getNotified": "Отримувати сповіщення при наближенні до пристроїв спостереження",
"batteryUsage": "Використовує додаткову батарею для безперервного моніторингу місцезнаходження",
@@ -128,7 +136,13 @@
"enableNotifications": "Увімкнути Сповіщення",
"checkingPermissions": "Перевірка дозволів...",
"alertDistance": "Відстань сповіщення: ",
"rangeInfo": "Діапазон: {}-{} {} (за замовчуванням: {})"
"rangeInfo": "Діапазон: {}-{} {} (за замовчуванням: {})",
"backgroundServiceTitle": "Сповіщення про наближення активні",
"backgroundServiceText": "Пошук пристроїв стеження поблизу",
"backgroundServiceChannel": "Моніторинг сповіщень про наближення",
"openSettings": "Відкрити налаштування",
"blockedTitle": "Сповіщення заблоковано",
"blockedMessage": "Сповіщення для DeFlock вимкнено. Увімкніть їх у налаштуваннях системи, щоб отримувати сповіщення про наближення."
},
"node": {
"title": "Вузол #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "Видалення вузла поставлено в чергу для завантаження",
"confirmDeleteTitle": "Видалити Вузол",
"confirmDeleteMessage": "Ви впевнені, що хочете видалити вузол #{}? Цю дію не можна скасувати.",
"deleteReasonLabel": "Причина Видалення (Опціонально)",
"deleteReasonHint": "наприклад пристрій видалено, неправильне розташування, дублікат..."
"deleteReasonLabel": "Причина Видалення",
"deleteReasonSelectHint": "Вибрати...",
"deleteReasonDeviceRemoved": "Пристрій видалено",
"deleteReasonDuplicateNode": "Дубльований вузол",
"deleteReasonMisidentifiedInfra": "Неправильно ідентифікована інфраструктура",
"deleteReasonSpamVandalism": "Спам/вандалізм",
"deleteReasonCustom": "Власний..",
"deleteReasonHint": "Опишіть причину...",
"mustBeLoggedInToDelete": "Ви повинні увійти в обліковий запис OpenStreetMap, щоб надавати дані карти.",
"uploadPending": "Завантаження очікує",
"uploadCreatingChangeset": "Створення набору змін...",
"uploadUploading": "Завантаження...",
"uploadClosingChangeset": "Закриття набору змін...",
"uploadError": "Помилка завантаження",
"uploadComplete": "Завантаження завершено",
"viewInQueue": "Переглянути в Черзі",
"deletedSuccessfully": "Цей вузол було успішно видалено з OpenStreetMap."
},
"addNode": {
"profile": "Профіль",
@@ -244,7 +273,12 @@
"reauthExplanation": "Ви повинні оновити вашу автентифікацію, щоб отримувати сповіщення про повідомлення OSM через додаток.",
"reauthBenefit": "Це дозволить показувати точки сповіщень, коли у вас є непрочитані повідомлення в OpenStreetMap.",
"reauthNow": "Зробити Зараз",
"reauthLater": "Пізніше"
"newChangesetComments": "Новий Коментар до Набору Змін",
"newChangesetCommentsSubtitle": "Хтось прокоментував один або декілька ваших наборів змін",
"reauthLater": "Пізніше",
"unreadNotificationsTitle": "У Вас Є Непрочитані Сповіщення",
"unreadNotificationsMessage": "У вас є непрочитані повідомлення OSM та/або нові коментарі до ваших наборів змін.",
"unreadNotificationsView": "Переглянути Зараз"
},
"queue": {
"title": "Черга Завантаження",
@@ -279,7 +313,11 @@
"closingChangeset": " (Закриття набору змін...)",
"processingPaused": "Обробка Черги Призупинена",
"pausedDueToOffline": "Обробка завантаження призупинена, оскільки увімкнено офлайн режим.",
"pausedByUser": "Обробка завантаження призупинена вручну."
"pausedByUser": "Обробка завантаження призупинена вручну.",
"inFlightWaitTitle": "Завершення Подання",
"inFlightWaitMessage": "Наразі триває подання, яке потрібно завершити перед застосуванням цього налаштування. Це має зайняти лише мить.",
"inFlightCompleteTitle": "Подання Завершено",
"inFlightCompleteMessage": "Ваше подання успішно завершено. Застосування вашого налаштування зараз."
},
"tileProviders": {
"title": "Постачальники Плиток",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "Повторно отримати дані вузлів для цієї області",
"startRefresh": "Почати Оновлення",
"refreshStarted": "Оновлення розпочато!",
"refreshFailed": "Оновлення не вдалося: {}"
"refreshFailed": "Оновлення не вдалося: {}",
"disableConfirmTitle": "Видалити Наявні Дані Офлайн-Областей?",
"disableConfirmMessage": "У вас вже є наявні дані офлайн-областей. Вимкнення офлайн-функцій завадить додатку використовувати їх. Бажаєте зберегти ці дані на пристрої на випадок, якщо ви знову увімкнете офлайн-функції пізніше, чи видалити їх зараз, щоб звільнити місце на диску?",
"keepData": "Зберегти Дані",
"deleteData": "Видалити Дані"
},
"refineTagsSheet": {
"title": "Уточнити Теги",
+49 -7
View File
@@ -112,12 +112,20 @@
"advancedSettingsSubtitle": "性能、警报和地图提供商设置",
"proximityAlerts": "邻近警报",
"keepScreenAwake": "保持屏幕常亮",
"networkStatusIndicator": "网络状态指示器"
"networkStatusIndicator": "网络状态指示器",
"hideZoomControls": "隐藏缩放控件",
"enableOfflineFeatures": "启用离线功能",
"enableOfflineFeaturesTitle": "启用离线功能",
"enableOfflineFeaturesSubtitle": "允许下载和使用离线地图区域。禁用后,离线模式和已下载的区域将不可用。"
},
"keepScreenAwake": {
"title": "使用应用时保持屏幕常亮",
"subtitle": "防止在使用应用期间屏幕自动熄灭"
},
"hideZoomControls": {
"title": "隐藏缩放控件",
"subtitle": "隐藏 +/- 缩放按钮和缩放级别指示器。您仍然可以使用捏合手势进行缩放。"
},
"proximityAlerts": {
"getNotified": "接近监控设备时接收通知",
"batteryUsage": "使用额外电量进行连续位置监控",
@@ -128,7 +136,13 @@
"enableNotifications": "启用通知",
"checkingPermissions": "检查权限中...",
"alertDistance": "警报距离:",
"rangeInfo": "范围:{}-{} {}(默认:{})"
"rangeInfo": "范围:{}-{} {}(默认:{})",
"backgroundServiceTitle": "邻近提醒已启用",
"backgroundServiceText": "正在搜索附近的监控设备",
"backgroundServiceChannel": "邻近提醒监控",
"openSettings": "打开设置",
"blockedTitle": "通知已被阻止",
"blockedMessage": "DeFlock 的通知已关闭。请在系统设置中启用,以接收邻近提醒。"
},
"node": {
"title": "节点 #{}",
@@ -138,8 +152,23 @@
"deleteQueuedForUpload": "节点删除已排队上传",
"confirmDeleteTitle": "删除节点",
"confirmDeleteMessage": "您确定要删除节点 #{} 吗?此操作无法撤销。",
"deleteReasonLabel": "删除原因(可选)",
"deleteReasonHint": "例如:设备已移除、位置错误、重复..."
"deleteReasonLabel": "删除原因",
"deleteReasonSelectHint": "请选择...",
"deleteReasonDeviceRemoved": "设备已移除",
"deleteReasonDuplicateNode": "重复节点",
"deleteReasonMisidentifiedInfra": "识别错误的基础设施",
"deleteReasonSpamVandalism": "垃圾信息/破坏",
"deleteReasonCustom": "自定义..",
"deleteReasonHint": "请描述原因...",
"mustBeLoggedInToDelete": "您必须使用 OpenStreetMap 账户登录才能贡献地图数据。",
"uploadPending": "上传待处理",
"uploadCreatingChangeset": "正在创建变更集...",
"uploadUploading": "正在上传...",
"uploadClosingChangeset": "正在关闭变更集...",
"uploadError": "上传失败",
"uploadComplete": "上传完成",
"viewInQueue": "在队列中查看",
"deletedSuccessfully": "此节点已成功从 OpenStreetMap 删除。"
},
"addNode": {
"profile": "配置文件",
@@ -244,7 +273,12 @@
"reauthExplanation": "您必须刷新身份验证才能通过应用接收 OSM 消息通知。",
"reauthBenefit": "这将在您在 OpenStreetMap 上有未读消息时启用通知点。",
"reauthNow": "现在执行",
"reauthLater": "稍后"
"newChangesetComments": "新的变更集评论",
"newChangesetCommentsSubtitle": "有人评论了您的一个或多个变更集",
"reauthLater": "稍后",
"unreadNotificationsTitle": "您有未读通知",
"unreadNotificationsMessage": "您有未读的 OSM 消息和/或对您变更集的新评论。",
"unreadNotificationsView": "立即查看"
},
"queue": {
"title": "上传队列",
@@ -279,7 +313,11 @@
"closingChangeset": " (关闭变更集...)",
"processingPaused": "队列处理已暂停",
"pausedDueToOffline": "因为离线模式已启用,上传处理已暂停。",
"pausedByUser": "上传处理已手动暂停。"
"pausedByUser": "上传处理已手动暂停。",
"inFlightWaitTitle": "正在完成提交",
"inFlightWaitMessage": "当前有一个提交正在进行中,需要先完成才能应用此设置。这应该只需要一点时间。",
"inFlightCompleteTitle": "提交完成",
"inFlightCompleteMessage": "您的提交已成功完成。正在应用您的设置。"
},
"tileProviders": {
"title": "瓦片提供商",
@@ -426,7 +464,11 @@
"refreshNodesSubtitle": "重新获取此区域的节点数据",
"startRefresh": "开始刷新",
"refreshStarted": "刷新已开始!",
"refreshFailed": "刷新失败:{}"
"refreshFailed": "刷新失败:{}",
"disableConfirmTitle": "删除现有的离线区域数据?",
"disableConfirmMessage": "您已有现有的离线区域数据。禁用离线功能将阻止应用使用这些数据。您是想将这些数据保留在设备上,以便日后重新启用离线功能时使用,还是现在删除以释放存储空间?",
"keepData": "保留数据",
"deleteData": "删除数据"
},
"refineTagsSheet": {
"title": "细化标签",
+42 -5
View File
@@ -17,12 +17,44 @@ import 'services/localization_service.dart';
import 'services/provider_tile_cache_manager.dart';
import 'services/version_service.dart';
import 'services/deep_link_service.dart';
import 'services/deflock_tile_provider.dart' show TileLoadCancelledException, TileNotAvailableOfflineException;
/// Suppress console noise for expected, already-handled tile load errors.
///
/// [TileLoadCancelledException] (tile scrolled off screen) and
/// [TileNotAvailableOfflineException] (no cached data available) are thrown
/// deliberately by DeflockOfflineTileImageProvider and are already handled —
/// TileLayerManager.onTileLoadError() specifically skips retry logic for
/// both. Flutter's image pipeline reports them via
/// MultiFrameImageStreamCompleter with `silent: true`, but
/// FlutterError.dumpErrorToConsole has a debug-mode assert() that ignores
/// the silent flag and always prints to console anyway. This filters those
/// two specific, expected exception types back out while leaving all other
/// errors (including genuinely silent-but-unexpected ones) reported as
/// normal.
void _installTileErrorFilter() {
final defaultOnError = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails details) {
final exception = details.exception;
if (details.silent &&
(exception is TileLoadCancelledException ||
exception is TileNotAvailableOfflineException)) {
return; // Already handled — don't spam the console.
}
if (defaultOnError != null) {
defaultOnError(details);
} else {
FlutterError.presentError(details);
}
};
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
_installTileErrorFilter();
// Initialize version service
await VersionService().init();
@@ -93,16 +125,21 @@ class DeFlockApp extends StatelessWidget {
},
initialRoute: '/',
onUnknownRoute: (settings) {
// Handle deep link routes that Flutter tries to process before app_links
// This catches routes like "/?id=13939398601" from "deflockapp://node?id=13939398601"
debugPrint('[Navigation] Unknown route intercepted: ${settings.name} (likely deep link, will be handled by DeepLinkService)');
// Fallback for any genuinely unknown named route (e.g. a stale/bad
// link). Deep links (deflockapp://...) are handled exclusively by
// DeepLinkService via the app_links package - Flutter's own
// implicit deep-link routing is disabled at the platform level
// (see AndroidManifest.xml's flutter_deeplinking_enabled and
// Info.plist's FlutterDeepLinkingEnabled) to avoid this handler
// double-navigating and burying screens pushed by DeepLinkService.
debugPrint('[Navigation] Unknown route intercepted: ${settings.name}');
return MaterialPageRoute(
settings: settings,
builder: (_) => const HomeScreen(),
);
},
);
}
}
+29
View File
@@ -3,11 +3,13 @@ import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'app_state.dart';
import 'services/offline_area_service.dart';
import 'services/profile_service.dart';
import 'services/suspected_location_cache.dart';
import 'widgets/nuclear_reset_dialog.dart';
import 'dev_config.dart';
/// One-time migrations that run when users upgrade to specific versions.
/// Each migration function is named after the version where it should run.
class OneTimeMigrations {
@@ -189,6 +191,30 @@ class OneTimeMigrations {
}
}
/// Enable offline features for existing users who already have offline
/// area data (v2.10.5). New installs and existing users who never used
/// offline areas will keep the new "offline features enabled" setting at
/// its default of false.
static Future<void> migrate_2_10_5(AppState appState) async {
try {
final offlineAreaService = OfflineAreaService();
await offlineAreaService.ensureInitialized();
if (offlineAreaService.offlineAreas.isNotEmpty) {
await appState.setOfflineFeaturesEnabled(true);
debugPrint('[Migration] 2.10.5: Existing offline area data found - enabled offline features');
} else {
debugPrint('[Migration] 2.10.5: No existing offline area data - leaving offline features disabled');
}
debugPrint('[Migration] 2.10.5 completed: offline features migration done');
} catch (e) {
debugPrint('[Migration] 2.10.5 ERROR: Failed to migrate offline features setting: $e');
// Don't rethrow - this is non-critical, worst case is the user needs
// to manually re-enable the toggle to see their existing offline areas.
}
}
/// Get the migration function for a specific version
static Future<void> Function(AppState)? getMigrationForVersion(String version) {
switch (version) {
@@ -206,11 +232,14 @@ class OneTimeMigrations {
return migrate_2_7_3;
case '2.10.0':
return migrate_2_10_0;
case '2.10.5':
return migrate_2_10_5;
default:
return null;
}
}
/// Run migration for a specific version with nuclear reset on failure
static Future<void> runMigration(String version, AppState appState, BuildContext? context) async {
try {
@@ -4,6 +4,8 @@ import 'settings/sections/proximity_alerts_section.dart';
import 'settings/sections/suspected_locations_section.dart';
import 'settings/sections/tile_provider_section.dart';
import 'settings/sections/keep_screen_awake_section.dart';
import 'settings/sections/hide_zoom_controls_section.dart';
import '../services/localization_service.dart';
class AdvancedSettingsScreen extends StatelessWidget {
@@ -35,6 +37,9 @@ class AdvancedSettingsScreen extends StatelessWidget {
Divider(),
KeepScreenAwakeSection(),
Divider(),
HideZoomControlsSection(),
Divider(),
// NetworkStatusSection(), // Commented out - network status indicator now defaults to enabled
// Divider(),
TileProviderSection(),
+110 -71
View File
@@ -8,6 +8,8 @@ import '../app_state.dart';
import '../dev_config.dart';
import '../widgets/map_view.dart';
import '../services/localization_service.dart';
import '../services/map_data_provider.dart';
import '../widgets/node_tag_sheet.dart';
import '../widgets/download_area_dialog.dart';
@@ -16,6 +18,7 @@ import '../widgets/search_bar.dart';
import '../widgets/suspected_location_sheet.dart';
import '../widgets/welcome_dialog.dart';
import '../widgets/changelog_dialog.dart';
import '../widgets/unread_notifications_dialog.dart';
import '../models/osm_node.dart';
import '../models/suspected_location.dart';
import '../models/search_result.dart';
@@ -51,6 +54,9 @@ class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
// Track popup display to avoid showing multiple times
bool _hasCheckedForPopup = false;
// Track whether we've shown the unread notifications popup this session
bool _hasShownUnreadNotificationsPopup = false;
@override
void initState() {
@@ -245,6 +251,21 @@ class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
}
}
void _showUnreadNotificationsDialog() {
if (!mounted) return;
showDialog(
context: context,
builder: (context) => UnreadNotificationsDialog(
onView: () {
Navigator.of(context).pushNamed('/settings/osm-account');
},
onDismiss: () {
// Just dismiss - badges remain visible until the user views them.
},
),
);
}
void _onStartRoute() {
_navigationCoordinator.startRoute(
context: context,
@@ -455,6 +476,35 @@ class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
});
}
// Show a one-time popup this session if the user has unread messages
// and/or unread changeset comments. Gated on _hasCheckedForPopup so it
// doesn't race with the welcome/changelog dialog above.
if (_hasCheckedForPopup &&
!_hasShownUnreadNotificationsPopup &&
appState.isLoggedIn &&
appState.hasUnreadNotifications) {
_hasShownUnreadNotificationsPopup = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_showUnreadNotificationsDialog();
});
}
// Auto-focus a node's details sheet right after it was submitted/edited/deleted,
// behind kAutoOpenNodeSheetAfterSubmit (pending A/B testing/team feedback).
if (kAutoOpenNodeSheetAfterSubmit) {
final focusNodeId = appState.consumePendingFocusNodeId();
if (focusNodeId != null && !_sheetCoordinator.hasActiveNodeSheet) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final node = MapDataProvider().getNodeById(focusNodeId);
if (node != null) {
openNodeTagSheet(node);
}
});
}
}
// Pass the active sheet height directly to the map
final activeSheetHeight = _sheetCoordinator.activeSheetHeight;
@@ -492,23 +542,9 @@ class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
final appState = context.watch<AppState>();
return IconButton(
tooltip: LocalizationService.instance.settings,
icon: Stack(
children: [
const Icon(Icons.settings),
if (appState.hasUnreadMessages)
Positioned(
right: 0,
top: 0,
child: Container(
width: 10,
height: 10,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.error,
shape: BoxShape.circle,
),
),
),
],
icon: Badge(
isLabelVisible: appState.hasUnreadNotifications,
child: const Icon(Icons.settings),
),
onPressed: () => Navigator.pushNamed(context, '/settings'),
);
@@ -595,67 +631,70 @@ class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
),
margin: EdgeInsets.only(bottom: kBottomButtonBarOffset),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
child: Row(
children: [
Expanded(
flex: 7, // 70% for primary action
child: AnimatedBuilder(
animation: LocalizationService.instance,
builder: (context, child) => ElevatedButton.icon(
icon: Icon(Icons.add_location_alt),
label: Text(LocalizationService.instance.tagNode),
onPressed: _openAddNodeSheet,
style: ElevatedButton.styleFrom(
minimumSize: Size(0, 48),
textStyle: TextStyle(fontSize: 16),
child: AnimatedBuilder(
animation: LocalizationService.instance,
builder: (context, child) {
final appState = context.watch<AppState>();
final showDownloadButton = appState.offlineFeaturesEnabled;
final canDownload = appState.selectedTileType?.allowsOfflineDownload ?? false;
return Row(
children: [
Expanded(
// Take full width when the download button is hidden
flex: showDownloadButton ? 7 : 10,
child: ElevatedButton.icon(
icon: Icon(Icons.add_location_alt),
label: Text(LocalizationService.instance.tagNode),
onPressed: _openAddNodeSheet,
style: ElevatedButton.styleFrom(
minimumSize: Size(0, 48),
textStyle: TextStyle(fontSize: 16),
),
),
),
),
),
SizedBox(width: 12),
Expanded(
flex: 3, // 30% for secondary action
child: AnimatedBuilder(
animation: LocalizationService.instance,
builder: (context, child) {
final appState = context.watch<AppState>();
final canDownload = appState.selectedTileType?.allowsOfflineDownload ?? false;
return FittedBox(
fit: BoxFit.scaleDown,
child: ElevatedButton.icon(
icon: Icon(Icons.download_for_offline),
label: Text(LocalizationService.instance.download),
onPressed: canDownload ? () {
// Check minimum zoom level before opening download dialog
final currentZoom = _mapController.mapController.camera.zoom;
if (currentZoom < kMinZoomForOfflineDownload) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
LocalizationService.instance.t('download.areaTooBigMessage',
params: [kMinZoomForOfflineDownload.toString()])
if (showDownloadButton) ...[
SizedBox(width: 12),
Expanded(
flex: 3, // 30% for secondary action
child: FittedBox(
fit: BoxFit.scaleDown,
child: ElevatedButton.icon(
icon: Icon(Icons.download_for_offline),
label: Text(LocalizationService.instance.download),
onPressed: canDownload ? () {
// Check minimum zoom level before opening download dialog
final currentZoom = _mapController.mapController.camera.zoom;
if (currentZoom < kMinZoomForOfflineDownload) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
LocalizationService.instance.t('download.areaTooBigMessage',
params: [kMinZoomForOfflineDownload.toString()])
),
),
),
);
return;
}
);
return;
}
showDialog(
context: context,
builder: (ctx) => DownloadAreaDialog(controller: _mapController.mapController),
);
} : null,
style: ElevatedButton.styleFrom(
minimumSize: Size(0, 48),
textStyle: TextStyle(fontSize: 16),
showDialog(
context: context,
builder: (ctx) => DownloadAreaDialog(controller: _mapController.mapController),
);
} : null,
style: ElevatedButton.styleFrom(
minimumSize: Size(0, 48),
textStyle: TextStyle(fontSize: 16),
),
),
),
);
},
),
),
],
),
],
],
);
},
),
),
),
);
+38 -13
View File
@@ -1,4 +1,7 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../app_state.dart';
import 'settings/sections/enable_offline_features_section.dart';
import 'settings/sections/offline_mode_section.dart';
import 'settings/sections/offline_areas_section.dart';
import '../services/localization_service.dart';
@@ -16,20 +19,42 @@ class OfflineSettingsScreen extends StatelessWidget {
appBar: AppBar(
title: Text(locService.t('settings.offlineSettings')),
),
body: ListView(
padding: EdgeInsets.fromLTRB(
16,
16,
16,
16 + MediaQuery.of(context).padding.bottom,
),
children: const [
OfflineModeSection(),
Divider(),
OfflineAreasSection(),
],
body: Consumer<AppState>(
builder: (context, appState, child) {
final offlineFeaturesEnabled = appState.offlineFeaturesEnabled;
return ListView(
padding: EdgeInsets.fromLTRB(
16,
16,
16,
16 + MediaQuery.of(context).padding.bottom,
),
children: [
const EnableOfflineFeaturesSection(),
const Divider(),
// Grey out and disable interaction with the rest of the
// offline settings when the master toggle is off, while
// keeping them visible/discoverable.
Opacity(
opacity: offlineFeaturesEnabled ? 1.0 : 0.4,
child: IgnorePointer(
ignoring: !offlineFeaturesEnabled,
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
OfflineModeSection(),
Divider(),
OfflineAreasSection(),
],
),
),
),
],
);
},
),
),
);
}
}
}
+37 -29
View File
@@ -128,38 +128,46 @@ class _OSMAccountScreenState extends State<OSMAccountScreen> {
},
),
// Unread changeset comments - links directly to the
// specific changeset with the new comment, and only
// appears when there is one.
if (appState.hasUnreadChangesetComments) ...[
const Divider(),
ListTile(
leading: Badge(
isLabelVisible: true,
child: const Icon(Icons.comment),
),
title: Text(locService.t('auth.newChangesetComments')),
subtitle: Text(locService.t('auth.newChangesetCommentsSubtitle')),
trailing: const Icon(Icons.open_in_new),
onTap: () async {
final changesetUrl = appState.getUnreadChangesetUrl();
if (changesetUrl == null) return;
final url = Uri.parse(changesetUrl);
if (await canLaunchUrl(url)) {
await launchUrl(url, mode: LaunchMode.externalApplication);
// The user has now had the opportunity to see the
// new comment on OSM's website - clear our badge.
appState.markChangesetCommentsRead();
} else {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(locService.t('advancedEdit.couldNotOpenOSMWebsite'))),
);
}
}
},
),
],
// Messages button - only show when not in simulate mode
const Divider(),
ListTile(
leading: Stack(
children: [
const Icon(Icons.message),
if (appState.hasUnreadMessages)
Positioned(
right: 0,
top: 0,
child: Container(
padding: const EdgeInsets.all(2),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.error,
shape: BoxShape.circle,
),
constraints: const BoxConstraints(
minWidth: 12,
minHeight: 12,
),
child: Text(
'${appState.unreadMessageCount}',
style: TextStyle(
color: Theme.of(context).colorScheme.onError,
fontSize: 10,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
),
),
],
leading: Badge(
isLabelVisible: appState.hasUnreadMessages,
label: Text('${appState.unreadMessageCount ?? 0}'),
child: const Icon(Icons.message),
),
title: Text(locService.t('auth.viewMessages')),
subtitle: Text(appState.hasUnreadMessages
@@ -0,0 +1,101 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../app_state.dart';
import '../../../services/offline_area_service.dart';
import '../../../services/localization_service.dart';
/// Master toggle for all offline-area functionality (downloading, browsing,
/// and using cached tiles/nodes offline). When disabled, the rest of the
/// Offline Settings screen (offline mode + offline areas list) is greyed out
/// and the download button on the map screen is hidden. Functionally, the
/// app will behave as if no offline area data exists at all while this is
/// off, regardless of whether area files still exist on disk.
class EnableOfflineFeaturesSection extends StatelessWidget {
const EnableOfflineFeaturesSection({super.key});
Future<void> _handleToggle(BuildContext context, AppState appState, bool value) async {
if (value) {
// Enabling requires no confirmation.
await appState.setOfflineFeaturesEnabled(true);
return;
}
// Disabling: if offline area data already exists, ask whether to keep
// or delete it. Either choice proceeds to disable the toggle - there is
// no "cancel" path once this dialog is shown.
final offlineService = OfflineAreaService();
await offlineService.ensureInitialized();
if (!context.mounted) return;
final hasExistingAreas = offlineService.offlineAreas.isNotEmpty;
if (!hasExistingAreas) {
await appState.setOfflineFeaturesEnabled(false);
return;
}
final locService = LocalizationService.instance;
final shouldDelete = await showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: Text(locService.t('offlineAreas.disableConfirmTitle')),
content: Text(locService.t('offlineAreas.disableConfirmMessage')),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text(locService.t('offlineAreas.keepData')),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
child: Text(locService.t('offlineAreas.deleteData')),
),
],
),
);
if (shouldDelete == true) {
for (final area in offlineService.offlineAreas.toList()) {
offlineService.deleteArea(area.id);
}
}
// Disable regardless of the user's data choice.
await appState.setOfflineFeaturesEnabled(false);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: LocalizationService.instance,
builder: (context, child) {
final locService = LocalizationService.instance;
final appState = context.watch<AppState>();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
locService.t('settings.enableOfflineFeatures'),
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text(locService.t('settings.enableOfflineFeaturesTitle')),
subtitle: Text(
locService.t('settings.enableOfflineFeaturesSubtitle'),
style: const TextStyle(fontSize: 12),
),
value: appState.offlineFeaturesEnabled,
onChanged: (value) => _handleToggle(context, appState, value),
),
],
);
},
);
}
}
@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../app_state.dart';
import '../../../services/localization_service.dart';
class HideZoomControlsSection extends StatelessWidget {
const HideZoomControlsSection({super.key});
@override
Widget build(BuildContext context) {
// Standard Pattern: Use AnimatedBuilder to respond to language/localization changes
return AnimatedBuilder(
animation: LocalizationService.instance,
builder: (context, child) {
final locService = LocalizationService.instance;
final appState = context.watch<AppState>();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Bold Section Header (matches Keep Screen Awake, Proximity, etc.)
Text(
locService.t('settings.hideZoomControls'),
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
// The Functional Toggle
SwitchListTile(
contentPadding: EdgeInsets.zero, // Aligns switch text with the bold header
title: Text(locService.t('hideZoomControls.title')),
subtitle: Text(
locService.t('hideZoomControls.subtitle'),
style: const TextStyle(fontSize: 12),
),
value: appState.hideZoomControls,
onChanged: (bool value) {
appState.setHideZoomControls(value);
},
),
],
);
},
);
}
}
@@ -3,6 +3,8 @@ import 'package:provider/provider.dart';
import '../../../app_state.dart';
import '../../../services/offline_area_service.dart';
import '../../../services/localization_service.dart';
import '../../../widgets/in_flight_upload_wait_dialog.dart';
class OfflineModeSection extends StatelessWidget {
const OfflineModeSection({super.key});
@@ -49,10 +51,17 @@ class OfflineModeSection extends StatelessWidget {
}
}
// Proceed with the change
await appState.setOfflineMode(value);
// Proceed with the change, respecting any in-flight submission that
// needs to finish before offline mode actually takes effect.
if (!context.mounted) return;
await applyQueueSettingChangeRespectingInFlightUploads(
context: context,
appState: appState,
applyChange: () => appState.setOfflineMode(value),
);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
@@ -18,7 +18,8 @@ class ProximityAlertsSection extends StatefulWidget {
State<ProximityAlertsSection> createState() => _ProximityAlertsSectionState();
}
class _ProximityAlertsSectionState extends State<ProximityAlertsSection> {
class _ProximityAlertsSectionState extends State<ProximityAlertsSection>
with WidgetsBindingObserver {
late final TextEditingController _distanceController;
bool _notificationsEnabled = false;
bool _checkingPermissions = false;
@@ -26,6 +27,9 @@ class _ProximityAlertsSectionState extends State<ProximityAlertsSection> {
@override
void initState() {
super.initState();
// Re-check on resume: the user may have just granted notifications in the
// system settings app and come back.
WidgetsBinding.instance.addObserver(this);
final appState = context.read<AppState>();
// Convert meters to display units for the text field
final displayValue = DistanceService.convertFromMeters(
@@ -57,19 +61,59 @@ class _ProximityAlertsSectionState extends State<ProximityAlertsSection> {
setState(() {
_checkingPermissions = true;
});
final enabled = await ProximityAlertService().requestNotificationPermissions();
if (mounted) {
setState(() {
_notificationsEnabled = enabled;
_checkingPermissions = false;
});
if (!mounted) return;
setState(() {
_notificationsEnabled = enabled;
_checkingPermissions = false;
});
// Still not granted. On iOS the system prompt only ever appears once, so
// re-requesting silently does nothing — the only remaining path is the
// system settings app.
if (!enabled) {
await _promptOpenSystemSettings();
}
}
Future<void> _promptOpenSystemSettings() async {
final locService = LocalizationService.instance;
final shouldOpen = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(locService.t('proximityAlerts.blockedTitle')),
content: Text(locService.t('proximityAlerts.blockedMessage')),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: Text(locService.t('actions.cancel')),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: Text(locService.t('proximityAlerts.openSettings')),
),
],
),
);
if (shouldOpen == true) {
await ProximityAlertService().openSystemSettings();
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_checkNotificationPermissions();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_distanceController.dispose();
super.dispose();
}
+3 -17
View File
@@ -117,23 +117,9 @@ class SettingsScreen extends StatelessWidget {
final appState = context.watch<AppState>();
return ListTile(
leading: Stack(
children: [
const Icon(Icons.account_circle),
if (appState.hasUnreadMessages)
Positioned(
right: 0,
top: 0,
child: Container(
width: 10,
height: 10,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.error,
shape: BoxShape.circle,
),
),
),
],
leading: Badge(
isLabelVisible: appState.hasUnreadNotifications,
child: const Icon(Icons.account_circle),
),
title: Text(locService.t('auth.osmAccountTitle')),
subtitle: Text(locService.t('auth.osmAccountSubtitle')),
+20 -1
View File
@@ -3,6 +3,8 @@ import 'package:provider/provider.dart';
import '../app_state.dart';
import '../models/pending_upload.dart';
import '../services/localization_service.dart';
import '../widgets/in_flight_upload_wait_dialog.dart';
class UploadQueueScreen extends StatelessWidget {
const UploadQueueScreen({super.key});
@@ -84,6 +86,22 @@ class UploadQueueScreen extends StatelessWidget {
}
}
Future<void> _handlePauseQueueChange(BuildContext context, AppState appState, bool value) async {
// Only need to wait for in-flight uploads when turning pause ON.
// Resuming (turning it off) can happen immediately.
if (!value) {
await appState.setPauseQueueProcessing(value);
return;
}
await applyQueueSettingChangeRespectingInFlightUploads(
context: context,
appState: appState,
applyChange: () => appState.setPauseQueueProcessing(value),
);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
@@ -166,9 +184,10 @@ class UploadQueueScreen extends StatelessWidget {
value: appState.pauseQueueProcessing,
onChanged: appState.offlineMode
? null // Disable when offline mode is on
: (value) => appState.setPauseQueueProcessing(value),
: (value) => _handlePauseQueueChange(context, appState, value),
),
),
const SizedBox(height: 16),
+5
View File
@@ -241,7 +241,12 @@ class ChangelogService {
versionsNeedingMigration.add('2.10.0');
}
if (needsMigration(lastSeenVersion, currentVersion, '2.10.5')) {
versionsNeedingMigration.add('2.10.5');
}
// Future versions can be added here
// if (needsMigration(lastSeenVersion, currentVersion, '2.0.0')) {
// versionsNeedingMigration.add('2.0.0');
// }
@@ -0,0 +1,182 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../state/settings_state.dart';
import 'http_client.dart';
/// Tracks unread comments on the user's own changesets.
///
/// The OSM API has no "read" concept for changeset comments, so we track it
/// ourselves: we remember the `comments_count` we last saw for each of the
/// user's recent changesets, and flag a changeset as having unread comments
/// if it now has a higher count than what we last recorded.
///
/// This only looks at the user's most recent 100 changesets (the OSM API's
/// max page size, and it doesn't support simple offset paging). If a
/// changeset receives a new comment and then ages out of that window
/// entirely before the next check, we will miss it - an accepted limitation
/// of polling a bounded recent-activity window rather than a real
/// notification feed.
class ChangesetCommentsService {
static const _cacheDuration = Duration(minutes: 5);
final _client = UserAgentClient();
DateTime? _lastCheck;
int? _lastResult; // ID of changeset with unread comments, or null if none
bool _lastResultIsSet = false; // whether _lastResult holds a valid cached value
UploadMode? _lastMode;
/// Returns the ID of a changeset with more comments now than the last
/// time [markRead] was called for this upload mode, or null if there are
/// none (or if not logged in, in simulate mode, or on error). When
/// multiple changesets have new comments, returns the most recent one
/// (the API returns changesets newest-first).
Future<int?> getUnreadChangesetId({
required String? username,
required UploadMode uploadMode,
bool forceRefresh = false,
}) async {
if (uploadMode == UploadMode.simulate) return null;
if (username == null || username.isEmpty) return null;
if (!forceRefresh &&
_lastResultIsSet &&
_lastMode == uploadMode &&
_lastCheck != null &&
DateTime.now().difference(_lastCheck!) < _cacheDuration) {
return _lastResult;
}
try {
final current = await _fetchCommentCounts(username, uploadMode);
if (current == null) return null;
final seen = await _loadSeenCounts(uploadMode);
// current is built from the API response, which is ordered
// newest-first, so the first match found is the most recent one.
int? unreadId;
for (final entry in current.entries) {
if (entry.value > (seen[entry.key] ?? 0)) {
unreadId = entry.key;
break;
}
}
_lastCheck = DateTime.now();
_lastResult = unreadId;
_lastResultIsSet = true;
_lastMode = uploadMode;
return unreadId;
} catch (e) {
return null;
}
}
/// Mark all currently-visible changeset comments as read by saving the
/// current comment counts as the new baseline.
Future<void> markRead({
required String? username,
required UploadMode uploadMode,
}) async {
if (uploadMode == UploadMode.simulate) return;
if (username == null || username.isEmpty) return;
try {
final current = await _fetchCommentCounts(username, uploadMode);
if (current == null) return;
await _saveSeenCounts(uploadMode, current);
// Update in-memory cache so getUnreadChangesetId() doesn't need to
// re-fetch immediately after marking read.
_lastCheck = DateTime.now();
_lastResult = null;
_lastResultIsSet = true;
_lastMode = uploadMode;
} catch (e) {
// Best-effort - if this fails the badge will just persist until the
// next successful mark-read attempt.
}
}
/// Clear cached state (useful on logout or upload mode change).
void clearCache() {
_lastCheck = null;
_lastResult = null;
_lastResultIsSet = false;
_lastMode = null;
}
/// Build the URL to the given changeset on the OSM website for the given
/// upload mode.
String getChangesetUrl(int changesetId, UploadMode uploadMode) {
switch (uploadMode) {
case UploadMode.production:
return 'https://www.openstreetmap.org/changeset/$changesetId';
case UploadMode.sandbox:
return 'https://master.apis.dev.openstreetmap.org/changeset/$changesetId';
case UploadMode.simulate:
return 'https://www.openstreetmap.org/changeset/$changesetId';
}
}
/// Fetches the user's most recent changesets and returns a map of
/// changeset ID -> comments_count. Returns null on any error.
Future<Map<int, int>?> _fetchCommentCounts(
String username,
UploadMode uploadMode,
) async {
final apiHost = _getApiHost(uploadMode);
final response = await _client.get(
Uri.parse('$apiHost/api/0.6/changesets.json?display_name=${Uri.encodeQueryComponent(username)}'),
);
if (response.statusCode != 200) return null;
final data = jsonDecode(response.body);
final changesets = data['changesets'];
if (changesets is! List) return null;
final result = <int, int>{};
for (final cs in changesets) {
final id = cs['id'];
final count = cs['comments_count'];
if (id is int && count is int) {
result[id] = count;
}
}
return result;
}
Future<Map<int, int>> _loadSeenCounts(UploadMode uploadMode) async {
final prefs = await SharedPreferences.getInstance();
final json = prefs.getString(_prefsKey(uploadMode));
if (json == null) return {};
try {
final decoded = jsonDecode(json) as Map<String, dynamic>;
return decoded.map((k, v) => MapEntry(int.parse(k), v as int));
} catch (e) {
return {};
}
}
Future<void> _saveSeenCounts(UploadMode uploadMode, Map<int, int> counts) async {
final prefs = await SharedPreferences.getInstance();
final encoded = jsonEncode(counts.map((k, v) => MapEntry(k.toString(), v)));
await prefs.setString(_prefsKey(uploadMode), encoded);
}
String _prefsKey(UploadMode uploadMode) =>
'changeset_comments_seen_${uploadMode.name}';
String _getApiHost(UploadMode uploadMode) {
switch (uploadMode) {
case UploadMode.production:
return 'https://api.openstreetmap.org';
case UploadMode.sandbox:
return 'https://api06.dev.openstreetmap.org';
case UploadMode.simulate:
return 'https://api.openstreetmap.org';
}
}
}
+27
View File
@@ -0,0 +1,27 @@
/// Shared validation helpers for geographic coordinates and zoom levels.
///
/// Used wherever a coordinate or zoom level comes from an external source
/// (GPS fixes, persisted preferences, live map camera state) that isn't
/// guaranteed to be finite/in-range.
library;
import '../dev_config.dart' show kAbsoluteMaxZoom;
/// Validate that a latitude value is finite and within -90 to 90.
bool isValidLatitude(double value) {
return !value.isNaN && !value.isInfinite && value >= -90.0 && value <= 90.0;
}
/// Validate that a longitude value is finite and within -180 to 180.
bool isValidLongitude(double value) {
return !value.isNaN && !value.isInfinite && value >= -180.0 && value <= 180.0;
}
/// Validate that a zoom level is finite and within a sane range.
///
/// Defaults to 1.0 to [kAbsoluteMaxZoom]. `num` is used (rather than
/// `double`) so the `int` constant [kAbsoluteMaxZoom] can be used directly
/// as a default parameter value.
bool isValidZoom(double zoom, {num min = 1.0, num max = kAbsoluteMaxZoom}) {
return !zoom.isNaN && !zoom.isInfinite && zoom >= min && zoom <= max;
}
@@ -0,0 +1,32 @@
import '../models/node_profile.dart';
/// Formats editor direction values exactly as they will be queued for upload.
class DirectionSubmissionFormatter {
const DirectionSubmissionFormatter._();
static Object format(List<double> directions, NodeProfile? profile) {
if (directions.isEmpty) return 0.0;
final fov = profile?.fov;
if (fov != null && fov > 0) {
final ranges = directions
.map((center) => _formatDirectionWithFov(center, fov))
.toList();
return ranges.length == 1 ? ranges.first : ranges.join(';');
}
if (directions.length == 1) return directions.first;
return directions
.map((direction) => direction.round().toString())
.join(';');
}
static String _formatDirectionWithFov(double center, double fov) {
if (fov >= 360) return '0-360';
final halfFov = fov / 2;
final start = (center - halfFov + 360) % 360;
final end = (center + halfFov) % 360;
return '${start.round()}-${end.round()}';
}
}
@@ -0,0 +1,77 @@
import '../models/pending_upload.dart';
import '../state/session_state.dart';
import '../state/settings_state.dart';
import 'direction_submission_formatter.dart';
/// Detects whether an edit would serialize to a different OSM node.
class EditNodeChangeDetector {
const EditNodeChangeDetector._();
static bool hasActualChanges(EditNodeSession session) {
if (session.extractFromWay) return true;
const tolerance = 0.0000001;
if ((session.target.latitude - session.originalNode.coord.latitude).abs() >
tolerance ||
(session.target.longitude - session.originalNode.coord.longitude)
.abs() >
tolerance) {
return true;
}
final originalTags = session.originalNode.tags;
final submittedTags = _getSubmittedTags(session);
final originalDirection = _directionValue(originalTags);
final submittedDirection =
originalDirection == null && session.directions.isEmpty
? null
: _directionValue(submittedTags);
if (originalDirection != submittedDirection) {
return true;
}
return !_tagsEqual(originalTags, submittedTags);
}
static Map<String, String> _getSubmittedTags(EditNodeSession session) {
if (session.profile == null) return <String, String>{};
return PendingUpload(
coord: session.target,
direction: DirectionSubmissionFormatter.format(
session.directions,
session.profile,
),
profile: session.profile,
operatorProfile: session.operatorProfile,
refinedTags: session.refinedTags,
additionalExistingTags: session.additionalExistingTags,
changesetComment: session.changesetComment,
uploadMode: UploadMode.production,
operation: UploadOperation.modify,
originalNodeId: session.originalNode.id,
).getCombinedTags();
}
static String? _directionValue(Map<String, String> tags) =>
tags['direction'] ?? tags['camera:direction'];
static bool _tagsEqual(
Map<String, String> originalTags,
Map<String, String> submittedTags,
) {
final original = Map<String, String>.from(originalTags)
..remove('direction')
..remove('camera:direction');
final submitted = Map<String, String>.from(submittedTags)
..remove('direction')
..remove('camera:direction');
if (original.length != submitted.length) return false;
for (final entry in original.entries) {
if (submitted[entry.key] != entry.value) return false;
}
return true;
}
}
+40
View File
@@ -0,0 +1,40 @@
import 'dart:math' as math;
import 'package:flutter_map/flutter_map.dart' show LatLngBounds;
import 'package:latlong2/latlong.dart';
/// Mean meters per degree of latitude. Constant enough at any latitude for
/// picking a node lookup box.
const double _metersPerDegreeLat = 111320.0;
/// Smallest cos(latitude) we will divide by. Past ~89.4° the true factor tends
/// to zero and the longitude span would blow up to the whole globe.
const double _minCosLatitude = 0.01;
/// A square of roughly [radiusMeters] in every direction around [center].
///
/// Used to pull cached nodes near a GPS position, as opposed to near whatever
/// the map camera is showing — the camera is frozen while the app is
/// backgrounded, so it is not a usable proxy for where the user is.
///
/// A degree of longitude shrinks by cos(latitude), so the box is widened east
/// to west to keep the real-world radius honest as you move away from the
/// equator.
LatLngBounds boundsAround(LatLng center, num radiusMeters) {
final radius = radiusMeters.toDouble().abs();
final latDelta = radius / _metersPerDegreeLat;
final cosLat = math.cos(center.latitude * math.pi / 180).abs();
final lngDelta =
radius / (_metersPerDegreeLat * math.max(cosLat, _minCosLatitude));
return LatLngBounds(
LatLng(
(center.latitude - latDelta).clamp(-90.0, 90.0),
(center.longitude - lngDelta).clamp(-180.0, 180.0),
),
LatLng(
(center.latitude + latDelta).clamp(-90.0, 90.0),
(center.longitude + lngDelta).clamp(-180.0, 180.0),
),
);
}
+1 -1
View File
@@ -54,8 +54,8 @@ class MapDataProvider {
required List<NodeProfile> profiles,
UploadMode uploadMode = UploadMode.production,
int maxResults = 0, // 0 = no limit for offline downloads
int maxTries = 3,
}) async {
if (AppState.instance.offlineMode) {
throw OfflineModeException("Cannot fetch remote nodes for offline area download in offline mode.");
}
+27 -4
View File
@@ -215,7 +215,18 @@ class NodeDataManager extends ChangeNotifier {
}
}
/// Fetch nodes with automatic area splitting if needed
/// Fetch nodes, splitting the query area into quadrants only when Overpass
/// reports the query would exceed its hard 50k node limit ([NodeLimitError]).
///
/// Splitting is deliberately NOT used for other failure modes:
/// - [RateLimitError] (HTTP 429): the server explicitly asked us to slow
/// down, so firing off up to 4x more requests would be counterproductive.
/// We back off instead, while still surfacing the "slow" status
/// indicator to the user (same UI feedback as the splitting case).
/// - Timeouts / other transient failures now surface as [NetworkError]
/// (see [OverpassService]) and are not caught here at all — they're
/// handled by the normal retry/backoff/fallback logic and reported as a
/// plain timeout/error status by the caller.
Future<List<OsmNode>> fetchWithSplitting(
LatLngBounds bounds,
List<NodeProfile> profiles, {
@@ -238,7 +249,7 @@ class NodeDataManager extends ChangeNotifier {
return nodes;
} on NodeLimitError {
// Hit node limit or timeout - split area if not too deep
// Hit the deterministic 50k node limit - split area if not too deep
if (splitDepth >= maxSplitDepth) {
debugPrint('[NodeDataManager] Max split depth reached, giving up');
return [];
@@ -254,13 +265,20 @@ class NodeDataManager extends ChangeNotifier {
return _fetchSplitAreas(bounds, profiles, splitDepth + 1, isUserInitiated: isUserInitiated);
} on RateLimitError {
// Rate limited - wait and return empty
debugPrint('[NodeDataManager] Rate limited, backing off');
// Rate limited - back off without splitting the area. Splitting here
// would multiply request volume against a server that just told us to
// slow down. We still show the same "slow" status indicator so the
// user gets feedback, but there is no recursive quadrant fetching.
debugPrint('[NodeDataManager] Rate limited, backing off (no area splitting)');
if (isUserInitiated) {
NetworkStatus.instance.setSplitting();
}
await Future.delayed(const Duration(seconds: 30));
return [];
}
}
/// Fetch data by splitting area into quadrants
Future<List<OsmNode>> _fetchSplitAreas(
LatLngBounds bounds,
@@ -372,8 +390,13 @@ class NodeDataManager extends ChangeNotifier {
/// Load all offline nodes into cache (call at app startup)
Future<void> preloadOfflineNodes() async {
// Skip entirely when the user has disabled offline features — this call
// isn't gated by OfflineAreaService.hasOfflineAreasForProvider*() since
// it fetches directly via fetchLocalNodes, so we guard it explicitly.
if (!AppState.instance.offlineFeaturesEnabled) return;
try {
final offlineAreaService = OfflineAreaService();
for (final area in offlineAreaService.offlineAreas) {
if (area.status != OfflineAreaStatus.complete) continue;
+11
View File
@@ -29,7 +29,13 @@ class OfflineAreaService {
/// Fast check: do we have any completed offline areas for a specific provider/type?
/// This allows smart cache routing without expensive filesystem searches.
/// Safe to call before initialization - returns false if not yet initialized.
///
/// Returns false immediately if the user has disabled offline features via
/// the master "Enable Offline Features" toggle, regardless of whether area
/// data still exists on disk — this fully gates the offline-first tile
/// pipeline without needing to touch fetchLocalTile/fetchLocalNodes.
bool hasOfflineAreasForProvider(String providerId, String tileTypeId) {
if (!AppState.instance.offlineFeaturesEnabled) return false;
if (!_initialized) {
return false; // No offline areas loaded yet
}
@@ -44,7 +50,11 @@ class OfflineAreaService {
/// Like [hasOfflineAreasForProvider] but also checks that at least one area
/// covers the given [zoom] level. Used by [DeflockTileProvider] to skip the
/// offline-first path for tiles that will never be found locally.
///
/// Also returns false immediately when offline features are disabled (see
/// [hasOfflineAreasForProvider] for rationale).
bool hasOfflineAreasForProviderAtZoom(String providerId, String tileTypeId, int zoom) {
if (!AppState.instance.offlineFeaturesEnabled) return false;
if (!_initialized) return false;
return _areas.any((area) =>
area.status == OfflineAreaStatus.complete &&
@@ -54,6 +64,7 @@ class OfflineAreaService {
zoom <= area.maxZoom
);
}
/// Reset service state and inject areas for unit tests.
@visibleForTesting
@@ -1,23 +0,0 @@
/// Exception thrown when Overpass API returns an error indicating too many nodes were requested.
/// This typically happens when querying large areas that would return more than 50k nodes.
class OverpassNodeLimitException implements Exception {
final String message;
final String? serverResponse;
OverpassNodeLimitException(this.message, {this.serverResponse});
@override
String toString() => 'OverpassNodeLimitException: $message';
}
/// Exception thrown when Overpass API rate limits the request.
/// Should trigger longer backoff delays, not area splitting.
class OverpassRateLimitException implements Exception {
final String message;
final String? serverResponse;
OverpassRateLimitException(this.message, {this.serverResponse});
@override
String toString() => 'OverpassRateLimitException: $message';
}
+170 -37
View File
@@ -32,7 +32,20 @@ class OverpassService {
String get _primaryEndpoint => _endpointOverride ?? defaultEndpoint;
/// Fetch surveillance nodes from Overpass API with retry and fallback.
/// Throws NetworkError for retryable failures, NodeLimitError for area splitting.
///
/// Throws:
/// - [NodeLimitError] when the query would exceed Overpass's hard 50k node
/// limit. This is the *only* case where the caller should split the
/// query area into smaller regions, since it's a deterministic function
/// of how much data lives in the requested bounds.
/// - [RateLimitError] when rate limited (HTTP 429 or equivalent). Callers
/// should back off, not split/retry — splitting would only amplify load
/// on a server that just told us to slow down.
/// - [NetworkError] for timeouts and other retryable HTTP/network failures.
/// Timeouts are usually a sign of server load or an expensive query, not
/// "too much area" — retrying with a hail of smaller sub-requests makes
/// the problem worse, so timeouts are treated like any other transient
/// network failure (handled by the existing retry/backoff/fallback logic).
Future<List<OsmNode>> fetchNodes({
required LatLngBounds bounds,
required List<NodeProfile> profiles,
@@ -70,22 +83,16 @@ class OverpassService {
final errorBody = response.body;
// Node limit error - caller should split area
// Node limit error - a deterministic result-set size limit. This is
// the one case where splitting the query area into smaller regions is
// the correct fix, since it directly reduces nodes-per-request.
if (response.statusCode == 400 &&
(errorBody.contains('too many nodes') && errorBody.contains('50000'))) {
debugPrint('[OverpassService] Node limit exceeded, area should be split');
debugPrint('[OverpassService] Node limit exceeded (50k), area should be split');
throw NodeLimitError('Query exceeded 50k node limit');
}
// Timeout error - also try splitting (complex query)
if (errorBody.contains('timeout') ||
errorBody.contains('runtime limit exceeded') ||
errorBody.contains('Query timed out')) {
debugPrint('[OverpassService] Query timeout, area should be split');
throw NodeLimitError('Query timed out - area too complex');
}
// Rate limit
// Rate limit - back off, don't split or hammer the server with more requests.
if (response.statusCode == 429 ||
errorBody.contains('rate limited') ||
errorBody.contains('too many requests')) {
@@ -93,6 +100,17 @@ class OverpassService {
throw RateLimitError('Rate limited by Overpass API');
}
// Timeout / runtime limit exceeded - treat as a plain retryable network
// error. This is usually server load or query cost, not "area too
// big" — splitting into up to 64 sub-requests would only make load
// on the server worse.
if (errorBody.contains('timeout') ||
errorBody.contains('runtime limit exceeded') ||
errorBody.contains('Query timed out')) {
debugPrint('[OverpassService] Query timed out');
throw NetworkError('Query timed out');
}
throw NetworkError('HTTP ${response.statusCode}: $errorBody');
} catch (e) {
if (e is NodeLimitError || e is RateLimitError || e is NetworkError) {
@@ -108,33 +126,150 @@ class OverpassService {
return ErrorDisposition.retry;
}
/// Build Overpass QL query for given bounds and profiles
/// Build Overpass QL query for given bounds and profiles.
///
/// Profiles are deduplicated first: if one profile's non-empty tags are a
/// subset of another's (with identical values), the broader profile's query
/// clause already returns every node the narrower one would, so the
/// narrower clause is redundant and can be dropped. This directly reduces
/// query size/complexity without changing the result set — client-side
/// filtering (matching returned nodes against the full profile list) still
/// happens independently, so nothing is lost.
String _buildQuery(LatLngBounds bounds, List<NodeProfile> profiles) {
final nodeClauses = profiles.map((profile) {
// Convert profile tags to Overpass filter format, excluding empty values
final tagFilters = profile.tags.entries
final profilesToQuery = _deduplicateProfilesForQuery(profiles);
if (profilesToQuery.length < profiles.length) {
debugPrint(
'[OverpassService] Deduplicated ${profiles.length} profiles to ${profilesToQuery.length} for query efficiency');
}
// Per-profile tag filter strings (e.g. ["man_made"="surveillance"]["surveillance:type"="ALPR"]),
// excluding empty tag values. Reused twice below: once to select our nodes
// in the bbox, and again to re-select just our nodes out of the pool of
// way/relation-connected nodes (which may include unrelated node types).
final tagFilterStrings = profilesToQuery.map((profile) {
return profile.tags.entries
.where((entry) => entry.value.trim().isNotEmpty)
.map((entry) => '["${entry.key}"="${entry.value}"]')
.join();
}).toList();
return 'node$tagFilters(${bounds.southWest.latitude},${bounds.southWest.longitude},${bounds.northEast.latitude},${bounds.northEast.longitude});';
}).join('\n ');
final bboxStr = '${bounds.southWest.latitude},${bounds.southWest.longitude},'
'${bounds.northEast.latitude},${bounds.northEast.longitude}';
final allNodesClauses =
tagFilterStrings.map((filters) => 'node$filters($bboxStr);').join('\n ');
final resNodesClauses =
tagFilterStrings.map((filters) => 'node.resNodes$filters;').join('\n ');
// Query strategy:
// 1. Find all matching nodes in bbox -> .allNodes, output them with tags ("out body").
// 2. Find any way/relation that references one of .allNodes ("bn." = "by node"),
// then pull the node IDs those ways/relations reference -> .wayNodes/.relNodes.
// (`node(w)`/`node(r)` on a way/relation set returns only node IDs, not
// full tags/coords, keeping the query/response cheap.)
// 3. Re-filter that combined node pool down to just our own matching
// surveillance nodes (.resNodes may contain unrelated node types too).
// 4. `convert restriction ::id = id();` emits each of those node IDs as a
// lightweight synthetic `{"type":"restriction","id":<nodeId>}` element —
// a flat, unambiguous list of which node IDs are "constrained" (part of
// some way/relation), without needing the full way/relation node lists.
return '''
[out:json][timeout:${kOverpassQueryTimeout.inSeconds}];
(
$nodeClauses
);
out body;
$allNodesClauses
)->.allNodes;
.allNodes out body;
way(bn.allNodes); node(w)->.wayNodes;
relation(bn.allNodes); node(r)->.relNodes;
(.wayNodes;.relNodes;)->.resNodes;
(
way(bn);
rel(bn);
$resNodesClauses
);
out skel;
convert restriction ::id = id();
out;
''';
}
/// Parse Overpass JSON response into OsmNode objects
/// Deduplicate profiles for Overpass queries by removing profiles that are
/// subsumed by others. A profile A subsumes profile B if all of A's
/// non-empty tags exist in B with identical values — meaning every node
/// matching B's filter also matches A's filter, so B's clause is redundant.
List<NodeProfile> _deduplicateProfilesForQuery(List<NodeProfile> profiles) {
if (profiles.length <= 1) return profiles;
final result = <NodeProfile>[];
for (final candidate in profiles) {
// Skip profiles that only have empty tags - they would match
// everything and shouldn't be treated as subsuming or subsumable.
final candidateNonEmptyTags = candidate.tags.entries
.where((entry) => entry.value.trim().isNotEmpty)
.toList();
if (candidateNonEmptyTags.isEmpty) continue;
// Check if any existing profile in our result subsumes this candidate
bool isSubsumed = false;
for (final existing in result) {
if (_profileSubsumes(existing, candidate)) {
isSubsumed = true;
break;
}
}
if (!isSubsumed) {
// This candidate is not subsumed, so add it. But first, remove any
// existing profiles that this candidate subsumes (candidate is
// broader, so those clauses are now redundant).
result.removeWhere((existing) => _profileSubsumes(candidate, existing));
result.add(candidate);
}
}
// Safety check: if dedup removed everything (e.g. all-empty-tag
// profiles), fall back to the original list rather than sending an
// empty query.
return result.isNotEmpty ? result : profiles;
}
/// Check if [broaderProfile] subsumes [specificProfile]: true if all
/// non-empty tags in [broaderProfile] exist in [specificProfile] with
/// identical values.
bool _profileSubsumes(NodeProfile broaderProfile, NodeProfile specificProfile) {
final broaderTags = Map.fromEntries(
broaderProfile.tags.entries.where((entry) => entry.value.trim().isNotEmpty),
);
final specificTags = Map.fromEntries(
specificProfile.tags.entries.where((entry) => entry.value.trim().isNotEmpty),
);
// If broader has no non-empty tags, it doesn't subsume anything (it
// would match everything, which isn't a meaningful "broader filter").
if (broaderTags.isEmpty) return false;
// If broader has more non-empty tags than specific, it can't subsume it.
if (broaderTags.length > specificTags.length) return false;
for (final entry in broaderTags.entries) {
if (specificTags[entry.key] != entry.value) return false;
}
return true;
}
/// Parse Overpass JSON response into OsmNode objects.
///
/// The query (see [_buildQuery]) produces two kinds of elements:
/// - `type: "node"` — our matched surveillance nodes, with full tags/coords
/// (from `.allNodes out body;`).
/// - `type: "restriction"` — synthetic elements (from
/// `convert restriction ::id = id();`) whose `id` is the OSM node ID of
/// one of our nodes that Overpass determined is referenced by some way
/// or relation. These carry no lat/lon/tags — just the id — and exist
/// purely to tell us which node IDs are "constrained".
List<OsmNode> _parseResponse(String responseBody) {
final data = jsonDecode(responseBody) as Map<String, dynamic>;
final elements = data['elements'] as List<dynamic>;
@@ -142,21 +277,16 @@ out skel;
final nodeElements = <Map<String, dynamic>>[];
final constrainedNodeIds = <int>{};
// First pass: collect surveillance nodes and identify constrained nodes
// First pass: collect surveillance nodes and constrained-node markers.
for (final element in elements.whereType<Map<String, dynamic>>()) {
final type = element['type'] as String?;
if (type == 'node') {
nodeElements.add(element);
} else if (type == 'way' || type == 'relation') {
// Mark referenced nodes as constrained
final refs = element['nodes'] as List<dynamic>? ??
element['members']?.where((m) => m['type'] == 'node').map((m) => m['ref']) ?? [];
for (final ref in refs) {
final nodeId = ref is int ? ref : int.tryParse(ref.toString());
if (nodeId != null) constrainedNodeIds.add(nodeId);
}
} else if (type == 'restriction') {
final rawId = element['id'];
final nodeId = rawId is int ? rawId : int.tryParse(rawId.toString());
if (nodeId != null) constrainedNodeIds.add(nodeId);
}
}
@@ -176,7 +306,10 @@ out skel;
}
}
/// Error thrown when query exceeds node limits or is too complex - area should be split
/// Error thrown when a query would exceed Overpass's 50k node limit.
/// The caller should split the query area into smaller regions to resolve this
/// — it's a deterministic function of how much data lives within the bounds.
class NodeLimitError extends Error {
final String message;
NodeLimitError(this.message);
@@ -192,7 +325,7 @@ class RateLimitError extends Error {
String toString() => 'RateLimitError: $message';
}
/// Error thrown for network/HTTP issues - retryable
/// Error thrown for network/HTTP issues (including timeouts) - retryable
class NetworkError extends Error {
final String message;
NetworkError(this.message);
+162 -76
View File
@@ -12,7 +12,7 @@ import '../dev_config.dart';
class RecentAlert {
final int nodeId;
final DateTime alertTime;
RecentAlert({required this.nodeId, required this.alertTime});
}
@@ -24,125 +24,189 @@ class ProximityAlertService {
ProximityAlertService._internal();
FlutterLocalNotificationsPlugin? _notifications;
bool _isInitialized = false;
/// Whether the plugin itself is usable. Deliberately NOT derived from
/// initialize()'s return value: on iOS that reports the outcome of the
/// permission request, which we intentionally disable below, so it returns
/// false even though the plugin works fine. Gating on it made every
/// notification path dead on iOS.
bool _pluginReady = false;
/// Guards against re-initializing on every settings visit.
Future<void>? _initFuture;
// Simple in-memory tracking of recent alerts to prevent spam
final List<RecentAlert> _recentAlerts = [];
static const Duration _alertCooldown = kProximityAlertCooldown;
// Callback for showing in-app visual alerts
VoidCallback? _onVisualAlert;
/// Initialize the notification plugin and request permissions
Future<void> initialize({VoidCallback? onVisualAlert}) async {
_onVisualAlert = onVisualAlert;
/// Initialize the notification plugin. Permissions are requested separately,
/// on demand, when the user enables proximity alerts.
Future<void> initialize({VoidCallback? onVisualAlert}) {
if (onVisualAlert != null) _onVisualAlert = onVisualAlert;
return _initFuture ??= _doInitialize();
}
Future<void> _doInitialize() async {
_notifications = FlutterLocalNotificationsPlugin();
const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
const iosSettings = DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
const initSettings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
try {
final initialized = await _notifications!.initialize(initSettings);
_isInitialized = initialized ?? false;
// Note: We don't request notification permissions here anymore.
// Permissions are requested on-demand when user enables proximity alerts.
debugPrint('[ProximityAlertService] Initialized: $_isInitialized (permissions deferred)');
await _notifications!.initialize(initSettings);
// Completing without throwing is the real signal that the plugin is up.
_pluginReady = true;
debugPrint('[ProximityAlertService] Plugin ready (permissions deferred)');
} catch (e) {
debugPrint('[ProximityAlertService] Failed to initialize: $e');
_isInitialized = false;
_pluginReady = false;
_initFuture = null; // Allow a later retry
}
}
/// Ensure the plugin is up before touching it, so callers that arrive before
/// MapView's fire-and-forget initialize() completes still work.
Future<bool> _ensureReady() async {
if (_pluginReady) return true;
await initialize();
return _pluginReady;
}
/// Request notification permissions on both platforms
/// Request notification permissions on both platforms.
///
/// Note that on iOS the system prompt appears only ONCE, ever. After the
/// user has answered it, this call returns silently without showing
/// anything — which is why callers must check the result and fall back to
/// sending the user to system settings.
Future<void> _requestNotificationPermissions() async {
if (_notifications == null) return;
try {
// Request permissions - this will show the permission dialog on Android 13+
final result = await _notifications!
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
?.requestNotificationsPermission();
debugPrint('[ProximityAlertService] Android notification permission result: $result');
// Also request for iOS (though this was already done in initialization)
await _notifications!
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
final android = _notifications!
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
if (android != null) {
final result = await android.requestNotificationsPermission();
debugPrint('[ProximityAlertService] Android permission result: $result');
return;
}
final ios = _notifications!
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>();
if (ios != null) {
final result = await ios.requestPermissions(
alert: true,
badge: true,
sound: true,
);
debugPrint('[ProximityAlertService] iOS permission result: $result');
}
} catch (e) {
debugPrint('[ProximityAlertService] Failed to request permissions: $e');
}
}
/// Open the OS settings page for this app, so the user can grant
/// notifications after the one-shot iOS prompt has already been answered.
/// Uses Geolocator's platform channel purely as a way to open app settings;
/// it is not location-specific.
Future<bool> openSystemSettings() async {
try {
return await Geolocator.openAppSettings();
} catch (e) {
debugPrint('[ProximityAlertService] Failed to open app settings: $e');
return false;
}
}
/// Check proximity to nodes and trigger alerts if needed
/// This should be called on GPS position updates
/// Check proximity to nodes and trigger alerts if needed.
/// This should be called on GPS position updates.
Future<void> checkProximity({
required LatLng userLocation,
required List<OsmNode> nodes,
required List<NodeProfile> enabledProfiles,
required int alertDistance,
}) async {
if (!_isInitialized || nodes.isEmpty) return;
if (!_pluginReady || nodes.isEmpty) return;
// Clean up old alerts (anything older than cooldown period)
final cutoffTime = DateTime.now().subtract(_alertCooldown);
_recentAlerts.removeWhere((alert) => alert.alertTime.isBefore(cutoffTime));
// Check each node for proximity
for (final node in nodes) {
// Skip if we recently alerted for this node
if (_recentAlerts.any((alert) => alert.nodeId == node.id)) {
continue;
}
// Calculate distance using Geolocator's distanceBetween
if (_recentAlerts.any((alert) => alert.nodeId == node.id)) continue;
final distance = Geolocator.distanceBetween(
userLocation.latitude,
userLocation.longitude,
node.coord.latitude,
node.coord.longitude,
);
// Check if within alert distance
if (distance <= alertDistance) {
// Determine node type for alert message
final nodeType = _getNodeTypeDescription(node, enabledProfiles);
// Trigger both push notification and visual alert
await _showNotification(node, nodeType, distance.round());
_showVisualAlert();
// Track this alert to prevent spam
_recentAlerts.add(RecentAlert(
nodeId: node.id,
alertTime: DateTime.now(),
));
_recentAlerts.add(RecentAlert(nodeId: node.id, alertTime: DateTime.now()));
debugPrint('[ProximityAlertService] Alert triggered for node ${node.id} ($nodeType) at ${distance.round()}m');
}
}
}
/// Notification IDs must fit in a signed 32-bit int, but OSM node IDs are
/// well past that (currently ~12 billion), so passing one through raises
/// "must fit within the size of a 32-bit integer" and the notification is
/// dropped. Fold to a stable positive 31-bit value instead.
///
/// Deterministic across runs, so re-alerting for the same node replaces the
/// existing notification rather than stacking a duplicate.
static int _notificationId(int nodeId) => nodeId.abs() % 0x7FFFFFFF;
/// Show push notification for proximity alert
Future<void> _showNotification(OsmNode node, String nodeType, int distance) async {
if (!_isInitialized || _notifications == null) return;
await _show(
id: _notificationId(node.id),
title: 'Surveillance Device Nearby',
body: '$nodeType detected ${distance}m ahead',
);
}
Future<void> _show({
required int id,
required String title,
required String body,
}) async {
if (!_pluginReady || _notifications == null) {
debugPrint('[ProximityAlertService] NOT SHOWN: plugin not ready');
return;
}
// A notification that silently no-ops because permission was never granted
// is indistinguishable from one that was never triggered. Say which.
if (!await areNotificationsEnabled()) {
debugPrint(
'[ProximityAlertService] NOT SHOWN: OS notification permission not '
'granted. Settings → Proximity Alerts → Enable Notifications.',
);
return;
}
const androidDetails = AndroidNotificationDetails(
'proximity_alerts',
'Proximity Alerts',
@@ -154,7 +218,13 @@ class ProximityAlertService {
);
const iosDetails = DarwinNotificationDetails(
// presentAlert is dead on iOS 14+: the plugin's willPresentNotification
// only consults presentBanner/presentList there and ignores presentAlert
// entirely. Setting just presentAlert produced no visible banner at all.
// Keep it for iOS 13 and below, but presentBanner is what actually works.
presentAlert: true,
presentBanner: true,
presentList: true,
presentBadge: false,
presentSound: true,
);
@@ -164,16 +234,16 @@ class ProximityAlertService {
iOS: iosDetails,
);
final title = 'Surveillance Device Nearby';
final body = '$nodeType detected ${distance}m ahead';
try {
await _notifications!.show(
node.id, // Use node ID as notification ID
id, // Use node ID as notification ID
title,
body,
notificationDetails,
);
debugPrint('[ProximityAlertService] SHOWN id=$id "$title" — $body');
} on ArgumentError catch (e) {
debugPrint('[ProximityAlertService] Rejected notification id=$id: $e');
} catch (e) {
debugPrint('[ProximityAlertService] Failed to show notification: $e');
}
@@ -226,30 +296,46 @@ class ProximityAlertService {
_recentAlerts.clear();
}
/// Check if notification permissions are granted
/// Check if notification permissions are granted.
Future<bool> areNotificationsEnabled() async {
if (!_isInitialized || _notifications == null) return false;
if (!await _ensureReady() || _notifications == null) return false;
try {
// Check Android permissions
final androidImpl = _notifications!
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
if (androidImpl != null) {
final result = await androidImpl.areNotificationsEnabled();
return result ?? false;
}
// For iOS, assume enabled if we got this far (permissions were requested during init)
return true;
// iOS: actually ask the system rather than assuming. The old code
// returned a blind `true` here, so the UI could never tell whether
// notifications were really authorized.
final iosImpl = _notifications!
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>();
if (iosImpl != null) {
final options = await iosImpl.checkPermissions();
if (options == null) return false;
return options.isEnabled || options.isProvisionalEnabled;
}
return false;
} catch (e) {
debugPrint('[ProximityAlertService] Failed to check notification permissions: $e');
return false;
}
}
/// Request permissions again (can be called from settings)
/// Request permissions and report whether they ended up granted.
///
/// A `false` result does NOT mean the prompt was declined just now — on iOS
/// the prompt may not have appeared at all because it was already answered
/// in a previous launch. Callers should offer [openSystemSettings] on false.
Future<bool> requestNotificationPermissions() async {
if (!await _ensureReady()) return false;
await _requestNotificationPermissions();
return await areNotificationsEnabled();
final enabled = await areNotificationsEnabled();
debugPrint('[ProximityAlertService] Permissions after request: $enabled');
return enabled;
}
}
@@ -58,13 +58,18 @@ class SuspectedLocationDatabase {
}
/// Create database tables
Future<void> _createTables(Database db, int version) async {
///
/// Takes a [DatabaseExecutor] (rather than [Database]) so this can be
/// called either directly on the database (e.g. from [onCreate]) or inside
/// a transaction (see [insertBatch]).
Future<void> _createTables(DatabaseExecutor db, int version) async {
debugPrint('[SuspectedLocationDatabase] Creating tables...');
// Main suspected locations table
await db.execute('''
CREATE TABLE $_tableName (
$_columnTicketNo TEXT PRIMARY KEY,
$_columnCentroidLat REAL NOT NULL,
$_columnCentroidLng REAL NOT NULL,
$_columnBounds TEXT,
+3 -3
View File
@@ -104,7 +104,7 @@ class Uploader {
// Create new node
final mergedTags = p.getCombinedTags();
final tagsXml = mergedTags.entries.map((e) =>
'<tag k="${e.key}" v="${e.value}"/>').join('\n ');
'<tag k="${_sanitizeXmlText(e.key)}" v="${_sanitizeXmlText(e.value)}"/>').join('\n ');
final nodeXml = '''
<osm>
<node changeset="$changesetId" lat="${p.coord.latitude}" lon="${p.coord.longitude}">
@@ -141,7 +141,7 @@ class Uploader {
// Update existing node with version
final mergedTags = p.getCombinedTags();
final tagsXml = mergedTags.entries.map((e) =>
'<tag k="${e.key}" v="${e.value}"/>').join('\n ');
'<tag k="${_sanitizeXmlText(e.key)}" v="${_sanitizeXmlText(e.value)}"/>').join('\n ');
final nodeXml = '''
<osm>
<node changeset="$changesetId" id="${p.originalNodeId}" version="$currentVersion" lat="${p.coord.latitude}" lon="${p.coord.longitude}">
@@ -190,7 +190,7 @@ class Uploader {
// Extract creates a new node with tags from the original node
final mergedTags = p.getCombinedTags();
final tagsXml = mergedTags.entries.map((e) =>
'<tag k="${e.key}" v="${e.value}"/>').join('\n ');
'<tag k="${_sanitizeXmlText(e.key)}" v="${_sanitizeXmlText(e.value)}"/>').join('\n ');
final nodeXml = '''
<osm>
<node changeset="$changesetId" lat="${p.coord.latitude}" lon="${p.coord.longitude}">
+49 -10
View File
@@ -1,22 +1,28 @@
import 'package:flutter/material.dart';
import '../services/osm_messages_service.dart';
import '../services/changeset_comments_service.dart';
import 'settings_state.dart';
/// State management for OSM message notifications
/// State management for OSM message and changeset comment notifications
class MessagesState extends ChangeNotifier {
final OSMMessagesService _messagesService = OSMMessagesService();
final ChangesetCommentsService _changesetCommentsService = ChangesetCommentsService();
int? _unreadCount;
int? _unreadChangesetId; // ID of a changeset with unread comments, if any
bool _isChecking = false;
// Getters
int? get unreadCount => _unreadCount;
bool get hasUnreadMessages => (_unreadCount ?? 0) > 0;
bool get hasUnreadChangesetComments => _unreadChangesetId != null;
bool get hasUnreadNotifications => hasUnreadMessages || hasUnreadChangesetComments;
bool get isChecking => _isChecking;
/// Check for unread messages
/// Check for unread messages and changeset comments
Future<void> checkMessages({
required String? accessToken,
required String? username,
required UploadMode uploadMode,
bool forceRefresh = false,
}) async {
@@ -26,18 +32,29 @@ class MessagesState extends ChangeNotifier {
notifyListeners();
try {
final count = await _messagesService.getUnreadMessageCount(
accessToken: accessToken,
uploadMode: uploadMode,
forceRefresh: forceRefresh,
);
final results = await Future.wait([
_messagesService.getUnreadMessageCount(
accessToken: accessToken,
uploadMode: uploadMode,
forceRefresh: forceRefresh,
),
_changesetCommentsService.getUnreadChangesetId(
username: username,
uploadMode: uploadMode,
forceRefresh: forceRefresh,
),
]);
if (_unreadCount != count) {
final count = results[0];
final unreadChangesetId = results[1];
if (_unreadCount != count || _unreadChangesetId != unreadChangesetId) {
_unreadCount = count;
_unreadChangesetId = unreadChangesetId;
notifyListeners();
}
} catch (e) {
// Silently handle errors - messages are not critical
// Silently handle errors - notifications are not critical
debugPrint('MessagesState: Error checking messages: $e');
} finally {
_isChecking = false;
@@ -45,6 +62,26 @@ class MessagesState extends ChangeNotifier {
}
}
/// URL of the changeset with unread comments, on OSM's website, or null
/// if there are no unread changeset comments.
String? getUnreadChangesetUrl(UploadMode uploadMode) {
final id = _unreadChangesetId;
if (id == null) return null;
return _changesetCommentsService.getChangesetUrl(id, uploadMode);
}
/// Mark changeset comments as read (called when user views the changeset on OSM)
Future<void> markChangesetCommentsRead({
required String? username,
required UploadMode uploadMode,
}) async {
await _changesetCommentsService.markRead(username: username, uploadMode: uploadMode);
if (_unreadChangesetId != null) {
_unreadChangesetId = null;
notifyListeners();
}
}
/// Get the URL to view messages
String getMessagesUrl(UploadMode uploadMode) {
return _messagesService.getMessagesUrl(uploadMode);
@@ -53,7 +90,9 @@ class MessagesState extends ChangeNotifier {
/// Clear message state (when user logs out or changes mode)
void clearMessages() {
_unreadCount = null;
_unreadChangesetId = null;
_messagesService.clearCache();
_changesetCommentsService.clearCache();
notifyListeners();
}
}
}
+46
View File
@@ -40,10 +40,15 @@ class SettingsState extends ChangeNotifier {
static const String _navigationAvoidanceDistancePrefsKey = 'navigation_avoidance_distance';
static const String _distanceUnitPrefsKey = 'distance_unit';
static const String _keepScreenAwakePrefsKey = 'keep_screen_awake';
static const String _hideZoomControlsPrefsKey = 'hide_zoom_controls';
static const String _offlineFeaturesEnabledPrefsKey = 'offline_features_enabled';
bool _offlineMode = false;
bool _pauseQueueProcessing = false;
bool _keepScreenAwake = false;
bool _hideZoomControls = false;
bool _offlineFeaturesEnabled = false;
int _maxNodes = kDefaultMaxNodes;
// Default must account for missing secrets (preview builds) even before init() runs
UploadMode _uploadMode = (kEnableDevelopmentModes || !kHasOsmSecrets) ? UploadMode.simulate : UploadMode.production;
@@ -68,7 +73,11 @@ class SettingsState extends ChangeNotifier {
bool get networkStatusIndicatorEnabled => _networkStatusIndicatorEnabled;
int get suspectedLocationMinDistance => _suspectedLocationMinDistance;
bool get keepScreenAwake => _keepScreenAwake;
bool get hideZoomControls => _hideZoomControls;
bool get offlineFeaturesEnabled => _offlineFeaturesEnabled;
List<TileProvider> get tileProviders => List.unmodifiable(_tileProviders);
String get selectedTileTypeId => _selectedTileTypeId;
int get navigationAvoidanceDistance => _navigationAvoidanceDistance;
DistanceUnit get distanceUnit => _distanceUnit;
@@ -144,7 +153,17 @@ class SettingsState extends ChangeNotifier {
// Load keep screen awake setting
_keepScreenAwake = prefs.getBool(_keepScreenAwakePrefsKey) ?? false;
// Load hide zoom controls setting
_hideZoomControls = prefs.getBool(_hideZoomControlsPrefsKey) ?? false;
// Load offline features enabled setting (defaults to false; migration
// for existing users with pre-existing offline area data lives in
// migrations.dart / migrate_2_10_5)
_offlineFeaturesEnabled = prefs.getBool(_offlineFeaturesEnabledPrefsKey) ?? false;
// Load upload mode (including migration from old test_mode bool)
if (prefs.containsKey(_uploadModePrefsKey)) {
final idx = prefs.getInt(_uploadModePrefsKey) ?? 0;
@@ -413,6 +432,33 @@ class SettingsState extends ChangeNotifier {
}
}
/// Set hide zoom controls enabled/disabled
Future<void> setHideZoomControls(bool enabled) async {
if (_hideZoomControls != enabled) {
_hideZoomControls = enabled;
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_hideZoomControlsPrefsKey, enabled);
notifyListeners();
}
}
/// Set the master "offline features enabled" toggle. When this is off,
/// offline areas (downloading, browsing, and using cached tiles/nodes) are
/// disabled entirely. Note: any cascading side effects (forcing offline
/// mode off, cancelling active downloads, prompting to delete existing
/// area data) are handled by the caller (see AppState.setOfflineFeaturesEnabled)
/// since those require access to services not owned by SettingsState.
Future<void> setOfflineFeaturesEnabled(bool enabled) async {
if (_offlineFeaturesEnabled != enabled) {
_offlineFeaturesEnabled = enabled;
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_offlineFeaturesEnabledPrefsKey, enabled);
notifyListeners();
}
}
/// Set distance for avoidance of nodes during navigation
Future<void> setNavigationAvoidanceDistance(int distance) async {
if (_navigationAvoidanceDistance != distance) {
+9 -38
View File
@@ -6,8 +6,8 @@ import 'package:latlong2/latlong.dart';
import '../models/pending_upload.dart';
import '../models/osm_node.dart';
import '../models/node_profile.dart';
import '../services/map_data_provider.dart';
import '../services/direction_submission_formatter.dart';
import '../services/uploader.dart';
import '../widgets/node_provider_with_cache.dart';
import '../dev_config.dart';
@@ -121,10 +121,10 @@ class UploadQueueState extends ChangeNotifier {
}
// Add a completed session to the upload queue
void addFromSession(AddNodeSession session, {required UploadMode uploadMode}) {
PendingUpload addFromSession(AddNodeSession session, {required UploadMode uploadMode}) {
final upload = PendingUpload(
coord: session.target!,
direction: _formatDirectionsForSubmission(session.directions, session.profile),
direction: DirectionSubmissionFormatter.format(session.directions, session.profile),
profile: session.profile!, // Safe to use ! because commitSession() checks for null
operatorProfile: session.operatorProfile,
refinedTags: session.refinedTags,
@@ -159,10 +159,11 @@ class UploadQueueState extends ChangeNotifier {
NodeProviderWithCache.instance.notifyListeners();
notifyListeners();
return upload;
}
// Add a completed edit session to the upload queue
void addFromEditSession(EditNodeSession session, {required UploadMode uploadMode}) {
PendingUpload addFromEditSession(EditNodeSession session, {required UploadMode uploadMode}) {
// Determine operation type and coordinates
final UploadOperation operation;
final LatLng coordToUse;
@@ -183,7 +184,7 @@ class UploadQueueState extends ChangeNotifier {
final upload = PendingUpload(
coord: coordToUse,
direction: _formatDirectionsForSubmission(session.directions, session.profile),
direction: DirectionSubmissionFormatter.format(session.directions, session.profile),
profile: session.profile!, // Safe to use ! because commitEditSession() checks for null
operatorProfile: session.operatorProfile,
refinedTags: session.refinedTags,
@@ -250,10 +251,11 @@ class UploadQueueState extends ChangeNotifier {
NodeProviderWithCache.instance.notifyListeners();
notifyListeners();
return upload;
}
// Add a node deletion to the upload queue
void addFromNodeDeletion(OsmNode node, {required UploadMode uploadMode, String? changesetComment}) {
PendingUpload addFromNodeDeletion(OsmNode node, {required UploadMode uploadMode, String? changesetComment}) {
final upload = PendingUpload(
coord: node.coord,
direction: node.directionDeg.isNotEmpty ? node.directionDeg.first : 0, // Direction not used for deletions but required for API
@@ -282,6 +284,7 @@ class UploadQueueState extends ChangeNotifier {
NodeProviderWithCache.instance.notifyListeners();
notifyListeners();
return upload;
}
void clearQueue() {
@@ -736,38 +739,6 @@ class UploadQueueState extends ChangeNotifier {
}
}
// Helper method to format multiple directions for submission, supporting profile FOV
dynamic _formatDirectionsForSubmission(List<double> directions, NodeProfile? profile) {
if (directions.isEmpty) return 0.0;
// If profile has FOV, convert center directions to range notation
if (profile?.fov != null && profile!.fov! > 0) {
final ranges = directions.map((center) =>
_formatDirectionWithFov(center, profile.fov!)
).toList();
return ranges.length == 1 ? ranges.first : ranges.join(';');
}
// No profile FOV: use original format (single number or semicolon-separated)
if (directions.length == 1) return directions.first;
return directions.map((d) => d.round().toString()).join(';');
}
// Convert a center direction and FOV to range notation (e.g., 180° center with 90° FOV -> "135-225")
String _formatDirectionWithFov(double center, double fov) {
// Handle 360-degree FOV as special case
if (fov >= 360) {
return '0-360';
}
final halfFov = fov / 2;
final start = (center - halfFov + 360) % 360;
final end = (center + halfFov) % 360;
return '${start.round()}-${end.round()}';
}
// Clean up pending nodes from cache when queue items are deleted/cleared
void _cleanupPendingNodeFromCache(PendingUpload upload) {
if (upload.isDeletion) {
+2 -98
View File
@@ -7,11 +7,11 @@ import 'package:flutter_map/flutter_map.dart';
import '../app_state.dart';
import '../dev_config.dart';
import '../models/node_profile.dart';
import '../models/pending_upload.dart';
import '../services/localization_service.dart';
import '../services/map_data_provider.dart';
import '../services/node_data_manager.dart';
import '../services/changelog_service.dart';
import '../services/edit_node_change_detector.dart';
import 'refine_tags_sheet.dart';
import 'advanced_edit_options_sheet.dart';
import 'proximity_warning_dialog.dart';
@@ -151,102 +151,6 @@ class _EditNodeSheetState extends State<EditNodeSheet> {
);
}
/// Check if the edit session has any actual changes compared to the original node
bool _hasActualChanges(EditNodeSession session) {
// Extract operation is always a change
if (session.extractFromWay) return true;
// Check location change
const double tolerance = 0.0000001; // ~1cm precision
if ((session.target.latitude - session.originalNode.coord.latitude).abs() > tolerance ||
(session.target.longitude - session.originalNode.coord.longitude).abs() > tolerance) {
return true;
}
// Check direction changes
if (!_directionsEqual(session.directions, session.originalNode.directionDeg)) {
return true;
}
// Check tag changes (including operator profile and additional existing tags)
final originalTags = session.originalNode.tags;
final newTags = _getSessionCombinedTags(session);
if (!_tagsEqual(originalTags, newTags)) {
return true;
}
return false;
}
/// Compare two direction lists, handling empty vs [0] cases
bool _directionsEqual(List<double> sessionDirs, List<double> originalDirs) {
// Sort both lists for comparison
final sorted1 = List<double>.from(sessionDirs)..sort();
final sorted2 = List<double>.from(originalDirs)..sort();
// Handle empty list cases
if (sorted1.isEmpty && sorted2.isEmpty) return true;
if (sorted1.isEmpty || sorted2.isEmpty) {
// Special case: if one is empty and the other is [0], consider them different
// because the user either added or removed a direction
return false;
}
if (sorted1.length != sorted2.length) return false;
for (int i = 0; i < sorted1.length; i++) {
if ((sorted1[i] - sorted2[i]).abs() > 0.1) return false; // 0.1° tolerance
}
return true;
}
/// Compare two tag maps, ignoring direction tags (handled separately)
bool _tagsEqual(Map<String, String> tags1, Map<String, String> tags2) {
final filtered1 = Map<String, String>.from(tags1);
final filtered2 = Map<String, String>.from(tags2);
// Remove direction tags - they're handled separately
filtered1.remove('direction');
filtered1.remove('camera:direction');
filtered2.remove('direction');
filtered2.remove('camera:direction');
return _mapEquals(filtered1, filtered2);
}
/// Deep equality check for maps
bool _mapEquals(Map<String, String> map1, Map<String, String> map2) {
if (map1.length != map2.length) return false;
for (final entry in map1.entries) {
if (map2[entry.key] != entry.value) return false;
}
return true;
}
/// Get the combined tags that would be submitted for this session
Map<String, String> _getSessionCombinedTags(EditNodeSession session) {
if (session.profile == null) return <String, String>{};
// Create a temporary PendingUpload to use its getCombinedTags logic
final tempUpload = PendingUpload(
coord: session.target,
direction: session.directions.isNotEmpty ? session.directions.first : 0.0,
profile: session.profile,
operatorProfile: session.operatorProfile,
refinedTags: session.refinedTags,
additionalExistingTags: session.additionalExistingTags, // Include additional existing tags!
changesetComment: session.changesetComment, // Required parameter
uploadMode: UploadMode.production, // Mode doesn't matter for tag combination
operation: UploadOperation.modify,
originalNodeId: session.originalNode.id, // Required for modify operations
);
return tempUpload.getCombinedTags();
}
/// Show dialog explaining why submission is disabled due to no changes
void _showNoChangesDialog(BuildContext context, LocalizationService locService) {
showDialog<void>(
@@ -436,7 +340,7 @@ class _EditNodeSheetState extends State<EditNodeSheet> {
void commit() {
// Check if there are any actual changes to submit
if (!_hasActualChanges(widget.session)) {
if (!EditNodeChangeDetector.hasActualChanges(widget.session)) {
_showNoChangesDialog(context, locService);
return;
}
@@ -0,0 +1,157 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../app_state.dart';
import '../dev_config.dart';
import '../services/localization_service.dart';
/// Applies a queue-pausing settings change (enabling offline mode or pausing
/// the upload queue), but if there's an in-flight submission (a queue item
/// that has already opened a changeset and hasn't closed it yet), first
/// shows a non-dismissible-by-tap-outside dialog explaining that the
/// submission needs to finish. Once it completes, a brief confirmation is
/// shown before the dialog auto-closes and the setting takes effect.
///
/// If nothing is in-flight, [applyChange] is invoked immediately with no
/// dialog shown at all.
///
/// The dialog can also be dismissed early by the user tapping "View in
/// Queue", in case something is stuck (e.g. a failed/erroring item) — this
/// lets the user navigate to the queue screen to investigate/clear it out,
/// rather than getting stuck waiting indefinitely.
Future<void> applyQueueSettingChangeRespectingInFlightUploads({
required BuildContext context,
required AppState appState,
required Future<void> Function() applyChange,
}) async {
if (!appState.hasInFlightUploads) {
await applyChange();
return;
}
await showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => InFlightUploadWaitDialog(
onAllComplete: () {
// Fire and forget - the dialog doesn't need to await this.
applyChange();
},
),
);
}
class InFlightUploadWaitDialog extends StatefulWidget {
/// Called exactly once, as soon as no queue items are actively processing.
final VoidCallback onAllComplete;
const InFlightUploadWaitDialog({super.key, required this.onAllComplete});
@override
State<InFlightUploadWaitDialog> createState() => _InFlightUploadWaitDialogState();
}
class _InFlightUploadWaitDialogState extends State<InFlightUploadWaitDialog> {
bool _completed = false;
bool _appliedChange = false;
Timer? _autoCloseTimer;
late final AppState _appState;
@override
void initState() {
super.initState();
_appState = AppState.instance;
_appState.addListener(_onAppStateChanged);
// Handle the (unlikely) race where the in-flight upload finishes between
// the initial check and this dialog actually mounting.
WidgetsBinding.instance.addPostFrameCallback((_) => _onAppStateChanged());
}
void _onAppStateChanged() {
if (!mounted || _completed) return;
if (_appState.hasInFlightUploads) return;
setState(() {
_completed = true;
});
if (!_appliedChange) {
_appliedChange = true;
widget.onAllComplete();
}
_autoCloseTimer = Timer(kInFlightUploadCompleteDisplayDuration, () {
if (mounted) {
Navigator.of(context, rootNavigator: true).pop();
}
});
}
@override
void dispose() {
_appState.removeListener(_onAppStateChanged);
_autoCloseTimer?.cancel();
super.dispose();
}
void _viewInQueue() {
Navigator.of(context, rootNavigator: true).pop();
Navigator.of(context).pushNamed('/settings/queue');
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: LocalizationService.instance,
builder: (context, child) {
final locService = LocalizationService.instance;
return PopScope(
canPop: false,
child: AlertDialog(
title: Row(
children: [
Icon(
_completed ? Icons.check_circle : Icons.cloud_upload,
color: _completed ? Colors.green : Theme.of(context).colorScheme.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
_completed
? locService.t('queue.inFlightCompleteTitle')
: locService.t('queue.inFlightWaitTitle'),
),
),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_completed
? locService.t('queue.inFlightCompleteMessage')
: locService.t('queue.inFlightWaitMessage'),
),
const SizedBox(height: 20),
Center(
child: _completed
? const Icon(Icons.check_circle, size: 40, color: Colors.green)
: const CircularProgressIndicator(),
),
],
),
actions: [
if (!_completed)
TextButton(
onPressed: _viewInQueue,
child: Text(locService.t('node.viewInQueue')),
),
],
),
);
},
);
}
}
+209 -20
View File
@@ -1,5 +1,6 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart' show LatLngBounds;
import 'package:flutter_map_animations/flutter_map_animations.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';
@@ -8,8 +9,11 @@ import 'package:flutter/foundation.dart' show defaultTargetPlatform, TargetPlatf
import '../../dev_config.dart';
import '../../app_state.dart' show FollowMeMode;
import '../../services/proximity_alert_service.dart';
import '../../services/coordinate_validation.dart';
import '../../services/localization_service.dart';
import '../../models/osm_node.dart';
import '../../models/node_profile.dart';
import '../../services/geo_bounds.dart';
/// Simple GPS controller that handles precise location permissions only.
/// Key principles:
@@ -19,7 +23,11 @@ import '../../models/node_profile.dart';
class GpsController {
StreamSubscription<Position>? _positionSub;
Timer? _retryTimer;
/// Whether the live stream was started with background delivery armed, so a
/// proximity-alerts toggle knows whether it actually needs to rebuild it.
bool _streamIsBackgroundCapable = false;
// Location state
LatLng? _currentLocation;
bool _hasLocation = false;
@@ -30,11 +38,15 @@ class GpsController {
FollowMeMode Function()? _getCurrentFollowMeMode;
bool Function()? _getProximityAlertsEnabled;
int Function()? _getProximityAlertDistance;
List<OsmNode> Function()? _getNearbyNodes;
List<OsmNode> Function(LatLng userLocation, int radiusMeters)? _getNearbyNodes;
List<NodeProfile> Function()? _getEnabledProfiles;
VoidCallback? _onMapMovedProgrammatically;
bool Function()? _isUserInteracting;
LatLngBounds? _backgroundTrackingBounds;
bool _isFetchingBackgroundNodes = false;
Future<void> Function(LatLngBounds)? _onFetchBackgroundNodes;
/// Get the current GPS location (if available)
LatLng? get currentLocation => _currentLocation;
@@ -48,8 +60,9 @@ class GpsController {
required FollowMeMode Function() getCurrentFollowMeMode,
required bool Function() getProximityAlertsEnabled,
required int Function() getProximityAlertDistance,
required List<OsmNode> Function() getNearbyNodes,
required List<OsmNode> Function(LatLng userLocation, int radiusMeters) getNearbyNodes,
required List<NodeProfile> Function() getEnabledProfiles,
Future<void> Function(LatLngBounds)? onFetchBackgroundNodes,
VoidCallback? onMapMovedProgrammatically,
bool Function()? isUserInteracting,
}) async {
@@ -63,6 +76,7 @@ class GpsController {
_getProximityAlertDistance = getProximityAlertDistance;
_getNearbyNodes = getNearbyNodes;
_getEnabledProfiles = getEnabledProfiles;
_onFetchBackgroundNodes = onFetchBackgroundNodes;
_onMapMovedProgrammatically = onMapMovedProgrammatically;
_isUserInteracting = isUserInteracting;
@@ -84,6 +98,38 @@ class GpsController {
_handleInitialFollowMeAnimation(newMode, oldMode);
}
/// Force a fresh fix, e.g. when the app returns from the background.
///
/// The position stream can stay silent after a resume — and a simulated
/// location that "teleported" while the app was suspended produces no
/// movement event at all — leaving _currentLocation stale, so proximity
/// alerts would keep evaluating against the old position.
Future<void> refreshLocation() async {
debugPrint('[GpsController] Refreshing location after resume');
// Restart the stream first: iOS often stops delivering to a subscription
// that spanned suspension.
if (_positionSub != null) {
_stopLocationTracking();
_startPositionStream();
}
try {
// geolocator 10.x: getCurrentPosition takes desiredAccuracy, unlike
// getPositionStream above which takes a LocationSettings object.
final position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
// Match the stream's forceLocationManager: true, so the one-shot and
// the stream cannot disagree about where we are on Android.
forceAndroidLocationManager: true,
timeLimit: const Duration(seconds: 10),
);
_onPositionReceived(position);
} catch (e) {
debugPrint('[GpsController] Failed to refresh location: $e');
}
}
/// Manual retry (e.g., user pressed follow-me button)
Future<void> retryLocationInit() async {
debugPrint('[GpsController] Manual retry of location initialization');
@@ -147,24 +193,29 @@ class GpsController {
final followMeMode = _getCurrentFollowMeMode?.call() ?? FollowMeMode.off;
final distanceFilter = followMeMode == FollowMeMode.off ? 5 : 1; // 5m normal, 1m follow-me
debugPrint('[GpsController] Starting GPS position stream (${distanceFilter}m filter)');
// Both platforms stop feeding a backgrounded app by default, which is why
// alerts only ever fired with the app on screen. Keeping the stream alive
// in the background is visible to the user (persistent notification on
// Android, blue status bar on iOS), so only ask for it when proximity
// alerts are actually switched on.
final background = _getProximityAlertsEnabled?.call() ?? false;
debugPrint(
'[GpsController] Starting GPS position stream '
'(${distanceFilter}m filter, background=$background)',
);
try {
_positionSub = Geolocator.getPositionStream(
locationSettings: defaultTargetPlatform == TargetPlatform.android
? AndroidSettings(
accuracy: LocationAccuracy.high,
distanceFilter: distanceFilter,
forceLocationManager: true,
)
: LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: distanceFilter,
),
locationSettings: _buildLocationSettings(
distanceFilter: distanceFilter,
background: background,
),
).listen(
_onPositionReceived,
onError: _onPositionError,
);
_streamIsBackgroundCapable = background;
} catch (e) {
debugPrint('[GpsController] Failed to start position stream: $e');
_hasLocation = false;
@@ -173,6 +224,79 @@ class GpsController {
}
}
/// Platform-specific location settings.
///
/// When [background] is false these are exactly the old foreground-only
/// settings, so nothing changes for users who leave proximity alerts off.
LocationSettings _buildLocationSettings({
required int distanceFilter,
required bool background,
}) {
final locService = LocalizationService.instance;
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidSettings(
accuracy: LocationAccuracy.high,
distanceFilter: distanceFilter,
forceLocationManager: true,
// Supplying this config is what makes geolocator run its
// GeolocatorLocationService as a foreground service. Without it
// Android throttles a backgrounded app to a few updates per hour and
// then stops entirely, so alerts never fire.
foregroundNotificationConfig: background
? ForegroundNotificationConfig(
notificationTitle:
locService.t('proximityAlerts.backgroundServiceTitle'),
notificationText:
locService.t('proximityAlerts.backgroundServiceText'),
notificationChannelName:
locService.t('proximityAlerts.backgroundServiceChannel'),
// Without a wake lock the system sleeps and delivers the
// queued positions in one burst on wake — far too late to warn
// anyone about a device they already drove past.
enableWakeLock: true,
setOngoing: true,
)
: null,
);
}
if (defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS) {
return AppleSettings(
accuracy: LocationAccuracy.high,
distanceFilter: distanceFilter,
// Pairs with UIBackgroundModes=location in Info.plist. Together they
// stop iOS from suspending the app on background, which is what killed
// the position stream (and therefore every alert) before.
allowBackgroundLocationUpdates: background,
// iOS otherwise pauses updates when it decides you have stopped moving
// and never reliably resumes them — a silent death for alerts.
pauseLocationUpdatesAutomatically: false,
// The blue status bar pill. Non-negotiable honesty: the app is reading
// location off screen and the user should be able to see that.
showBackgroundLocationIndicator: background,
activityType: ActivityType.otherNavigation,
);
}
return LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: distanceFilter,
);
}
/// Rebuild the stream when the proximity-alerts setting is toggled, so
/// background delivery is armed (or dropped) immediately rather than at the
/// next unrelated stream restart.
void updateProximityAlertsEnabled(bool enabled) {
if (_streamIsBackgroundCapable == enabled) return;
debugPrint('[GpsController] Proximity alerts $enabled — rebuilding stream');
_stopLocationTracking();
_startPositionStream();
}
/// Restart position stream with current follow-me settings
void _restartPositionStream() {
if (_positionSub == null) {
@@ -185,8 +309,65 @@ class GpsController {
_startPositionStream();
}
Future<void> _checkBackgroundDataRefresh(LatLng userLocation) async {
final proximityEnabled = _getProximityAlertsEnabled?.call() ?? false;
// Debug 1: Check the early return conditions
debugPrint('[GpsController-Background] proximityEnabled: $proximityEnabled, '
'onFetchBackgroundNodes null: ${_onFetchBackgroundNodes == null}, '
'isFetchingBackgroundNodes: $_isFetchingBackgroundNodes');
if (!proximityEnabled || _onFetchBackgroundNodes == null || _isFetchingBackgroundNodes) return;
bool needsRefresh = false;
if (_backgroundTrackingBounds == null) {
debugPrint('[GpsController-Background] Bounds are null. Triggering initial refresh.');
needsRefresh = true;
} else {
final bounds = _backgroundTrackingBounds!;
final northDist = Geolocator.distanceBetween(userLocation.latitude, userLocation.longitude, bounds.north, userLocation.longitude);
final southDist = Geolocator.distanceBetween(userLocation.latitude, userLocation.longitude, bounds.south, userLocation.longitude);
final eastDist = Geolocator.distanceBetween(userLocation.latitude, userLocation.longitude, userLocation.latitude, bounds.east);
final westDist = Geolocator.distanceBetween(userLocation.latitude, userLocation.longitude, userLocation.latitude, bounds.west);
final minDist = [northDist, southDist, eastDist, westDist].reduce((a, b) => a < b ? a : b);
// Debug 2: Print the closest distance to the edge
debugPrint('[GpsController-Background] Closest edge distance: ${minDist.toStringAsFixed(1)}m (Threshold: 2500m)');
if (minDist < 2500) {
debugPrint('[GpsController-Background] Threshold crossed. Triggering refresh.');
needsRefresh = true;
}
}
if (needsRefresh) {
_isFetchingBackgroundNodes = true;
try {
final newBounds = boundsAround(userLocation, 5000);
await _onFetchBackgroundNodes?.call(newBounds);
_backgroundTrackingBounds = newBounds;
debugPrint('[GpsController-Background] Successfully fetched and updated tracking bounds.');
} catch (e) {
debugPrint('[GpsController-Background] Background fetch failed: $e');
} finally {
_isFetchingBackgroundNodes = false;
}
}
}
/// Handle incoming GPS position
void _onPositionReceived(Position position) {
// Reject malformed fixes (occasionally NaN/Infinite from the platform
// location stack) before they reach map state.
if (!isValidLatitude(position.latitude) || !isValidLongitude(position.longitude)) {
debugPrint(
'[GpsController] Ignoring invalid GPS position: '
'lat=${position.latitude}, lng=${position.longitude}',
);
return;
}
final newLocation = LatLng(position.latitude, position.longitude);
_currentLocation = newLocation;
@@ -203,7 +384,8 @@ class GpsController {
// Handle proximity alerts
_checkProximityAlerts(newLocation);
_checkBackgroundDataRefresh(newLocation);
// Handle follow-me animations
_handleFollowMeUpdate(position, newLocation);
}
@@ -224,13 +406,19 @@ class GpsController {
void _checkProximityAlerts(LatLng userLocation) {
final proximityEnabled = _getProximityAlertsEnabled?.call() ?? false;
if (!proximityEnabled) return;
final nearbyNodes = _getNearbyNodes?.call() ?? [];
if (nearbyNodes.isEmpty) return;
final alertDistance = _getProximityAlertDistance?.call() ?? 200;
// Look up nodes around where the user actually is, not around whatever the
// map camera happens to show. Backgrounded, the camera never moves, so the
// old viewport-based lookup went stale the moment you drove out of it —
// and even in the foreground it missed alerts whenever the map was panned
// away from your position.
final nearbyNodes = _getNearbyNodes?.call(userLocation, alertDistance) ?? [];
if (nearbyNodes.isEmpty) return;
final enabledProfiles = _getEnabledProfiles?.call() ?? [];
ProximityAlertService().checkProximity(
userLocation: userLocation,
nodes: nearbyNodes,
@@ -362,6 +550,7 @@ class GpsController {
_getProximityAlertDistance = null;
_getNearbyNodes = null;
_getEnabledProfiles = null;
_onFetchBackgroundNodes = null;
_onMapMovedProgrammatically = null;
_isUserInteracting = null;
}
+65 -57
View File
@@ -17,6 +17,7 @@ class MapOverlays extends StatelessWidget {
final EditNodeSession? editSession;
final String? attribution; // Attribution for current tile provider
final VoidCallback? onSearchPressed; // Callback for search button
final bool hideZoomControls; // Hide zoom indicator + zoom in/out buttons
const MapOverlays({
super.key,
required this.mapController,
@@ -25,8 +26,10 @@ class MapOverlays extends StatelessWidget {
this.editSession,
this.attribution,
this.onSearchPressed,
this.hideZoomControls = false,
});
/// Show full attribution text in a dialog with license link.
void _showAttributionDialog(BuildContext context, String attribution) {
final locService = LocalizationService.instance;
@@ -138,35 +141,37 @@ class MapOverlays extends StatelessWidget {
),
// Zoom indicator, positioned relative to button bar with left safe area
Positioned(
left: leftPositionWithSafeArea(10, safeArea),
bottom: bottomPositionFromButtonBar(kZoomIndicatorSpacingAboveButtonBar, safeArea.bottom),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.52),
borderRadius: BorderRadius.circular(7),
),
child: Builder(
builder: (context) {
double zoom = 15.0; // fallback
try {
zoom = mapController.mapController.camera.zoom;
} catch (_) {
// Map controller not ready yet
}
return Text(
'Zoom: ${zoom.toStringAsFixed(2)}',
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w600,
),
);
},
if (!hideZoomControls)
Positioned(
left: leftPositionWithSafeArea(10, safeArea),
bottom: bottomPositionFromButtonBar(kZoomIndicatorSpacingAboveButtonBar, safeArea.bottom),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.52),
borderRadius: BorderRadius.circular(7),
),
child: Builder(
builder: (context) {
double zoom = 15.0; // fallback
try {
zoom = mapController.mapController.camera.zoom;
} catch (_) {
// Map controller not ready yet
}
return Text(
'Zoom: ${zoom.toStringAsFixed(2)}',
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w600,
),
);
},
),
),
),
),
// Attribution overlay, positioned relative to button bar with left safe area
if (attribution != null)
@@ -228,37 +233,40 @@ class MapOverlays extends StatelessWidget {
// Layer selector button
const LayerSelectorButton(),
const SizedBox(height: 8),
// Zoom in button
FloatingActionButton(
mini: true,
heroTag: "zoom_in",
onPressed: () {
try {
final zoom = mapController.mapController.camera.zoom;
mapController.mapController.move(mapController.mapController.camera.center, zoom + 1);
} catch (_) {
// Map controller not ready yet
}
},
child: const Icon(Icons.add),
),
const SizedBox(height: 8),
// Zoom out button
FloatingActionButton(
mini: true,
heroTag: "zoom_out",
onPressed: () {
try {
final zoom = mapController.mapController.camera.zoom;
mapController.mapController.move(mapController.mapController.camera.center, zoom - 1);
} catch (_) {
// Map controller not ready yet
}
},
child: const Icon(Icons.remove),
),
if (!hideZoomControls) ...[
const SizedBox(height: 8),
// Zoom in button
FloatingActionButton(
mini: true,
heroTag: "zoom_in",
onPressed: () {
try {
final zoom = mapController.mapController.camera.zoom;
mapController.mapController.move(mapController.mapController.camera.center, zoom + 1);
} catch (_) {
// Map controller not ready yet
}
},
child: const Icon(Icons.add),
),
const SizedBox(height: 8),
// Zoom out button
FloatingActionButton(
mini: true,
heroTag: "zoom_out",
onPressed: () {
try {
final zoom = mapController.mapController.camera.zoom;
mapController.mapController.move(mapController.mapController.camera.center, zoom - 1);
} catch (_) {
// Map controller not ready yet
}
},
child: const Icon(Icons.remove),
),
],
],
);
},
),
+11 -28
View File
@@ -3,6 +3,7 @@ import 'package:flutter_map_animations/flutter_map_animations.dart';
import 'package:latlong2/latlong.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../services/coordinate_validation.dart';
/// Manages map position persistence and initial positioning.
/// Handles saving/loading last map position and moving to initial locations.
@@ -29,9 +30,9 @@ class MapPositionManager {
final lng = prefs.getDouble('last_map_longitude');
final zoom = prefs.getDouble('last_map_zoom');
if (lat != null && lng != null &&
_isValidCoordinate(lat) && _isValidCoordinate(lng)) {
final validZoom = zoom != null && _isValidZoom(zoom) ? zoom : 15.0;
if (lat != null && lng != null &&
isValidLatitude(lat) && isValidLongitude(lng)) {
final validZoom = zoom != null && isValidZoom(zoom) ? zoom : 15.0;
_initialLocation = LatLng(lat, lng);
_initialZoom = validZoom;
debugPrint('[MapPositionManager] Loaded last map position: ${_initialLocation!.latitude}, ${_initialLocation!.longitude}, zoom: $_initialZoom');
@@ -50,9 +51,9 @@ class MapPositionManager {
try {
final zoom = _initialZoom ?? 15.0;
// Double-check coordinates are valid before moving
if (_isValidCoordinate(_initialLocation!.latitude) &&
_isValidCoordinate(_initialLocation!.longitude) &&
_isValidZoom(zoom)) {
if (isValidLatitude(_initialLocation!.latitude) &&
isValidLongitude(_initialLocation!.longitude) &&
isValidZoom(zoom)) {
controller.mapController.move(_initialLocation!, zoom);
_hasMovedToInitialLocation = true;
debugPrint('[MapPositionManager] Moved to initial location: ${_initialLocation!.latitude}, ${_initialLocation!.longitude}');
@@ -70,9 +71,9 @@ class MapPositionManager {
Future<void> saveMapPosition(LatLng location, double zoom) async {
try {
// Validate coordinates and zoom before saving
if (!_isValidCoordinate(location.latitude) ||
!_isValidCoordinate(location.longitude) ||
!_isValidZoom(zoom)) {
if (!isValidLatitude(location.latitude) ||
!isValidLongitude(location.longitude) ||
!isValidZoom(zoom)) {
debugPrint('[MapPositionManager] Invalid map position, not saving: lat=${location.latitude}, lng=${location.longitude}, zoom=$zoom');
return;
}
@@ -87,8 +88,6 @@ class MapPositionManager {
}
}
/// Clear any stored map position (useful for recovery from invalid data)
static Future<void> clearStoredMapPosition() async {
try {
@@ -101,20 +100,4 @@ class MapPositionManager {
debugPrint('[MapPositionManager] Failed to clear stored map position: $e');
}
}
/// Validate that a coordinate value is valid (not NaN, not infinite, within bounds)
bool _isValidCoordinate(double value) {
return !value.isNaN &&
!value.isInfinite &&
value >= -180.0 &&
value <= 180.0;
}
/// Validate that a zoom level is valid
bool _isValidZoom(double zoom) {
return !zoom.isNaN &&
!zoom.isInfinite &&
zoom >= 1.0 &&
zoom <= 25.0;
}
}
}
+108 -11
View File
@@ -7,6 +7,7 @@ import 'package:wakelock_plus/wakelock_plus.dart';
import '../app_state.dart' show AppState, FollowMeMode;
import '../services/offline_area_service.dart';
import '../services/geo_bounds.dart';
import '../models/osm_node.dart';
import '../models/suspected_location.dart';
@@ -26,9 +27,12 @@ import 'node_limit_indicator.dart';
import 'proximity_alert_banner.dart';
import '../dev_config.dart';
import '../services/proximity_alert_service.dart';
import '../services/coordinate_validation.dart';
import 'sheet_aware_map.dart';
import 'custom_scale_bar.dart';
class MapView extends StatefulWidget {
final AnimatedMapController controller;
const MapView({
@@ -61,7 +65,7 @@ class MapView extends StatefulWidget {
State<MapView> createState() => MapViewState();
}
class MapViewState extends State<MapView> {
class MapViewState extends State<MapView> with WidgetsBindingObserver {
late final AnimatedMapController _controller;
final Debouncer _cameraDebounce = Debouncer(kDebounceCameraRefresh);
final Debouncer _tileDebounce = Debouncer(const Duration(milliseconds: 150));
@@ -80,6 +84,13 @@ class MapViewState extends State<MapView> {
// Track map center to clear queue on significant panning
LatLng? _lastCenter;
// Last known-good camera center/zoom, used to self-heal if the camera
// ever gets pushed into an invalid state.
LatLng? _lastValidCenter;
double? _lastValidZoom;
// State for proximity alert banner
bool _showProximityBanner = false;
@@ -116,6 +127,8 @@ class MapViewState extends State<MapView> {
_dataManager = MapDataManager();
_interactionManager = MapInteractionManager();
WidgetsBinding.instance.addObserver(this);
// Initialize proximity alert service
ProximityAlertService().initialize(
onVisualAlert: () {
@@ -176,16 +189,16 @@ class MapViewState extends State<MapView> {
}
return 200;
},
getNearbyNodes: () {
getNearbyNodes: (userLocation, radiusMeters) {
if (mounted) {
try {
final LatLngBounds mapBounds;
try {
mapBounds = _controller.mapController.camera.visibleBounds;
} catch (_) {
return [];
}
return NodeProviderWithCache.instance.getCachedNodesForBounds(mapBounds);
// Deliberately not the map camera's visibleBounds: while the app
// is backgrounded the camera is frozen wherever the user left it,
// so a viewport lookup returns nodes from a place they may be
// miles from by now. Box around the live GPS position instead.
return NodeProviderWithCache.instance.getCachedNodesForBounds(
boundsAround(userLocation, radiusMeters),
);
} catch (e) {
debugPrint('[MapView] Could not get nearby nodes: $e');
return [];
@@ -204,6 +217,16 @@ class MapViewState extends State<MapView> {
}
return [];
},
onFetchBackgroundNodes: (bounds) async {
if (!mounted) return;
final appState = context.read<AppState>();
await NodeProviderWithCache.instance.fetchAndUpdate(
bounds: bounds,
profiles: appState.enabledProfiles,
uploadMode: appState.uploadMode,
);
},
onMapMovedProgrammatically: () {
// Refresh nodes when GPS controller moves the map
_refreshNodesFromProvider();
@@ -221,8 +244,18 @@ class MapViewState extends State<MapView> {
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// The position stream can go quiet across suspension, so pull a fresh fix
// rather than trusting the last one we saw before backgrounding.
if (state == AppLifecycleState.resumed) {
_gpsController.refreshLocation();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_cameraDebounce.dispose();
_tileDebounce.dispose();
_mapPositionDebounce.dispose();
@@ -275,6 +308,27 @@ class MapViewState extends State<MapView> {
return (!appState.offlineMode && appState.isInSearchMode) ? 60.0 : 0.0;
}
/// Known-good fallback location for [initialCenter]: validated GPS
/// location, then validated persisted position, then a hardcoded default.
LatLng get _safeInitialCenter {
final gpsLocation = _gpsController.currentLocation;
if (gpsLocation != null &&
isValidLatitude(gpsLocation.latitude) &&
isValidLongitude(gpsLocation.longitude)) {
return gpsLocation;
}
final persisted = _positionManager.initialLocation;
if (persisted != null &&
isValidLatitude(persisted.latitude) &&
isValidLongitude(persisted.longitude)) {
return persisted;
}
return LatLng(37.7749, -122.4194);
}
@override
void didUpdateWidget(covariant MapView oldWidget) {
@@ -298,6 +352,11 @@ class MapViewState extends State<MapView> {
// Keep screen awake based on user setting
_updateWakelock(appState.keepScreenAwake);
// Arm or drop background location delivery when the proximity alert
// setting is toggled. No-op when the stream already matches, same as
// _updateWakelock above.
_gpsController.updateProximityAlertsEnabled(appState.proximityAlertsEnabled);
// Check if enabled profiles changed and refresh nodes if needed
_nodeController.checkAndHandleProfileChanges(
currentEnabledProfiles: appState.enabledProfiles,
@@ -414,18 +473,47 @@ class MapViewState extends State<MapView> {
key: ValueKey('map_${appState.selectedTileProvider?.id ?? 'none'}_${appState.selectedTileType?.id ?? 'none'}_${appState.offlineMode}_${_tileManager.mapRebuildKey}'),
mapController: _controller.mapController,
options: MapOptions(
initialCenter: _gpsController.currentLocation ?? _positionManager.initialLocation ?? LatLng(37.7749, -122.4194),
initialCenter: _safeInitialCenter,
initialZoom: _positionManager.initialZoom ?? 15,
minZoom: 1.0,
maxZoom: (appState.selectedTileType?.maxZoom ?? 18).toDouble(),
interactionOptions: _interactionManager.getInteractionOptions(editSession),
onPositionChanged: (pos, gesture) {
// Self-heal if the camera center/zoom ever becomes invalid
// (observed to happen silently during ordinary panning,
// leaving a blank grey map with no tiles/markers). Snap back
// to the last known-good position immediately.
if (!isValidLatitude(pos.center.latitude) ||
!isValidLongitude(pos.center.longitude) ||
!isValidZoom(pos.zoom)) {
debugPrint(
'[MapView] Detected invalid camera position '
'(lat=${pos.center.latitude}, lng=${pos.center.longitude}, zoom=${pos.zoom}) '
'- snapping back to last known-good position',
);
final recoveryCenter = _lastValidCenter ?? _safeInitialCenter;
final recoveryZoom = _lastValidZoom ?? (_positionManager.initialZoom ?? 15.0);
WidgetsBinding.instance.addPostFrameCallback((_) {
try {
_controller.mapController.move(recoveryCenter, recoveryZoom);
} catch (e) {
debugPrint('[MapView] Failed to recover camera position: $e');
}
});
return; // Don't process this invalid position further
}
_lastValidCenter = pos.center;
_lastValidZoom = pos.zoom;
setState(() {}); // Instant UI update for zoom, etc.
if (gesture) {
widget.onUserGesture();
}
// Enforce minimum zoom level for add/edit node sheets (but not tag sheet)
if ((session != null || editSession != null) && pos.zoom < kMinZoomForNodeEditingSheets) {
// User tried to zoom out below minimum - snap back to minimum zoom
_controller.animateTo(
@@ -536,17 +624,24 @@ class MapViewState extends State<MapView> {
Builder(
builder: (context) {
final safeArea = MediaQuery.of(context).padding;
// When zoom controls (and the zoom level indicator) are hidden,
// shift the scale bar down into the indicator's old slot so we
// don't leave a weird empty gap above the attribution text.
final scaleBarSpacing = appState.hideZoomControls
? kZoomIndicatorSpacingAboveButtonBar
: kScaleBarSpacingAboveButtonBar;
return CustomScaleBar(
alignment: Alignment.bottomLeft,
padding: EdgeInsets.only(
left: leftPositionWithSafeArea(8, safeArea),
bottom: bottomPositionFromButtonBar(kScaleBarSpacingAboveButtonBar, safeArea.bottom),
bottom: bottomPositionFromButtonBar(scaleBarSpacing, safeArea.bottom),
),
maxWidthPx: 120,
barHeight: 8,
);
},
),
],
),
),
@@ -560,8 +655,10 @@ class MapViewState extends State<MapView> {
editSession: editSession,
attribution: appState.selectedTileType?.attribution,
onSearchPressed: widget.onSearchPressed,
hideZoomControls: appState.hideZoomControls,
),
// Node limit indicator (top-left) - shown when limit is active
Builder(
builder: (context) {
+19 -5
View File
@@ -17,6 +17,7 @@ class NodeProviderWithCache extends ChangeNotifier {
final NodeDataManager _nodeDataManager = NodeDataManager();
Timer? _debounceTimer;
Completer<void>? _activeCompleter;
/// Get cached nodes for the given bounds, filtered by enabled profiles
List<OsmNode> getCachedNodesForBounds(LatLngBounds bounds) {
@@ -34,14 +35,21 @@ class NodeProviderWithCache extends ChangeNotifier {
}
/// Fetch and update nodes for the given view, with debouncing for rapid map movement
void fetchAndUpdate({
Future<void> fetchAndUpdate({
required LatLngBounds bounds,
required List<NodeProfile> profiles,
UploadMode uploadMode = UploadMode.production,
}) {
// Serve cached immediately
notifyListeners();
// Prevent hanging awaits by completing the previous request if it gets cancelled
if (_activeCompleter != null && !_activeCompleter!.isCompleted) {
_activeCompleter!.complete();
}
_activeCompleter = Completer<void>();
// Debounce rapid panning/zooming
_debounceTimer?.cancel();
_debounceTimer = Timer(const Duration(milliseconds: 400), () async {
@@ -52,15 +60,21 @@ class NodeProviderWithCache extends ChangeNotifier {
uploadMode: uploadMode,
isUserInitiated: true,
);
// Notify UI of new data
notifyListeners();
} catch (e) {
debugPrint('[NodeProviderWithCache] Node fetch failed: $e');
// Cache already holds whatever is available for the view
} finally {
// Ensure we only complete if it hasn't been superseded by another call
if (_activeCompleter != null && !_activeCompleter!.isCompleted) {
_activeCompleter!.complete();
}
}
});
return _activeCompleter!.future;
}
/// Clear the cache and repopulate with pending nodes from upload queue
@@ -108,4 +122,4 @@ class NodeProviderWithCache extends ChangeNotifier {
}
return true;
}
}
}
+484 -80
View File
@@ -2,13 +2,17 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:collection/collection.dart';
import '../models/osm_node.dart';
import '../models/pending_upload.dart';
import '../services/map_data_provider.dart';
import '../app_state.dart';
import '../services/localization_service.dart';
import '../dev_config.dart';
import 'advanced_edit_options_sheet.dart';
class NodeTagSheet extends StatelessWidget {
class NodeTagSheet extends StatefulWidget {
final OsmNode node;
final VoidCallback? onEditPressed;
final bool isNodeLimitActive;
@@ -20,6 +24,88 @@ class NodeTagSheet extends StatelessWidget {
this.isNodeLimitActive = false,
});
@override
State<NodeTagSheet> createState() => _NodeTagSheetState();
}
class _NodeTagSheetState extends State<NodeTagSheet> {
// The PendingUpload backing this node (if it was in a pending state when the
// sheet was opened). We resolve this once and hold onto the object reference
// itself (not just its id) so we can keep observing its live status via its
// mutable fields even after it's eventually removed from the queue list
// (which happens ~1s after completion). Without this, once the item left
// the queue we'd have no way to tell "finished successfully" apart from
// "still pending" and would show stale/misleading status forever.
PendingUpload? _upload;
bool _uploadResolved = false;
@override
void initState() {
super.initState();
_resolveTrackedUpload();
}
void _resolveTrackedUpload() {
if (_uploadResolved) return;
_uploadResolved = true;
final appState = context.read<AppState>();
if (widget.node.tags['_pending_upload'] == 'true') {
_upload = appState.pendingUploads
.firstWhereOrNull((u) => u.tempNodeId == widget.node.id);
} else if (widget.node.tags['_pending_edit'] == 'true' ||
widget.node.tags['_pending_deletion'] == 'true') {
_upload = appState.pendingUploads
.firstWhereOrNull((u) => u.originalNodeId == widget.node.id);
}
}
/// Resolve the node data that should currently be displayed.
///
/// While an upload/edit/deletion is still in progress (or has failed), this
/// is just the snapshot that was passed in when the sheet was opened -
/// nothing has changed in the cache yet. Once the tracked upload completes,
/// we switch to the live node from the cache using the *real* submitted ID
/// (which can differ from the temporary negative "-epoch" ID for creates
/// and extracts, but matches the original ID for edits) so that tags, id,
/// and editability reflect reality instead of the stale pre-submission
/// snapshot. Returns null if the node has been deleted.
OsmNode? _resolveDisplayNode() {
final upload = _upload;
if (upload == null) {
// No tracked upload - either this node was never pending, or we
// couldn't find a matching queue entry (shouldn't normally happen).
// Try a live cache lookup so we still pick up any external updates,
// but fall back to the passed-in node if it's not (or no longer) cached.
return MapDataProvider().getNodeById(widget.node.id) ?? widget.node;
}
if (!upload.isComplete) {
// Still pending/in-progress/failed - nothing has changed yet.
return widget.node;
}
if (upload.isDeletion) {
return null; // Node has been deleted
}
// Upload completed successfully (create/modify/extract). Look up the
// live node using the real submitted ID (same as originalNodeId for
// modify operations, a brand-new positive ID for create/extract).
final realId = upload.submittedNodeId ?? widget.node.id;
final cached = MapDataProvider().getNodeById(realId);
if (cached != null) return cached;
// Fallback: cache might have already been cleared/replaced; reconstruct
// from the upload data directly so we don't fall back to stale pending
// tags/id.
return OsmNode(
id: realId,
coord: upload.coord,
tags: upload.getCombinedTags(),
);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
@@ -27,22 +113,30 @@ class NodeTagSheet extends StatelessWidget {
builder: (context, child) {
final appState = context.watch<AppState>();
final locService = LocalizationService.instance;
final upload = _upload;
final isDeleted = upload != null && upload.isComplete && upload.isDeletion;
final displayNode = isDeleted ? null : _resolveDisplayNode();
if (displayNode == null) {
return _buildDeletedSheet(context, locService);
}
// Check if this device is editable (not a pending upload, pending edit, or pending deletion)
final isEditable = (!node.tags.containsKey('_pending_upload') ||
node.tags['_pending_upload'] != 'true') &&
(!node.tags.containsKey('_pending_edit') ||
node.tags['_pending_edit'] != 'true') &&
(!node.tags.containsKey('_pending_deletion') ||
node.tags['_pending_deletion'] != 'true');
final isEditable = (!displayNode.tags.containsKey('_pending_upload') ||
displayNode.tags['_pending_upload'] != 'true') &&
(!displayNode.tags.containsKey('_pending_edit') ||
displayNode.tags['_pending_edit'] != 'true') &&
(!displayNode.tags.containsKey('_pending_deletion') ||
displayNode.tags['_pending_deletion'] != 'true');
// Check if this is a real OSM node (not pending) - for "View on OSM" button
final isRealOSMNode = !node.tags.containsKey('_pending_upload') &&
node.id > 0; // Real OSM nodes have positive IDs
final isRealOSMNode = !displayNode.tags.containsKey('_pending_upload') &&
displayNode.id > 0; // Real OSM nodes have positive IDs
void openEditSheet() {
// Check if node limit is active and warn user
if (isNodeLimitActive) {
if (widget.isNodeLimitActive) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
@@ -55,27 +149,52 @@ class NodeTagSheet extends StatelessWidget {
return;
}
if (onEditPressed != null) {
onEditPressed!(); // Use callback if provided
if (widget.onEditPressed != null) {
widget.onEditPressed!(); // Use callback if provided
} else {
// Fallback behavior
Navigator.pop(context); // Close this sheet first
appState.startEditSession(node); // HomeScreen will auto-show the edit sheet
appState.startEditSession(displayNode); // HomeScreen will auto-show the edit sheet
}
}
void deleteNode() async {
if (!appState.isLoggedIn) {
final shouldLogIn = await showDialog<bool>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text(locService.t('node.confirmDeleteTitle')),
content: Text(locService.t('node.mustBeLoggedInToDelete')),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text(locService.cancel),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text(locService.t('actions.logIn')),
),
],
),
);
if ((shouldLogIn ?? false) && context.mounted) {
Navigator.pushNamed(context, '/settings/osm-account');
}
return;
}
final result = await showDialog<({bool confirmed, String comment})>(
context: context,
builder: (BuildContext context) => _DeleteNodeDialog(
nodeId: node.id.toString(),
nodeId: displayNode.id.toString(),
locService: locService,
),
);
if ((result?.confirmed ?? false) && context.mounted) {
Navigator.pop(context); // Close this sheet first
appState.deleteNode(node, changesetComment: result!.comment);
appState.deleteNode(displayNode, changesetComment: result!.comment);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(locService.t('node.deleteQueuedForUpload'))),
);
@@ -83,7 +202,7 @@ class NodeTagSheet extends StatelessWidget {
}
void viewOnOSM() async {
final url = 'https://www.openstreetmap.org/node/${node.id}';
final url = 'https://www.openstreetmap.org/node/${displayNode.id}';
try {
final uri = Uri.parse(url);
if (await canLaunchUrl(uri)) {
@@ -108,10 +227,148 @@ class NodeTagSheet extends StatelessWidget {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => AdvancedEditOptionsSheet(node: node),
builder: (context) => AdvancedEditOptionsSheet(node: displayNode),
);
}
void viewInQueue() {
Navigator.pop(context); // Close this sheet first
Navigator.pushNamed(context, '/settings/queue');
}
Widget? uploadStatusBanner;
if (!isEditable) {
final IconData statusIcon;
final Color statusColor;
final String statusLabel;
final bool showSpinner;
final bool showQueueButton;
final state = upload?.uploadState;
if (state == null) {
// Fallback: tag says pending but we couldn't find a matching
// queue entry (shouldn't normally happen).
statusIcon = Icons.hourglass_empty;
statusColor = Colors.orange;
statusLabel = locService.t('node.uploadPending');
showSpinner = false;
showQueueButton = true;
} else {
switch (state) {
case UploadState.pending:
statusIcon = Icons.hourglass_empty;
statusColor = Colors.orange;
statusLabel = locService.t('node.uploadPending');
showSpinner = false;
showQueueButton = true;
break;
case UploadState.creatingChangeset:
statusIcon = Icons.cloud_upload_outlined;
statusColor = Colors.orange;
statusLabel = locService.t('node.uploadCreatingChangeset');
showSpinner = true;
showQueueButton = true;
break;
case UploadState.uploading:
statusIcon = Icons.cloud_upload_outlined;
statusColor = Colors.orange;
statusLabel = locService.t('node.uploadUploading');
showSpinner = true;
showQueueButton = true;
break;
case UploadState.closingChangeset:
statusIcon = Icons.cloud_upload_outlined;
statusColor = Colors.orange;
statusLabel = locService.t('node.uploadClosingChangeset');
showSpinner = true;
showQueueButton = true;
break;
case UploadState.error:
statusIcon = Icons.error_outline;
statusColor = Colors.red;
statusLabel = locService.t('node.uploadError');
showSpinner = false;
showQueueButton = true;
break;
case UploadState.complete:
statusIcon = Icons.check_circle_outline;
statusColor = Colors.green;
statusLabel = locService.t('node.uploadComplete');
showSpinner = false;
showQueueButton = false;
break;
}
}
uploadStatusBanner = Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: statusColor.withValues(alpha: 0.1),
border: Border.all(color: statusColor.withValues(alpha: 0.4)),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (showSpinner)
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
color: statusColor,
),
)
else
Icon(statusIcon, color: statusColor, size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(
statusLabel,
style: TextStyle(
color: statusColor,
fontWeight: FontWeight.w600,
),
),
),
],
),
if (state == UploadState.error &&
(upload?.errorMessage?.isNotEmpty ?? false)) ...[
const SizedBox(height: 4),
SelectableText(
upload!.errorMessage!,
style: TextStyle(
color: statusColor.withValues(alpha: 0.9),
fontSize: 12,
),
),
],
if (showQueueButton) ...[
const SizedBox(height: 4),
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: viewInQueue,
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
minimumSize: const Size(0, 28),
foregroundColor: statusColor,
),
child: Text(locService.t('node.viewInQueue')),
),
),
],
],
),
);
}
return LayoutBuilder(
builder: (context, constraints) {
return SafeArea(
@@ -122,78 +379,92 @@ class NodeTagSheet extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
locService.t('node.title').replaceAll('{}', node.id.toString()),
locService.t('node.title').replaceAll('{}', displayNode.id.toString()),
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 12),
?uploadStatusBanner,
// Tag list with flexible height constraint
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * getTagListHeightRatio(context),
),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...node.tags.entries.map(
(e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
e.key,
style: TextStyle(
fontWeight: FontWeight.w500,
color: Theme.of(context).colorScheme.onSurface,
),
),
const SizedBox(width: 8),
Expanded(
child: Linkify(
onOpen: (link) async {
final uri = Uri.parse(link.url);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${LocalizationService.instance.t('advancedEdit.couldNotOpenURL')}: ${link.url}')),
);
}
},
text: e.value,
child: SelectionArea(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
...displayNode.tags.entries
.where((e) => !e.key.startsWith('_')) // Hide internal bookkeeping tags
.map(
(e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
e.key,
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.7),
fontWeight: FontWeight.w500,
color: Theme.of(context).colorScheme.onSurface,
),
linkStyle: TextStyle(
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
options: const LinkifyOptions(humanize: false),
),
),
],
const SizedBox(width: 8),
Expanded(
child: Linkify(
onOpen: (link) async {
final uri = Uri.parse(link.url);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${LocalizationService.instance.t('advancedEdit.couldNotOpenURL')}: ${link.url}')),
);
}
},
text: e.value,
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.7),
),
linkStyle: TextStyle(
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
options: const LinkifyOptions(humanize: false),
),
),
],
),
),
),
),
],
],
),
),
),
),
const SizedBox(height: 16),
// First row: View and Advanced buttons
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
if (isRealOSMNode) ...[
TextButton.icon(
OutlinedButton.icon(
onPressed: () => viewOnOSM(),
icon: const Icon(Icons.open_in_new, size: 16),
icon: const Icon(Icons.open_in_new, size: 18),
label: Text(locService.t('actions.viewOnOSM')),
style: OutlinedButton.styleFrom(
minimumSize: const Size(0, 36),
),
),
const SizedBox(width: 8),
],
if (isEditable) ...[
OutlinedButton.icon(
onPressed: openAdvancedEdit,
@@ -222,12 +493,12 @@ class NodeTagSheet extends StatelessWidget {
),
const SizedBox(width: 8),
ElevatedButton.icon(
onPressed: node.isConstrained ? null : deleteNode,
onPressed: displayNode.isConstrained ? null : deleteNode,
icon: const Icon(Icons.delete, size: 18),
label: Text(locService.t('actions.delete')),
style: ElevatedButton.styleFrom(
minimumSize: const Size(0, 36),
foregroundColor: node.isConstrained ? null : Colors.red,
foregroundColor: displayNode.isConstrained ? null : Colors.red,
),
),
const SizedBox(width: 12),
@@ -247,6 +518,103 @@ class NodeTagSheet extends StatelessWidget {
},
);
}
/// Shown when the tracked upload was a deletion that has now completed -
/// the underlying node no longer exists, so we can't show tags or offer
/// edit/delete actions on it anymore.
Widget _buildDeletedSheet(BuildContext context, LocalizationService locService) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
locService.t('node.title').replaceAll('{}', widget.node.id.toString()),
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.1),
border: Border.all(color: Colors.green.withValues(alpha: 0.4)),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
const Icon(Icons.check_circle_outline, color: Colors.green, size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(
locService.t('node.deletedSuccessfully'),
style: const TextStyle(
color: Colors.green,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(locService.t('actions.close')),
),
],
),
],
),
),
);
}
}
enum _DeleteReason {
deviceRemoved,
duplicateNode,
misidentifiedInfra,
spamVandalism,
custom,
}
extension _DeleteReasonLabel on _DeleteReason {
String label(LocalizationService locService) {
switch (this) {
case _DeleteReason.deviceRemoved:
return locService.t('node.deleteReasonDeviceRemoved');
case _DeleteReason.duplicateNode:
return locService.t('node.deleteReasonDuplicateNode');
case _DeleteReason.misidentifiedInfra:
return locService.t('node.deleteReasonMisidentifiedInfra');
case _DeleteReason.spamVandalism:
return locService.t('node.deleteReasonSpamVandalism');
case _DeleteReason.custom:
return locService.t('node.deleteReasonCustom');
}
}
/// The text used to build the changeset comment (kept in English/consistent
/// regardless of UI language, matching prior app behavior for uploads).
String get commentText {
switch (this) {
case _DeleteReason.deviceRemoved:
return 'device removed';
case _DeleteReason.duplicateNode:
return 'duplicate node';
case _DeleteReason.misidentifiedInfra:
return 'misidentified infra';
case _DeleteReason.spamVandalism:
return 'spam/vandalism';
case _DeleteReason.custom:
return '';
}
}
}
class _DeleteNodeDialog extends StatefulWidget {
@@ -264,6 +632,7 @@ class _DeleteNodeDialog extends StatefulWidget {
class _DeleteNodeDialogState extends State<_DeleteNodeDialog> {
late final TextEditingController _commentController;
_DeleteReason? _selectedReason;
@override
void initState() {
@@ -277,6 +646,14 @@ class _DeleteNodeDialogState extends State<_DeleteNodeDialog> {
super.dispose();
}
bool get _canConfirm {
if (_selectedReason == null) return false;
if (_selectedReason == _DeleteReason.custom) {
return _commentController.text.trim().isNotEmpty;
}
return true;
}
@override
Widget build(BuildContext context) {
return AlertDialog(
@@ -292,16 +669,39 @@ class _DeleteNodeDialogState extends State<_DeleteNodeDialog> {
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
TextField(
controller: _commentController,
decoration: InputDecoration(
hintText: widget.locService.t('node.deleteReasonHint'),
border: const OutlineInputBorder(),
DropdownButtonFormField<_DeleteReason>(
initialValue: _selectedReason,
hint: Text(widget.locService.t('node.deleteReasonSelectHint')),
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: true,
),
maxLines: 2,
textCapitalization: TextCapitalization.sentences,
items: _DeleteReason.values
.map((reason) => DropdownMenuItem(
value: reason,
child: Text(reason.label(widget.locService)),
))
.toList(),
onChanged: (reason) {
setState(() {
_selectedReason = reason;
});
},
),
if (_selectedReason == _DeleteReason.custom) ...[
const SizedBox(height: 8),
TextField(
controller: _commentController,
decoration: InputDecoration(
hintText: widget.locService.t('node.deleteReasonHint'),
border: const OutlineInputBorder(),
isDense: true,
),
maxLines: 2,
textCapitalization: TextCapitalization.sentences,
onChanged: (_) => setState(() {}),
),
],
],
),
actions: [
@@ -310,17 +710,21 @@ class _DeleteNodeDialogState extends State<_DeleteNodeDialog> {
child: Text(widget.locService.cancel),
),
TextButton(
onPressed: () {
final comment = _commentController.text.trim();
final finalComment = comment.isEmpty
? 'Delete a surveillance node'
: 'Delete a surveillance node: $comment';
Navigator.of(context).pop((confirmed: true, comment: finalComment));
},
onPressed: _canConfirm
? () {
final reasonText = _selectedReason == _DeleteReason.custom
? _commentController.text.trim()
: _selectedReason!.commentText;
final finalComment = reasonText.isEmpty
? 'Delete a surveillance node'
: 'Delete a surveillance node: $reasonText';
Navigator.of(context).pop((confirmed: true, comment: finalComment));
}
: null,
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: Text(widget.locService.t('actions.delete')),
),
],
);
}
}
}
@@ -0,0 +1,54 @@
import 'package:flutter/material.dart';
import '../services/localization_service.dart';
/// Dialog shown once per session when the user has unread OSM messages
/// and/or unread changeset comments, prompting them to view their OSM
/// account details.
class UnreadNotificationsDialog extends StatelessWidget {
final VoidCallback onView;
final VoidCallback onDismiss;
const UnreadNotificationsDialog({
super.key,
required this.onView,
required this.onDismiss,
});
@override
Widget build(BuildContext context) {
final locService = LocalizationService.instance;
return AlertDialog(
title: Row(
children: [
Icon(
Icons.notifications_active_outlined,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(locService.t('auth.unreadNotificationsTitle')),
),
],
),
content: Text(locService.t('auth.unreadNotificationsMessage')),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
onDismiss();
},
child: Text(locService.t('auth.reauthLater')),
),
FilledButton.icon(
onPressed: () {
Navigator.of(context).pop();
onView();
},
icon: const Icon(Icons.arrow_forward, size: 18),
label: Text(locService.t('auth.unreadNotificationsView')),
),
],
);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
name: deflockapp
description: Map public surveillance infrastructure with OpenStreetMap
publish_to: "none"
version: 2.10.2+57 # The thing after the + is the version code, incremented with each release
version: 2.11.1+62 # The thing after the + is the version code, incremented with each release
environment:
sdk: ">=3.10.3 <4.0.0" # Resolved dependency floor (Dart 3.10.3 = Flutter 3.38+)
+221
View File
@@ -0,0 +1,221 @@
#!/usr/bin/env python3
"""
localize.py — small helper for managing lib/localizations/*.json translation files.
Usage (normally invoked via scripts/localize.sh):
localize.sh --check
Validate that every locale file is valid JSON, has a language.name key,
and has exactly the same set of leaf keys as en.json (the reference).
Exits non-zero (and prints details) if anything doesn't match.
localize.sh --list [--lang xx]
Print all dot-notation leaf keys. Defaults to en.json if --lang is
omitted. Useful for seeing the full key structure at a glance.
localize.sh --get --lang xx --key some.nested.key
Print the value of a single key from lib/localizations/xx.json.
localize.sh --write --lang xx --key some.nested.key "New value"
Set (or add) the value of a key in lib/localizations/xx.json. Creates
intermediate objects as needed. Preserves key order/formatting via
Python's json module (2-space indent, matching existing files).
Examples:
./scripts/localize.sh --check
./scripts/localize.sh --list --lang de
./scripts/localize.sh --get --lang en --key node.title
./scripts/localize.sh --write --lang es --key node.checkingNodeStatusTitle "Comprobando estado"
"""
import argparse
import json
import sys
from pathlib import Path
LOCALIZATIONS_DIR = Path(__file__).resolve().parent.parent / "lib" / "localizations"
REFERENCE_LOCALE = "en"
def locale_path(lang: str) -> Path:
return LOCALIZATIONS_DIR / f"{lang}.json"
def load_locale(lang: str) -> dict:
path = locale_path(lang)
if not path.exists():
print(f"error: no such locale file: {path}", file=sys.stderr)
sys.exit(1)
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except json.JSONDecodeError as e:
print(f"error: {path.name} is not valid JSON: {e}", file=sys.stderr)
sys.exit(1)
def save_locale(lang: str, data: dict) -> None:
path = locale_path(lang)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
def all_locale_files():
return sorted(LOCALIZATIONS_DIR.glob("*.json"))
def extract_leaf_keys(data, prefix=""):
keys = set()
for k, v in data.items():
full_key = f"{prefix}.{k}" if prefix else k
if isinstance(v, dict):
keys |= extract_leaf_keys(v, full_key)
else:
keys.add(full_key)
return keys
def get_nested(data: dict, dotted_key: str):
parts = dotted_key.split(".")
node = data
for part in parts:
if not isinstance(node, dict) or part not in node:
return None
node = node[part]
return node
def set_nested(data: dict, dotted_key: str, value: str) -> None:
parts = dotted_key.split(".")
node = data
for part in parts[:-1]:
if part not in node or not isinstance(node[part], dict):
node[part] = {}
node = node[part]
node[parts[-1]] = value
def cmd_check(_args) -> int:
files = all_locale_files()
if not files:
print(f"error: no locale files found in {LOCALIZATIONS_DIR}", file=sys.stderr)
return 1
ref_path = locale_path(REFERENCE_LOCALE)
if not ref_path.exists():
print(f"error: reference locale '{REFERENCE_LOCALE}.json' not found", file=sys.stderr)
return 1
ok = True
parsed = {}
for path in files:
try:
with open(path, "r", encoding="utf-8") as f:
parsed[path.stem] = json.load(f)
except json.JSONDecodeError as e:
print(f"FAIL {path.name}: invalid JSON: {e}")
ok = False
for lang, data in parsed.items():
lang_name = data.get("language", {}).get("name")
if not isinstance(lang_name, str) or not lang_name:
print(f"FAIL {lang}.json: missing 'language.name' string")
ok = False
if REFERENCE_LOCALE not in parsed:
print(f"error: {REFERENCE_LOCALE}.json failed to parse, cannot compare keys")
return 1
reference_keys = extract_leaf_keys(parsed[REFERENCE_LOCALE])
for lang, data in parsed.items():
if lang == REFERENCE_LOCALE:
continue
keys = extract_leaf_keys(data)
missing = reference_keys - keys
extra = keys - reference_keys
if missing:
print(f"FAIL {lang}.json: missing {len(missing)} key(s):")
for k in sorted(missing):
print(f" - {k}")
ok = False
if extra:
print(f"FAIL {lang}.json: has {len(extra)} extra key(s) not in {REFERENCE_LOCALE}.json:")
for k in sorted(extra):
print(f" + {k}")
ok = False
if ok:
print(f"OK {len(parsed)} locale file(s) valid, all keys match {REFERENCE_LOCALE}.json")
return 0
return 1
def cmd_list(args) -> int:
lang = args.lang or REFERENCE_LOCALE
data = load_locale(lang)
keys = sorted(extract_leaf_keys(data))
for k in keys:
print(k)
return 0
def cmd_get(args) -> int:
if not args.lang or not args.key:
print("error: --get requires --lang and --key", file=sys.stderr)
return 1
data = load_locale(args.lang)
value = get_nested(data, args.key)
if value is None:
print(f"error: key '{args.key}' not found in {args.lang}.json", file=sys.stderr)
return 1
if isinstance(value, dict):
print(f"error: '{args.key}' is not a leaf key (it's an object) in {args.lang}.json", file=sys.stderr)
return 1
print(value)
return 0
def cmd_write(args) -> int:
if not args.lang or not args.key or args.value is None:
print("error: --write requires --lang, --key, and a value argument", file=sys.stderr)
return 1
data = load_locale(args.lang)
set_nested(data, args.key, args.value)
save_locale(args.lang, data)
print(f"Wrote {args.lang}.json: {args.key} = {args.value!r}")
return 0
def main():
parser = argparse.ArgumentParser(
description="Manage DeFlock localization JSON files.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--check", action="store_true", help="Validate all locale files match en.json's key structure")
group.add_argument("--list", action="store_true", help="List all dot-notation leaf keys for a locale (default: en)")
group.add_argument("--get", action="store_true", help="Print the value of a single key")
group.add_argument("--write", action="store_true", help="Set the value of a single key")
parser.add_argument("--lang", help="Language code, e.g. 'en', 'de', 'es' (filename without .json)")
parser.add_argument("--key", help="Dot-notation key, e.g. 'node.title'")
parser.add_argument("value", nargs="?", help="New value (only used with --write)")
args = parser.parse_args()
if args.check:
sys.exit(cmd_check(args))
elif args.list:
sys.exit(cmd_list(args))
elif args.get:
sys.exit(cmd_get(args))
elif args.write:
sys.exit(cmd_write(args))
if __name__ == "__main__":
main()
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Thin wrapper around localize.py — see that file's docstring for full usage.
#
# Examples:
# ./scripts/localize.sh --check
# ./scripts/localize.sh --list --lang de
# ./scripts/localize.sh --get --lang en --key node.title
# ./scripts/localize.sh --write --lang es --key node.checkingNodeStatusTitle "Comprobando estado"
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_BIN="${PYTHON_BIN:-python3}"
exec "$PYTHON_BIN" "$SCRIPT_DIR/localize.py" "$@"
@@ -0,0 +1,72 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:deflockapp/services/coordinate_validation.dart';
void main() {
group('isValidLatitude', () {
test('accepts in-range values', () {
expect(isValidLatitude(0), isTrue);
expect(isValidLatitude(37.7749), isTrue);
expect(isValidLatitude(90), isTrue);
expect(isValidLatitude(-90), isTrue);
});
test('rejects NaN and Infinite', () {
expect(isValidLatitude(double.nan), isFalse);
expect(isValidLatitude(double.infinity), isFalse);
expect(isValidLatitude(double.negativeInfinity), isFalse);
});
test('rejects out-of-range values', () {
expect(isValidLatitude(90.1), isFalse);
expect(isValidLatitude(-90.1), isFalse);
});
});
group('isValidLongitude', () {
test('accepts in-range values', () {
expect(isValidLongitude(0), isTrue);
expect(isValidLongitude(-122.4194), isTrue);
expect(isValidLongitude(180), isTrue);
expect(isValidLongitude(-180), isTrue);
});
test('rejects NaN and Infinite', () {
expect(isValidLongitude(double.nan), isFalse);
expect(isValidLongitude(double.infinity), isFalse);
expect(isValidLongitude(double.negativeInfinity), isFalse);
});
test('rejects out-of-range values', () {
expect(isValidLongitude(180.1), isFalse);
expect(isValidLongitude(-180.1), isFalse);
});
});
group('isValidZoom', () {
test('accepts in-range values (default bounds: 1.0 to kAbsoluteMaxZoom)', () {
expect(isValidZoom(1), isTrue);
expect(isValidZoom(15), isTrue);
expect(isValidZoom(23), isTrue);
});
test('rejects NaN and Infinite', () {
expect(isValidZoom(double.nan), isFalse);
expect(isValidZoom(double.infinity), isFalse);
expect(isValidZoom(double.negativeInfinity), isFalse);
});
test('rejects out-of-range values with default bounds', () {
expect(isValidZoom(0), isFalse);
expect(isValidZoom(0.5), isFalse);
expect(isValidZoom(24), isFalse);
});
test('respects custom min/max bounds', () {
expect(isValidZoom(0.5, min: 1.0, max: 20.0), isFalse);
expect(isValidZoom(1.0, min: 1.0, max: 20.0), isTrue);
expect(isValidZoom(20.0, min: 1.0, max: 20.0), isTrue);
expect(isValidZoom(20.1, min: 1.0, max: 20.0), isFalse);
});
});
}
@@ -41,8 +41,11 @@ void main() {
mockAppState = MockAppState();
AppState.instance = mockAppState;
// Default stubs: online, no offline areas
// Default stubs: online, no offline areas, offline features enabled
// (so tests exercise the same behavior as before this setting existed)
when(() => mockAppState.offlineMode).thenReturn(false);
when(() => mockAppState.offlineFeaturesEnabled).thenReturn(true);
provider = DeflockTileProvider(
providerId: 'openstreetmap',
@@ -0,0 +1,73 @@
import 'package:deflockapp/models/node_profile.dart';
import 'package:deflockapp/models/osm_node.dart';
import 'package:deflockapp/services/edit_node_change_detector.dart';
import 'package:deflockapp/state/session_state.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:latlong2/latlong.dart';
void main() {
group('EditNodeChangeDetector direction serialization', () {
test(
'detects changing a range direction to a single direction with the same center',
() {
final session = _sessionFor(
originalDirection: '55-125',
profileFov: null,
);
expect(
EditNodeChangeDetector.hasActualChanges(session),
isTrue,
reason: 'direction=55-125 serializes differently from direction=90',
);
},
);
test('treats an unchanged range direction as unchanged', () {
final session = _sessionFor(originalDirection: '55-125', profileFov: 70);
expect(EditNodeChangeDetector.hasActualChanges(session), isFalse);
});
test('treats an unchanged single direction as unchanged', () {
final session = _sessionFor(originalDirection: '90', profileFov: null);
expect(EditNodeChangeDetector.hasActualChanges(session), isFalse);
});
test('treats an unchanged directionless node as unchanged', () {
final session = _sessionFor(originalDirection: null, profileFov: null)
..directions = <double>[]
..currentDirectionIndex = -1;
expect(EditNodeChangeDetector.hasActualChanges(session), isFalse);
});
});
}
EditNodeSession _sessionFor({
required String? originalDirection,
required double? profileFov,
}) {
const coord = LatLng(37.7749, -122.4194);
final node = OsmNode(
id: 157,
coord: coord,
tags: {'man_made': 'surveillance', 'direction': ?originalDirection},
);
final profile = NodeProfile(
id: 'existing-tags-157',
name: 'Existing tags',
tags: const {},
fov: profileFov,
);
return EditNodeSession(
originalNode: node,
originalHadDirections: originalDirection != null,
profile: profile,
initialDirection: 90,
target: coord,
additionalExistingTags: const {'man_made': 'surveillance'},
);
}
+88
View File
@@ -0,0 +1,88 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';
import 'package:deflockapp/services/geo_bounds.dart';
/// Real-world distance from a bounds edge back to its center, so the box can be
/// checked in meters rather than in degrees.
double _metersBetween(LatLng a, LatLng b) => Geolocator.distanceBetween(
a.latitude,
a.longitude,
b.latitude,
b.longitude,
);
void main() {
group('boundsAround', () {
test('contains the center', () {
const center = LatLng(38.9, -77.0);
final bounds = boundsAround(center, 200);
expect(bounds.contains(center), isTrue);
});
test('reaches at least the requested radius north/south and east/west', () {
const center = LatLng(38.9, -77.0);
const radius = 500;
final bounds = boundsAround(center, radius);
final north = _metersBetween(center, LatLng(bounds.north, center.longitude));
final south = _metersBetween(center, LatLng(bounds.south, center.longitude));
final east = _metersBetween(center, LatLng(center.latitude, bounds.east));
final west = _metersBetween(center, LatLng(center.latitude, bounds.west));
for (final reach in [north, south, east, west]) {
// At least the radius, and not wildly oversized (the box is a square,
// so its corners legitimately overshoot, but its edges should not).
expect(reach, greaterThanOrEqualTo(radius * 0.98));
expect(reach, lessThan(radius * 1.2));
}
});
test('widens longitude at high latitude to keep the real radius', () {
const radius = 1000;
final equator = boundsAround(const LatLng(0, 0), radius);
final far = boundsAround(const LatLng(64.0, 0), radius);
final equatorLngSpan = equator.east - equator.west;
final farLngSpan = far.east - far.west;
// cos(64°) ≈ 0.438, so the degree span must be roughly 2.3x wider.
expect(farLngSpan, greaterThan(equatorLngSpan * 2));
// ...and that wider span should still be ~1000m on the ground.
final reach = _metersBetween(
const LatLng(64.0, 0),
LatLng(64.0, far.east),
);
expect(reach, greaterThanOrEqualTo(radius * 0.98));
expect(reach, lessThan(radius * 1.2));
});
test('does not blow past the poles or the antimeridian', () {
for (final center in [
const LatLng(89.99, 179.99),
const LatLng(-89.99, -179.99),
]) {
final bounds = boundsAround(center, 100000);
expect(bounds.north, lessThanOrEqualTo(90.0));
expect(bounds.south, greaterThanOrEqualTo(-90.0));
expect(bounds.east, lessThanOrEqualTo(180.0));
expect(bounds.west, greaterThanOrEqualTo(-180.0));
}
});
test('a zero radius still yields usable bounds containing the center', () {
const center = LatLng(38.9, -77.0);
final bounds = boundsAround(center, 0);
expect(bounds.contains(center), isTrue);
});
test('grows with the alert distance', () {
const center = LatLng(38.9, -77.0);
final near = boundsAround(center, 100);
final far = boundsAround(center, 1600);
expect(far.north - far.south, greaterThan(near.north - near.south));
});
});
}
+48
View File
@@ -0,0 +1,48 @@
import 'package:flutter_test/flutter_test.dart';
/// Mirrors ProximityAlertService._notificationId. Kept in sync deliberately:
/// the real one is private, and this pins the contract the plugin enforces —
/// notification ids must fit in a signed 32-bit int.
int notificationId(int nodeId) => nodeId.abs() % 0x7FFFFFFF;
const int maxInt32 = 2147483647;
void main() {
group('notificationId', () {
test('folds real-world OSM node ids into 32-bit range', () {
// The id from the crash, plus ids around the current OSM high-water mark.
const ids = [
12741890927,
1,
2147483647,
2147483648,
9999999999,
13000000000,
];
for (final id in ids) {
final result = notificationId(id);
expect(result, greaterThanOrEqualTo(0), reason: 'id $id went negative');
expect(result, lessThanOrEqualTo(maxInt32), reason: 'id $id overflowed');
}
});
test('handles negative ids, which OSM uses for not-yet-uploaded nodes', () {
for (final id in [-1, -12741890927, -2147483648]) {
final result = notificationId(id);
expect(result, greaterThanOrEqualTo(0));
expect(result, lessThanOrEqualTo(maxInt32));
}
});
test('is deterministic, so a repeat alert replaces rather than stacks', () {
expect(notificationId(12741890927), notificationId(12741890927));
});
test('separates adjacent node ids', () {
final a = notificationId(12741890927);
final b = notificationId(12741890928);
expect(a, isNot(b));
});
});
}
@@ -1,10 +1,15 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:latlong2/latlong.dart';
import 'package:flutter_map/flutter_map.dart' show LatLngBounds;
import 'package:mocktail/mocktail.dart';
import 'package:deflockapp/app_state.dart';
import 'package:deflockapp/services/offline_area_service.dart';
import 'package:deflockapp/services/offline_areas/offline_area_models.dart';
class MockAppState extends Mock implements AppState {}
OfflineArea _makeArea({
String providerId = 'osm',
String tileTypeId = 'standard',
@@ -26,11 +31,19 @@ OfflineArea _makeArea({
void main() {
final service = OfflineAreaService();
late MockAppState mockAppState;
setUp(() {
service.setAreasForTesting([]);
mockAppState = MockAppState();
AppState.instance = mockAppState;
// These tests exercise the underlying zoom/provider matching logic, so
// offline features are enabled by default here — the "disabled" gating
// itself is covered separately below.
when(() => mockAppState.offlineFeaturesEnabled).thenReturn(true);
});
group('hasOfflineAreasForProviderAtZoom', () {
test('returns true for zoom within range', () {
service.setAreasForTesting([_makeArea(minZoom: 5, maxZoom: 12)]);
@@ -90,4 +103,30 @@ void main() {
expect(service.hasOfflineAreasForProviderAtZoom('osm', 'standard', 15), isFalse);
});
});
group('offlineFeaturesEnabled gating', () {
test('hasOfflineAreasForProvider returns false when feature disabled, even with matching areas', () {
service.setAreasForTesting([_makeArea(providerId: 'osm', tileTypeId: 'standard')]);
when(() => mockAppState.offlineFeaturesEnabled).thenReturn(false);
expect(service.hasOfflineAreasForProvider('osm', 'standard'), isFalse);
});
test('hasOfflineAreasForProviderAtZoom returns false when feature disabled, even within zoom range', () {
service.setAreasForTesting([_makeArea(minZoom: 5, maxZoom: 12)]);
when(() => mockAppState.offlineFeaturesEnabled).thenReturn(false);
expect(service.hasOfflineAreasForProviderAtZoom('osm', 'standard', 8), isFalse);
});
test('re-enabling offlineFeaturesEnabled restores normal matching', () {
service.setAreasForTesting([_makeArea(minZoom: 5, maxZoom: 12)]);
when(() => mockAppState.offlineFeaturesEnabled).thenReturn(false);
expect(service.hasOfflineAreasForProviderAtZoom('osm', 'standard', 8), isFalse);
when(() => mockAppState.offlineFeaturesEnabled).thenReturn(true);
expect(service.hasOfflineAreasForProviderAtZoom('osm', 'standard', 8), isTrue);
});
});
}
+159 -46
View File
@@ -57,7 +57,7 @@ void main() {
}
group('query building', () {
test('uses out skel for way/relation pass, out body for node pass',
test('uses the way/relation membership pass with restriction conversion',
() async {
stubOverpassResponse([]);
@@ -68,11 +68,16 @@ void main() {
).captured;
final query = (captured.last as Map<String, String>)['data']!;
expect(query, contains('out body;'));
expect(query, contains('out skel;'));
expect(query, contains('.allNodes out body;'));
expect(query, contains('way(bn.allNodes);'));
expect(query, contains('relation(bn.allNodes);'));
expect(query, contains('.resNodes'));
expect(query, contains('convert restriction ::id = id();'));
expect(query, isNot(contains('out meta;')));
expect(query, isNot(contains('out ids;')));
});
test('empty tag values are excluded from filters', () async {
final profileWithEmpty = [
NodeProfile(
@@ -99,8 +104,142 @@ void main() {
});
});
group('profile deduplication (subsumption)', () {
test('a specific profile subsumed by a generic one is dropped', () async {
final generic = NodeProfile(
id: 'generic-alpr',
name: 'Generic ALPR',
tags: const {
'man_made': 'surveillance',
'surveillance:type': 'ALPR',
},
);
final specific = NodeProfile(
id: 'flock',
name: 'Flock',
tags: const {
'man_made': 'surveillance',
'surveillance': 'public',
'surveillance:type': 'ALPR',
'surveillance:zone': 'traffic',
'camera:type': 'fixed',
'manufacturer': 'Flock Safety',
'manufacturer:wikidata': 'Q108485435',
},
);
stubOverpassResponse([]);
await service.fetchNodes(bounds: bounds, profiles: [generic, specific]);
final captured = verify(
() => mockClient.post(any(), body: captureAny(named: 'body')),
).captured;
final query = (captured.last as Map<String, String>)['data']!;
// Only the generic clause should remain.
expect(query, contains('["man_made"="surveillance"]["surveillance:type"="ALPR"]'));
expect(query, isNot(contains('manufacturer')));
expect(query, isNot(contains('Flock Safety')));
// Only one distinct tag-filter clause, appearing twice (once for
// .allNodes, once for the .resNodes re-filter).
final nodeClauseCount = RegExp(r'node[.\[]').allMatches(query).length;
expect(nodeClauseCount, equals(2));
});
test('unrelated profiles are all kept', () async {
final alprGeneric = NodeProfile(
id: 'generic-alpr',
name: 'Generic ALPR',
tags: const {
'man_made': 'surveillance',
'surveillance:type': 'ALPR',
},
);
final gunshotGeneric = NodeProfile(
id: 'generic-gunshot',
name: 'Generic Gunshot Detector',
tags: const {
'man_made': 'surveillance',
'surveillance:type': 'gunshot_detector',
},
);
stubOverpassResponse([]);
await service.fetchNodes(bounds: bounds, profiles: [alprGeneric, gunshotGeneric]);
final captured = verify(
() => mockClient.post(any(), body: captureAny(named: 'body')),
).captured;
final query = (captured.last as Map<String, String>)['data']!;
expect(query, contains('["surveillance:type"="ALPR"]'));
expect(query, contains('["surveillance:type"="gunshot_detector"]'));
});
test('full default profile set reduces to the two generic clauses', () async {
final profiles = NodeProfile.getDefaults();
stubOverpassResponse([]);
await service.fetchNodes(bounds: bounds, profiles: profiles);
final captured = verify(
() => mockClient.post(any(), body: captureAny(named: 'body')),
).captured;
final query = (captured.last as Map<String, String>)['data']!;
// Each of the 2 generic clauses appears twice (once in .allNodes,
// once in the .resNodes re-filter) = 4 total tag-filter clauses.
final nodeClauseCount = RegExp(r'node[.\[]').allMatches(query).length;
expect(nodeClauseCount, equals(4));
expect(query, contains('["man_made"="surveillance"]["surveillance:type"="ALPR"]'));
expect(query, contains('["man_made"="surveillance"]["surveillance:type"="gunshot_detector"]'));
// Brand-specific tags should not appear anywhere in the reduced query.
expect(query, isNot(contains('manufacturer')));
expect(query, isNot(contains('ShotSpotter')));
});
test('profiles with only empty tags do not subsume or break the query', () async {
final emptyTagsProfile = NodeProfile(
id: 'empty',
name: 'Empty',
tags: const {'camera:mount': ''},
);
final normalProfile = NodeProfile(
id: 'normal',
name: 'Normal',
tags: const {'man_made': 'surveillance'},
);
stubOverpassResponse([]);
await service.fetchNodes(bounds: bounds, profiles: [emptyTagsProfile, normalProfile]);
final captured = verify(
() => mockClient.post(any(), body: captureAny(named: 'body')),
).captured;
final query = (captured.last as Map<String, String>)['data']!;
expect(query, contains('["man_made"="surveillance"]'));
});
});
group('response parsing — constraint detection', () {
test('nodes referenced by a way are constrained', () async {
test('a node referenced as a "restriction" element is constrained',
() async {
// The Overpass query converts each way/relation-referenced node ID
// into a synthetic {"type":"restriction","id":<nodeId>} element
// (via `convert restriction ::id = id();`) — this is how the server
// tells us a node is part of some way/relation, regardless of whether
// that way/relation came from a "way" or a "relation" in Overpass.
stubOverpassResponse([
{
'type': 'node',
@@ -117,9 +256,8 @@ void main() {
'tags': {'man_made': 'surveillance'},
},
{
'type': 'way',
'id': 100,
'nodes': [1],
'type': 'restriction',
'id': 1,
},
]);
@@ -133,32 +271,8 @@ void main() {
expect(node2.isConstrained, isFalse);
});
test('nodes referenced by a relation member are constrained', () async {
stubOverpassResponse([
{
'type': 'node',
'id': 3,
'lat': 38.9,
'lon': -77.0,
'tags': {'man_made': 'surveillance'},
},
{
'type': 'relation',
'id': 200,
'members': [
{'type': 'node', 'ref': 3, 'role': ''},
],
},
]);
final nodes =
await service.fetchNodes(bounds: bounds, profiles: profiles);
expect(nodes, hasLength(1));
expect(nodes.first.isConstrained, isTrue);
});
test('nodes not in any way or relation are unconstrained', () async {
test('nodes not marked with a "restriction" element are unconstrained',
() async {
stubOverpassResponse([
{
'type': 'node',
@@ -176,7 +290,8 @@ void main() {
expect(nodes.first.isConstrained, isFalse);
});
test('mixed response with nodes, ways, and relations', () async {
test('mixed response with multiple constrained and unconstrained nodes',
() async {
stubOverpassResponse([
{
'type': 'node',
@@ -200,16 +315,12 @@ void main() {
'tags': {'man_made': 'surveillance'},
},
{
'type': 'way',
'id': 300,
'nodes': [10],
'type': 'restriction',
'id': 10,
},
{
'type': 'relation',
'id': 400,
'members': [
{'type': 'node', 'ref': 11, 'role': ''},
],
'type': 'restriction',
'id': 11,
},
]);
@@ -223,6 +334,7 @@ void main() {
});
});
group('error handling', () {
test('HTTP 200 returns parsed nodes', () async {
stubOverpassResponse([
@@ -255,27 +367,28 @@ void main() {
);
});
test('response with "timeout" throws NodeLimitError', () async {
test('response with "timeout" throws NetworkError (not split)', () async {
stubErrorResponse(400, 'runtime error: timeout in query execution');
await expectLater(
() => service.fetchNodes(
bounds: bounds, profiles: profiles, policy: const ResiliencePolicy(maxRetries: 0)),
throwsA(isA<NodeLimitError>()),
throwsA(isA<NetworkError>()),
);
});
test('response with "runtime limit exceeded" throws NodeLimitError',
test('response with "runtime limit exceeded" throws NetworkError (not split)',
() async {
stubErrorResponse(400, 'runtime limit exceeded');
await expectLater(
() => service.fetchNodes(
bounds: bounds, profiles: profiles, policy: const ResiliencePolicy(maxRetries: 0)),
throwsA(isA<NodeLimitError>()),
throwsA(isA<NetworkError>()),
);
});
test('HTTP 429 throws RateLimitError', () async {
stubErrorResponse(429, 'Too Many Requests');