use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
use strata_dom::reactive::Signal;
use crate::mock::DeviceMockController;
use crate::os_sensors::{probe_os_geolocation_async, register_web_api_geolocation_provider};
use crate::types::*;
struct ThreadLocalSignals {
battery: Signal<BatteryInfo>,
thermal: Signal<ThermalState>,
network: Signal<NetworkStatus>,
screen: Signal<ScreenGeometry>,
display_refresh: Signal<DisplayRefreshInfo>,
geolocation: Signal<GeolocationInfo>,
compass: Signal<CompassReading>,
imu: Signal<ImuReading>,
barometer: Signal<BarometerReading>,
ambient_light: Signal<AmbientLightReading>,
proximity: Signal<ProximityReading>,
hinge_angle: Signal<HingeAngleReading>,
radio_signal: Signal<RadioSignalReading>,
ambient_spl: Signal<AmbientSplReading>,
pedometer: Signal<PedometerReading>,
heart_rate: Signal<HeartRateReading>,
}
thread_local! {
static SIGNALS: RefCell<Option<ThreadLocalSignals>> = const { RefCell::new(None) };
}
static PENDING_GEO_FIX: OnceLock<Mutex<Option<GeolocationInfo>>> = OnceLock::new();
static GEO_PROBE_IN_FLIGHT: AtomicBool = AtomicBool::new(false);
fn pending_geo_slot() -> &'static Mutex<Option<GeolocationInfo>> {
PENDING_GEO_FIX.get_or_init(|| Mutex::new(None))
}
fn with_or_init_signals<R>(f: impl FnOnce(&ThreadLocalSignals) -> R) -> R {
SIGNALS.with(|cell| {
let mut borrow = cell.borrow_mut();
if borrow.is_none() {
let mock = DeviceMockController::new();
*borrow = Some(ThreadLocalSignals {
battery: Signal::new(mock.battery()),
thermal: Signal::new(mock.thermal()),
network: Signal::new(mock.network()),
screen: Signal::new(mock.screen()),
display_refresh: Signal::new(mock.display_refresh()),
geolocation: Signal::new(mock.geolocation()),
compass: Signal::new(mock.compass()),
imu: Signal::new(mock.imu()),
barometer: Signal::new(mock.barometer()),
ambient_light: Signal::new(mock.ambient_light()),
proximity: Signal::new(mock.proximity()),
hinge_angle: Signal::new(mock.hinge_angle()),
radio_signal: Signal::new(mock.radio_signal()),
ambient_spl: Signal::new(mock.ambient_spl()),
pedometer: Signal::new(mock.pedometer()),
heart_rate: Signal::new(mock.heart_rate()),
});
}
f(borrow.as_ref().unwrap())
})
}
pub(crate) fn sync_signals_from_mock(mock: &DeviceMockController) {
SIGNALS.with(|cell| {
if let Ok(borrow) = cell.try_borrow() {
if let Some(signals) = borrow.as_ref() {
signals.battery.set(mock.battery());
signals.thermal.set(mock.thermal());
signals.network.set(mock.network());
signals.screen.set(mock.screen());
signals.display_refresh.set(mock.display_refresh());
signals.geolocation.set(mock.geolocation());
signals.compass.set(mock.compass());
signals.imu.set(mock.imu());
signals.barometer.set(mock.barometer());
signals.ambient_light.set(mock.ambient_light());
signals.proximity.set(mock.proximity());
signals.hinge_angle.set(mock.hinge_angle());
signals.radio_signal.set(mock.radio_signal());
signals.ambient_spl.set(mock.ambient_spl());
signals.pedometer.set(mock.pedometer());
signals.heart_rate.set(mock.heart_rate());
}
}
});
}
pub fn use_battery() -> Signal<BatteryInfo> {
with_or_init_signals(|s| s.battery.clone())
}
pub fn use_thermal() -> Signal<ThermalState> {
with_or_init_signals(|s| s.thermal.clone())
}
pub fn use_network() -> Signal<NetworkStatus> {
with_or_init_signals(|s| s.network.clone())
}
pub fn use_screen() -> Signal<ScreenGeometry> {
with_or_init_signals(|s| s.screen.clone())
}
pub fn use_display_refresh() -> Signal<DisplayRefreshInfo> {
with_or_init_signals(|s| s.display_refresh.clone())
}
pub fn use_geolocation() -> Signal<GeolocationInfo> {
register_web_api_geolocation_provider();
let _ = poll_geolocation_updates();
with_or_init_signals(|s| s.geolocation.clone())
}
pub fn use_geolocation_with_options(
auto_probe_async: bool,
allow_ip_fallback: bool,
) -> Signal<GeolocationInfo> {
let sig = use_geolocation();
if auto_probe_async && !sig.untracked_get().is_available {
request_geolocation_refresh_async(allow_ip_fallback);
}
sig
}
pub fn request_geolocation_refresh_async(allow_ip_fallback: bool) {
if GEO_PROBE_IN_FLIGHT
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
.is_err()
{
return;
}
probe_os_geolocation_async(allow_ip_fallback, |maybe_fix| {
if let Some(fix) = maybe_fix {
if let Ok(mut pending) = pending_geo_slot().lock() {
*pending = Some(fix);
}
}
GEO_PROBE_IN_FLIGHT.store(false, Ordering::SeqCst);
});
}
pub fn poll_geolocation_updates() -> Option<GeolocationInfo> {
let fix = pending_geo_slot().lock().ok()?.take()?;
let mock = DeviceMockController::new();
let existing = mock.geolocation();
if existing.is_available && existing.source == GeolocationSource::MockOverride {
return Some(existing);
}
mock.set_geolocation(fix.clone());
Some(fix)
}
pub fn use_compass() -> Signal<CompassReading> {
with_or_init_signals(|s| s.compass.clone())
}
pub fn use_imu() -> Signal<ImuReading> {
with_or_init_signals(|s| s.imu.clone())
}
pub fn use_barometer() -> Signal<BarometerReading> {
with_or_init_signals(|s| s.barometer.clone())
}
pub fn use_ambient_light() -> Signal<AmbientLightReading> {
with_or_init_signals(|s| s.ambient_light.clone())
}
pub fn use_proximity() -> Signal<ProximityReading> {
with_or_init_signals(|s| s.proximity.clone())
}
pub fn use_hinge_angle() -> Signal<HingeAngleReading> {
with_or_init_signals(|s| s.hinge_angle.clone())
}
pub fn use_radio_signal() -> Signal<RadioSignalReading> {
with_or_init_signals(|s| s.radio_signal.clone())
}
pub fn use_ambient_spl() -> Signal<AmbientSplReading> {
if let Some(live) = crate::os_sensors::probe_os_ambient_spl() {
DeviceMockController::new().set_ambient_spl(live);
}
with_or_init_signals(|s| s.ambient_spl.clone())
}
pub fn use_pedometer() -> Signal<PedometerReading> {
with_or_init_signals(|s| s.pedometer.clone())
}
pub fn use_heart_rate() -> Signal<HeartRateReading> {
if let Some(live) = crate::os_sensors::probe_os_heart_rate() {
DeviceMockController::new().set_heart_rate(live);
}
with_or_init_signals(|s| s.heart_rate.clone())
}
type MemoryPressureCallback = Box<dyn Fn(MemoryPressure) + Send + Sync + 'static>;
static LISTENERS: OnceLock<Mutex<HashMap<usize, MemoryPressureCallback>>> = OnceLock::new();
static NEXT_LISTENER_ID: AtomicUsize = AtomicUsize::new(1);
fn get_listeners() -> &'static Mutex<HashMap<usize, MemoryPressureCallback>> {
LISTENERS.get_or_init(|| Mutex::new(HashMap::new()))
}
pub fn on_memory_pressure<F>(callback: F) -> usize
where
F: Fn(MemoryPressure) + Send + Sync + 'static,
{
let id = NEXT_LISTENER_ID.fetch_add(1, Ordering::SeqCst);
let mut listeners = get_listeners().lock().unwrap();
listeners.insert(id, Box::new(callback));
id
}
pub fn unregister_memory_pressure(id: usize) {
let mut listeners = get_listeners().lock().unwrap();
listeners.remove(&id);
}
pub fn notify_memory_pressure(level: MemoryPressure) {
let listeners = get_listeners().lock().unwrap();
for callback in listeners.values() {
callback(level);
}
}
pub fn clear_memory_pressure_listeners() {
let mut listeners = get_listeners().lock().unwrap();
listeners.clear();
}