lingxia-platform 0.6.0

Platform abstraction layer for LingXia framework (Android, iOS, HarmonyOS)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Apple platform location services implementation

use super::Platform;
use crate::error::PlatformError;
use crate::traits::location::Location;

#[cfg(any(target_os = "ios", target_os = "macos"))]
pub(crate) mod ios {
    use super::*;
    use dispatch2::DispatchQueue;
    use objc2::define_class;
    use objc2::msg_send;
    use objc2::rc::Retained;
    use objc2::runtime::{NSObject, NSObjectProtocol, ProtocolObject};
    use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly};
    use objc2_core_location::{
        CLAuthorizationStatus, CLLocation, CLLocationManager, CLLocationManagerDelegate,
        kCLDistanceFilterNone, kCLLocationAccuracyBest, kCLLocationAccuracyHundredMeters,
    };
    use objc2_foundation::{NSArray, NSError};
    use serde_json::json;
    use std::cell::{Cell, RefCell};
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex, OnceLock};
    use std::time::{Duration, Instant};

    // Global storage for location callbacks that can be accessed from any thread.
    static LOCATION_CALLBACKS: OnceLock<Arc<Mutex<HashMap<u64, LocationCallbackInfo>>>> =
        OnceLock::new();

    #[derive(Clone)]
    #[allow(dead_code)]
    struct LocationCallbackInfo {
        callback_id: u64,
        config: crate::traits::location::LocationRequestConfig,
        start_time: Instant,
    }

    #[allow(dead_code)]
    struct ActiveLocationRequest {
        manager: Retained<CLLocationManager>,
        delegate: Retained<LocationDelegate>,
    }

    std::thread_local! {
        static ACTIVE_REQUESTS: RefCell<HashMap<u64, ActiveLocationRequest>> = RefCell::new(HashMap::new());
    }

    #[derive(Default)]
    struct LocationDelegateIvars {
        callback_id: Cell<u64>,
    }

    define_class!(
        #[unsafe(super(NSObject))]
        #[thread_kind = MainThreadOnly]
        #[name = "LingXiaLocationDelegate"]
        #[ivars = LocationDelegateIvars]
        struct LocationDelegate;

        impl LocationDelegate {
            #[unsafe(method(locationManager:didUpdateLocations:))]
            fn location_manager_did_update_locations(
                &self,
                _manager: &CLLocationManager,
                locations: &NSArray<CLLocation>,
            ) {
                let callback_id = self.callback_id();
                let maybe_location = locations.lastObject();
                let Some(location) = maybe_location else {
                    log::warn!(
                        "Apple Location: Received update without locations for callback {}",
                        callback_id
                    );
                    deliver_failure(callback_id, "No location available");
                    return;
                };
                deliver_success(callback_id, &location);
            }

            #[unsafe(method(locationManager:didFailWithError:))]
            fn location_manager_did_fail_with_error(
                &self,
                _manager: &CLLocationManager,
                error: &NSError,
            ) {
                let callback_id = self.callback_id();
                let message = format!("Location update failed: {}", ns_error_to_string(error));
                log::error!("Apple Location: {} (callback {})", message, callback_id);
                deliver_failure(callback_id, &message);
            }

            #[unsafe(method(locationManagerDidChangeAuthorization:))]
            fn location_manager_did_change_authorization(&self, manager: &CLLocationManager) {
                let status = unsafe { manager.authorizationStatus() };
                let callback_id = self.callback_id();
                match status {
                    CLAuthorizationStatus::AuthorizedWhenInUse | CLAuthorizationStatus::AuthorizedAlways => {
                        unsafe {
                            manager.requestLocation();
                        }
                    }
                    CLAuthorizationStatus::Denied | CLAuthorizationStatus::Restricted => {
                        log::warn!(
                            "Apple Location: Authorization changed to denied/restricted for callback {}",
                            callback_id
                        );
                        deliver_failure(callback_id, "Location permission denied");
                    }
                    CLAuthorizationStatus::NotDetermined => {
                        log::debug!(
                            "Apple Location: Authorization still not determined for callback {}",
                            callback_id
                        );
                    }
                    _ => {}
                }
            }
        }

        unsafe impl NSObjectProtocol for LocationDelegate {}
        unsafe impl CLLocationManagerDelegate for LocationDelegate {}
    );

    impl LocationDelegate {
        fn new(callback_id: u64) -> Retained<Self> {
            let mtm =
                MainThreadMarker::new().expect("LocationDelegate must be created on main thread");
            let this = Self::alloc(mtm);
            let this = this.set_ivars(LocationDelegateIvars {
                callback_id: Cell::new(callback_id),
            });
            unsafe { msg_send![super(this), init] }
        }

        fn callback_id(&self) -> u64 {
            self.ivars().callback_id.get()
        }
    }

    fn ns_error_to_string(error: &NSError) -> String {
        error.localizedDescription().to_string()
    }

    fn active_requests_mut<F, R>(f: F) -> R
    where
        F: FnOnce(&mut HashMap<u64, ActiveLocationRequest>) -> R,
    {
        ACTIVE_REQUESTS.with(|cell| {
            let mut borrow = cell.borrow_mut();
            f(&mut borrow)
        })
    }

    fn insert_active_request(callback_id: u64, request: ActiveLocationRequest) {
        active_requests_mut(|active| {
            active.insert(callback_id, request);
        });
    }

    fn take_active_request(callback_id: u64) -> Option<ActiveLocationRequest> {
        active_requests_mut(|active| active.remove(&callback_id))
    }

    fn callbacks() -> &'static Arc<Mutex<HashMap<u64, LocationCallbackInfo>>> {
        LOCATION_CALLBACKS.get_or_init(|| Arc::new(Mutex::new(HashMap::new())))
    }

    fn remove_callback_info(callback_id: u64) -> Option<LocationCallbackInfo> {
        let callbacks = callbacks();
        let mut guard = callbacks.lock().unwrap();
        guard.remove(&callback_id)
    }

    fn cleanup_request(callback_id: u64) {
        if let Some(active) = take_active_request(callback_id) {
            unsafe {
                active.manager.stopUpdatingLocation();
                active.manager.setDelegate(None);
            }
        }
    }

    fn deliver_success(callback_id: u64, location: &CLLocation) {
        let info = remove_callback_info(callback_id);
        cleanup_request(callback_id);
        let Some(info) = info else {
            log::debug!(
                "Apple Location: Callback {} already handled before success",
                callback_id
            );
            return;
        };

        let payload = build_location_payload(location, info.config.include_altitude);
        log::info!(
            "Apple Location: Delivering success result for callback {}",
            callback_id
        );
        lingxia_messaging::invoke_callback(callback_id, Ok(payload));
    }

    fn deliver_failure(callback_id: u64, message: &str) {
        let info_present = remove_callback_info(callback_id).is_some();
        cleanup_request(callback_id);
        if !info_present {
            log::debug!(
                "Apple Location: Callback {} already handled before failure",
                callback_id
            );
            return;
        }

        let mut code: u32 = 1001; // Generic location_error
        if message.contains("permission") {
            code = 3002; // location_permission_denied
        } else if message.contains("disabled") {
            code = 4001; // location_services_disabled
        } else if message.contains("timed out") || message.contains("timeout") {
            code = 5002; // location_timeout
        }

        lingxia_messaging::invoke_callback(callback_id, Err(code));
    }

    fn build_location_payload(location: &CLLocation, include_altitude: bool) -> String {
        unsafe {
            let coordinate = location.coordinate();
            let horizontal_accuracy = sanitize_measurement(location.horizontalAccuracy());
            let vertical_accuracy = sanitize_measurement(location.verticalAccuracy());
            let speed = sanitize_measurement(location.speed());
            let altitude = if include_altitude {
                sanitize_measurement(location.altitude())
            } else {
                0.0
            };

            json!({
                "latitude": coordinate.latitude,
                "longitude": coordinate.longitude,
                "speed": speed,
                "accuracy": horizontal_accuracy,
                "altitude": altitude,
                "vertical_accuracy": vertical_accuracy,
                "horizontal_accuracy": horizontal_accuracy,
            })
            .to_string()
        }
    }

    fn sanitize_measurement(value: f64) -> f64 {
        if value.is_finite() && value >= 0.0 {
            value
        } else {
            0.0
        }
    }

    pub(crate) fn is_location_enabled() -> Result<bool, PlatformError> {
        let enabled = unsafe { CLLocationManager::locationServicesEnabled_class() };
        Ok(enabled)
    }

    pub(super) fn request_location_with_config(
        callback_id: u64,
        config: crate::traits::location::LocationRequestConfig,
    ) -> Result<(), PlatformError> {
        let services_enabled = unsafe { CLLocationManager::locationServicesEnabled_class() };
        if !services_enabled {
            log::error!("Apple Location: Services disabled");
            lingxia_messaging::invoke_callback(callback_id, Err(4001));
            // Error is fully reported via callback; no additional PlatformError needed.
            return Ok(());
        }

        // Record callback info so delegate can access configuration.
        callbacks().lock().unwrap().insert(
            callback_id,
            LocationCallbackInfo {
                callback_id,
                config: config.clone(),
                start_time: Instant::now(),
            },
        );

        #[allow(deprecated)]
        let authorization_status = unsafe { CLLocationManager::authorizationStatus_class() };
        if matches!(
            authorization_status,
            CLAuthorizationStatus::Denied | CLAuthorizationStatus::Restricted
        ) {
            log::warn!(
                "Apple Location: Authorization denied/restricted before request (status: {:?})",
                authorization_status
            );
            // Report permission denial via callback; the logic layer owns user-facing toasts
            // and error handling decisions.
            deliver_failure(callback_id, "Location permission denied");
            return Ok(());
        }

        DispatchQueue::main().exec_async(move || {
            if let Err(err_msg) = start_location_request(callback_id) {
                log::error!("Apple Location: Failed to start request {}", err_msg);
                deliver_failure(callback_id, &err_msg);
            }
        });

        // Set up timeout monitoring if requested.
        if let Some(timeout_ms) = config.high_accuracy_expire_time {
            let callbacks = callbacks().clone();
            let _ = crate::rt::spawn(async move {
                tokio::time::sleep(Duration::from_millis(timeout_ms as u64)).await;
                let should_timeout = {
                    let mut guard = callbacks.lock().unwrap();
                    if guard.contains_key(&callback_id) {
                        guard.remove(&callback_id);
                        true
                    } else {
                        false
                    }
                };

                if should_timeout {
                    log::warn!(
                        "Apple Location: Request {} timed out after {}ms",
                        callback_id,
                        timeout_ms
                    );
                    DispatchQueue::main().exec_async(move || {
                        cleanup_request(callback_id);
                        lingxia_messaging::invoke_callback(callback_id, Err(5002));
                    });
                }
            });
        }

        Ok(())
    }

    fn start_location_request(callback_id: u64) -> Result<(), String> {
        let callback_info = {
            let callbacks = callbacks();
            let guard = callbacks.lock().unwrap();
            guard.get(&callback_id).cloned()
        }
        .ok_or_else(|| "Location request not registered".to_string())?;

        let manager = unsafe { CLLocationManager::new() };
        let delegate = LocationDelegate::new(callback_id);
        let high_accuracy = callback_info.config.is_high_accuracy;

        unsafe {
            let desired_accuracy = if high_accuracy {
                kCLLocationAccuracyBest
            } else {
                kCLLocationAccuracyHundredMeters
            };
            manager.setDesiredAccuracy(desired_accuracy);

            if high_accuracy {
                manager.setDistanceFilter(kCLDistanceFilterNone);
            }

            manager.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));

            let status = manager.authorizationStatus();
            if matches!(
                status,
                CLAuthorizationStatus::Denied | CLAuthorizationStatus::Restricted
            ) {
                return Err("Location permission denied".to_string());
            }

            if status == CLAuthorizationStatus::NotDetermined {
                manager.requestWhenInUseAuthorization();
            }
        }

        let should_request_location_now = unsafe {
            let status = manager.authorizationStatus();
            matches!(
                status,
                CLAuthorizationStatus::AuthorizedWhenInUse
                    | CLAuthorizationStatus::AuthorizedAlways
            )
        };

        insert_active_request(
            callback_id,
            ActiveLocationRequest {
                manager: manager.clone(),
                delegate: delegate.clone(),
            },
        );

        if should_request_location_now {
            unsafe {
                manager.requestLocation();
            }
        }

        Ok(())
    }
}

impl Location for Platform {
    fn is_location_enabled(&self) -> Result<bool, PlatformError> {
        ios::is_location_enabled()
    }

    async fn request_location(
        &self,
        config: crate::traits::location::LocationRequestConfig,
    ) -> Result<String, PlatformError> {
        crate::rt::native_call(|callback_id| ios::request_location_with_config(callback_id, config))
            .await
    }
}