1use std::fmt;
5use std::sync::{Arc, OnceLock, RwLock};
6use std::time::{SystemTime, UNIX_EPOCH};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum GeolocationSource {
11 #[default]
12 MockOverride,
13 EnvOverride,
14 LinuxGeoClue2,
15 LinuxPortal,
16 NmeaGpsSerial,
17 GpsdDaemon,
18 MacOsCoreLocation,
19 WindowsWinRt,
20 HttpsIpFallback,
21}
22
23#[derive(Debug, Clone, PartialEq)]
25pub struct GeoCoordinates {
26 pub latitude: f64,
27 pub longitude: f64,
28 pub altitude: Option<f64>,
29 pub accuracy: f64,
30 pub altitude_accuracy: Option<f64>,
31 pub heading: Option<f64>,
32 pub speed: Option<f64>,
33}
34
35impl GeoCoordinates {
36 pub fn new(latitude: f64, longitude: f64, accuracy: f64) -> Self {
37 Self {
38 latitude,
39 longitude,
40 altitude: None,
41 accuracy,
42 altitude_accuracy: None,
43 heading: None,
44 speed: None,
45 }
46 }
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub struct GeolocationPosition {
52 pub coords: GeoCoordinates,
53 pub timestamp: u64,
54 pub source: GeolocationSource,
55}
56
57impl GeolocationPosition {
58 pub fn new(coords: GeoCoordinates) -> Self {
59 Self::with_source(coords, GeolocationSource::MockOverride)
60 }
61
62 pub fn with_source(coords: GeoCoordinates, source: GeolocationSource) -> Self {
63 let timestamp = SystemTime::now()
64 .duration_since(UNIX_EPOCH)
65 .map(|d| d.as_millis() as u64)
66 .unwrap_or(0);
67 Self {
68 coords,
69 timestamp,
70 source,
71 }
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum GeolocationError {
78 PermissionDenied(String),
79 PositionUnavailable(String),
80 Timeout(String),
81}
82
83impl fmt::Display for GeolocationError {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 match self {
86 Self::PermissionDenied(s) => write!(f, "Geolocation permission denied: {s}"),
87 Self::PositionUnavailable(s) => write!(f, "Position unavailable: {s}"),
88 Self::Timeout(s) => write!(f, "Geolocation lookup timed out: {s}"),
89 }
90 }
91}
92
93impl std::error::Error for GeolocationError {}
94
95#[derive(Debug, Clone)]
97pub struct GeolocationOptions {
98 pub enable_high_accuracy: bool,
99 pub timeout_ms: u64,
100 pub maximum_age_ms: u64,
101 pub allow_ip_fallback: bool,
103}
104
105impl Default for GeolocationOptions {
106 fn default() -> Self {
107 Self {
108 enable_high_accuracy: false,
109 timeout_ms: 10000,
110 maximum_age_ms: 0,
111 allow_ip_fallback: true,
112 }
113 }
114}
115
116pub type OsGeolocationProvider = fn(&GeolocationOptions) -> Option<GeolocationPosition>;
118
119static OS_GEO_PROVIDER: OnceLock<RwLock<Option<OsGeolocationProvider>>> = OnceLock::new();
120
121fn os_provider_slot() -> &'static RwLock<Option<OsGeolocationProvider>> {
122 OS_GEO_PROVIDER.get_or_init(|| RwLock::new(None))
123}
124
125#[derive(Clone)]
127pub struct Geolocation {
128 current_position: Arc<RwLock<Option<GeolocationPosition>>>,
129}
130
131impl Default for Geolocation {
132 fn default() -> Self {
133 Self::new()
134 }
135}
136
137impl Geolocation {
138 pub fn new() -> Self {
139 Self {
140 current_position: Arc::new(RwLock::new(None)),
141 }
142 }
143
144 pub fn register_os_provider(provider: OsGeolocationProvider) {
147 if let Ok(mut slot) = os_provider_slot().write() {
148 *slot = Some(provider);
149 }
150 }
151
152 pub fn clear_os_provider() {
154 if let Ok(mut slot) = os_provider_slot().write() {
155 *slot = None;
156 }
157 }
158
159 pub fn set_mock_position(&self, coords: GeoCoordinates) {
161 if let Ok(mut pos) = self.current_position.write() {
162 *pos = Some(GeolocationPosition::with_source(
163 coords,
164 GeolocationSource::MockOverride,
165 ));
166 }
167 }
168
169 pub fn clear_mock_position(&self) {
171 if let Ok(mut pos) = self.current_position.write() {
172 *pos = None;
173 }
174 }
175
176 pub fn get_current_position(&self) -> Result<GeolocationPosition, GeolocationError> {
178 self.get_current_position_with_options(&GeolocationOptions::default())
179 }
180
181 pub fn get_current_position_with_options(
184 &self,
185 options: &GeolocationOptions,
186 ) -> Result<GeolocationPosition, GeolocationError> {
187 let mock_pos = self
188 .current_position
189 .read()
190 .map_err(|e| GeolocationError::PositionUnavailable(e.to_string()))?
191 .clone();
192
193 if let Some(pos) = mock_pos {
194 return Ok(pos);
195 }
196
197 let provider = os_provider_slot().read().ok().and_then(|g| *g);
198 if let Some(provider_fn) = provider {
199 if let Some(pos) = provider_fn(options) {
200 return Ok(pos);
201 }
202 }
203
204 Err(GeolocationError::PositionUnavailable(
205 "No position available from device provider".into(),
206 ))
207 }
208}
209
210pub fn parse_env_lat_lon(raw: &str) -> Option<GeoCoordinates> {
217 let parts: Vec<&str> = raw.split(',').map(str::trim).collect();
218 if parts.len() < 2 {
219 return None;
220 }
221 let lat: f64 = parts[0].parse().ok()?;
222 let lon: f64 = parts[1].parse().ok()?;
223 if !is_valid_lat_lon(lat, lon) {
224 return None;
225 }
226 let alt = parts.get(2).and_then(|s| s.parse::<f64>().ok());
227 let acc = parts
228 .get(3)
229 .and_then(|s| s.parse::<f64>().ok())
230 .filter(|a| a.is_finite() && *a >= 0.0)
231 .unwrap_or(15.0);
232
233 let mut coords = GeoCoordinates::new(lat, lon, acc);
234 coords.altitude = alt.filter(|v| v.is_finite());
235 Some(coords)
236}
237
238pub fn parse_nmea_sentence(sentence: &str) -> Option<GeoCoordinates> {
241 let trimmed = sentence.trim();
242 if !trimmed.starts_with('$') {
243 return None;
244 }
245
246 let body = if let Some((payload, checksum_hex)) = trimmed[1..].split_once('*') {
247 let expected = u8::from_str_radix(checksum_hex.trim().get(..2)?, 16).ok()?;
248 let computed = payload.bytes().fold(0u8, |acc, b| acc ^ b);
249 if computed != expected {
250 return None;
251 }
252 payload
253 } else {
254 &trimmed[1..]
255 };
256
257 let fields: Vec<&str> = body.split(',').collect();
258 let talker_msg = *fields.first()?;
259 if talker_msg.len() < 5 {
260 return None;
261 }
262 let msg_type = &talker_msg[talker_msg.len() - 3..];
263
264 match msg_type {
265 "GGA" => {
266 if fields.len() < 10 {
268 return None;
269 }
270 let fix_quality: u8 = fields[6].parse().ok()?;
271 if fix_quality == 0 {
272 return None;
273 }
274 let lat = parse_nmea_deg_min(fields[2], fields[3], false)?;
275 let lon = parse_nmea_deg_min(fields[4], fields[5], true)?;
276 let hdop = fields[8].parse::<f64>().ok().filter(|v| *v > 0.0).unwrap_or(1.5);
277 let accuracy = (hdop * 5.0).clamp(1.0, 250.0);
278 let alt = fields[9].parse::<f64>().ok().filter(|v| v.is_finite());
279
280 let mut coords = GeoCoordinates::new(lat, lon, accuracy);
281 coords.altitude = alt;
282 Some(coords)
283 }
284 "RMC" => {
285 if fields.len() < 9 || fields[2] != "A" {
287 return None;
288 }
289 let lat = parse_nmea_deg_min(fields[3], fields[4], false)?;
290 let lon = parse_nmea_deg_min(fields[5], fields[6], true)?;
291 let speed_mps = fields[7]
292 .parse::<f64>()
293 .ok()
294 .filter(|v| v.is_finite() && *v >= 0.0)
295 .map(|knots| knots * 0.514_444);
296 let heading = fields[8]
297 .parse::<f64>()
298 .ok()
299 .filter(|v| v.is_finite())
300 .map(|deg| deg.rem_euclid(360.0));
301
302 let mut coords = GeoCoordinates::new(lat, lon, 10.0);
303 coords.speed = speed_mps;
304 coords.heading = heading;
305 Some(coords)
306 }
307 _ => None,
308 }
309}
310
311fn parse_nmea_deg_min(value: &str, hemi: &str, is_lon: bool) -> Option<f64> {
312 let raw: f64 = value.trim().parse().ok()?;
313 if !raw.is_finite() || raw < 0.0 {
314 return None;
315 }
316 let degrees = (raw / 100.0).floor();
317 let minutes = raw - degrees * 100.0;
318 if minutes >= 60.0 {
319 return None;
320 }
321 let mut decimal = degrees + minutes / 60.0;
322 match hemi.trim() {
323 "N" if !is_lon => {}
324 "S" if !is_lon => decimal = -decimal,
325 "E" if is_lon => {}
326 "W" if is_lon => decimal = -decimal,
327 _ => return None,
328 }
329 if (!is_lon && decimal.abs() <= 90.0) || (is_lon && decimal.abs() <= 180.0) {
330 Some(decimal)
331 } else {
332 None
333 }
334}
335
336pub fn parse_gpsd_tpv_json(line: &str) -> Option<GeoCoordinates> {
338 let val: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
339 if val.get("class").and_then(|v| v.as_str()) != Some("TPV") {
340 return None;
341 }
342 let mode = val.get("mode").and_then(|v| v.as_i64()).unwrap_or(0);
343 if mode < 2 {
344 return None;
345 }
346 let lat = val.get("lat").and_then(|v| v.as_f64())?;
347 let lon = val.get("lon").and_then(|v| v.as_f64())?;
348 if !is_valid_lat_lon(lat, lon) {
349 return None;
350 }
351 let epx = val.get("epx").and_then(|v| v.as_f64()).unwrap_or(10.0);
352 let epy = val.get("epy").and_then(|v| v.as_f64()).unwrap_or(10.0);
353 let accuracy = epx.hypot(epy).clamp(1.0, 50_000.0);
354
355 let mut coords = GeoCoordinates::new(lat, lon, accuracy);
356 coords.altitude = val
357 .get("altMSL")
358 .or_else(|| val.get("alt"))
359 .and_then(|v| v.as_f64())
360 .filter(|v| v.is_finite());
361 coords.speed = val
362 .get("speed")
363 .and_then(|v| v.as_f64())
364 .filter(|v| v.is_finite() && *v >= 0.0);
365 coords.heading = val
366 .get("track")
367 .and_then(|v| v.as_f64())
368 .filter(|v| v.is_finite())
369 .map(|d| d.rem_euclid(360.0));
370 Some(coords)
371}
372
373pub fn parse_geoclue_dbus_output(text: &str) -> Option<GeoCoordinates> {
376 let lat = extract_named_f64(text, "Latitude")?;
377 let lon = extract_named_f64(text, "Longitude")?;
378 if !is_valid_lat_lon(lat, lon) {
379 return None;
380 }
381 let accuracy = extract_named_f64(text, "Accuracy")
382 .filter(|v| v.is_finite() && *v >= 0.0)
383 .unwrap_or(50.0);
384 let altitude = extract_named_f64(text, "Altitude")
385 .filter(|v| v.is_finite() && *v > -1.0e6);
386 let speed = extract_named_f64(text, "Speed")
387 .filter(|v| v.is_finite() && *v >= 0.0);
388 let heading = extract_named_f64(text, "Heading")
389 .filter(|v| v.is_finite() && *v >= 0.0)
390 .map(|d| d.rem_euclid(360.0));
391
392 let mut coords = GeoCoordinates::new(lat, lon, accuracy);
393 coords.altitude = altitude;
394 coords.speed = speed;
395 coords.heading = heading;
396 Some(coords)
397}
398
399fn extract_named_f64(text: &str, key: &str) -> Option<f64> {
400 let idx = text.find(key)?;
402 let rest = &text[idx + key.len()..];
403 let bytes = rest.as_bytes();
404 let mut pos = 0usize;
405 while pos < bytes.len() {
406 let b = bytes[pos];
407 if b.is_ascii_digit() || b == b'-' || b == b'+' {
408 let end = rest[pos..]
410 .find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')))
411 .map(|rel| pos + rel)
412 .unwrap_or(rest.len());
413 if let Ok(val) = rest[pos..end].parse::<f64>() {
414 return Some(val);
415 }
416 pos = end;
417 } else if b == b'\n' || b == b',' || b == b'}' {
418 break;
419 } else {
420 pos += 1;
421 }
422 }
423 None
424}
425
426pub fn parse_ip_geolocation_json(json_str: &str) -> Option<GeoCoordinates> {
429 let val: serde_json::Value = serde_json::from_str(json_str.trim()).ok()?;
430 if val.get("success").and_then(|v| v.as_bool()) == Some(false) {
431 return None;
432 }
433 if val.get("error").and_then(|v| v.as_bool()) == Some(true) {
434 return None;
435 }
436
437 let (lat, lon) = if let (Some(la), Some(lo)) = (
438 val.get("latitude").and_then(json_to_f64),
439 val.get("longitude").and_then(json_to_f64),
440 ) {
441 (la, lo)
442 } else if let (Some(la), Some(lo)) = (
443 val.get("lat").and_then(json_to_f64),
444 val.get("lon").and_then(json_to_f64),
445 ) {
446 (la, lo)
447 } else if let Some(loc) = val.get("loc").and_then(|v| v.as_str()) {
448 let (a, b) = loc.split_once(',')?;
449 (a.trim().parse().ok()?, b.trim().parse().ok()?)
450 } else {
451 return None;
452 };
453
454 if !is_valid_lat_lon(lat, lon) || (lat.abs() < 1e-6 && lon.abs() < 1e-6) {
455 return None;
456 }
457 let accuracy = val
458 .get("accuracy")
459 .and_then(json_to_f64)
460 .filter(|v| v.is_finite() && *v > 0.0)
461 .unwrap_or(5_000.0);
462 Some(GeoCoordinates::new(lat, lon, accuracy))
463}
464
465fn json_to_f64(v: &serde_json::Value) -> Option<f64> {
466 v.as_f64()
467 .or_else(|| v.as_str().and_then(|s| s.trim().parse::<f64>().ok()))
468}
469
470#[inline]
471fn is_valid_lat_lon(lat: f64, lon: f64) -> bool {
472 lat.is_finite() && lon.is_finite() && (-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lon)
473}
474
475pub fn haversine_distance_meters(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
478 const EARTH_RADIUS_METERS: f64 = 6_371_000.0;
479
480 let d_lat = (lat2 - lat1).to_radians();
481 let d_lon = (lon2 - lon1).to_radians();
482
483 let rad_lat1 = lat1.to_radians();
484 let rad_lat2 = lat2.to_radians();
485
486 let a =
487 (d_lat / 2.0).sin().powi(2) + rad_lat1.cos() * rad_lat2.cos() * (d_lon / 2.0).sin().powi(2);
488
489 let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
490
491 EARTH_RADIUS_METERS * c
492}
493
494pub fn initial_bearing_degrees(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
496 let d_lon = (lon2 - lon1).to_radians();
497 let rad_lat1 = lat1.to_radians();
498 let rad_lat2 = lat2.to_radians();
499
500 let y = d_lon.sin() * rad_lat2.cos();
501 let x = rad_lat1.cos() * rad_lat2.sin() - rad_lat1.sin() * rad_lat2.cos() * d_lon.cos();
502
503 let bearing_rad = y.atan2(x);
504 let bearing_deg = bearing_rad.to_degrees();
505
506 (bearing_deg + 360.0) % 360.0
507}