1
//! POD types for the motion-sensor surface
2
//! (SUPER_PLAN_2 §1 feature 5 + research/03 §"Feature 5").
3
//!
4
//! The three raw sensors apps want — accelerometer, gyroscope,
5
//! magnetometer — each delivered as an `(x, y, z)` triple in the sensor's
6
//! natural unit. Defined here in `azul-core` so the manager + accessors
7
//! cross the FFI without `azul-layout` being a dependency. The stateful
8
//! side lives in `azul_layout::managers::sensors::SensorManager`.
9
//!
10
//! Coordinate frame (research/03 §coordinate-frame): right-handed,
11
//! +X right, +Y up, +Z out of the screen toward the user, in the device's
12
//! default-portrait frame (iOS keeps the device frame regardless of UI
13
//! orientation; Android auto-rotates only fused sensors). v1 reports the
14
//! raw device frame.
15

            
16
/// Which motion sensor a [`SensorReading`] came from.
17
#[repr(C)]
18
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
19
pub enum SensorKind {
20
    /// Linear acceleration including gravity, in **m/s²**
21
    /// (iOS `CMAccelerometerData` ×9.80665, Android `TYPE_ACCELEROMETER`).
22
    Accelerometer,
23
    /// Angular velocity, in **rad/s** (iOS `CMGyroData`, Android
24
    /// `TYPE_GYROSCOPE`).
25
    Gyroscope,
26
    /// Geomagnetic field, in **µT** (iOS `magneticField`, Android
27
    /// `TYPE_MAGNETIC_FIELD`).
28
    Magnetometer,
29
    // APPENDED at the end for ABI stability. The three above are the hard
30
    // ones — they need real per-OS backends and have them. Most of what
31
    // follows is DERIVED by the OS from those three, which is exactly why it
32
    // is worth exposing rather than making every app redo the fusion badly.
33
    /// Device orientation as a unit quaternion, x/y/z carrying the vector
34
    /// part (Android `TYPE_ROTATION_VECTOR`, iOS `CMAttitude.quaternion`).
35
    ///
36
    /// The OS fuses accelerometer, gyroscope and magnetometer to produce it,
37
    /// with drift correction an app cannot reproduce from the raw three.
38
    RotationVector,
39
    /// Gravity alone, in **m/s²** — the accelerometer with device motion
40
    /// removed (Android `TYPE_GRAVITY`, iOS `CMDeviceMotion.gravity`).
41
    Gravity,
42
    /// Device motion alone, in **m/s²** — the accelerometer with gravity
43
    /// removed (Android `TYPE_LINEAR_ACCELERATION`,
44
    /// iOS `CMDeviceMotion.userAcceleration`).
45
    ///
46
    /// `Gravity` and this always sum to `Accelerometer`; they are separate
47
    /// kinds because the split is what the OS's fusion buys you.
48
    LinearAcceleration,
49
    /// Illuminance in **lux**, in `x`. `y`/`z` unused.
50
    ///
51
    /// The signal behind "adapt to a dark room" — a UI dimming itself,
52
    /// a camera view raising exposure.
53
    AmbientLight,
54
    /// Proximity in **cm**, in `x`. `y`/`z` unused. The RAW distance, where
55
    /// the platform reports one (Android, Linux iio).
56
    ///
57
    /// Many phone sensors are binary and report only their maximum range or
58
    /// `0.0`; the TYPED answer - [`Proximity::Near`], [`Proximity::Far`] or a
59
    /// [`Proximity::Distance`] - is `CallbackInfo::get_proximity`, which is
60
    /// also the only form the boolean sensors (iOS, Windows `IsDetected`)
61
    /// can fill (8e-i-a-i, 8e-i-a-ii).
62
    Proximity,
63
    /// Atmospheric pressure in **hPa**, in `x`. `y`/`z` unused. Used for
64
    /// relative altitude, which GPS gives poorly.
65
    Barometer,
66
    /// Cumulative step count since boot, in `x`. `y`/`z` unused.
67
    ///
68
    /// Monotonic and NOT resettable — an app takes differences against its
69
    /// own baseline rather than expecting it to start at zero.
70
    StepCounter,
71
    /// Foldable hinge angle in **degrees**, in `x`: `0.0` fully closed,
72
    /// `180.0` flat. `y`/`z` unused.
73
    ///
74
    /// A LAYOUT input more than a sensor. Android exposes it as
75
    /// `TYPE_HINGE_ANGLE` and the web as `DevicePosture`, and it is the only
76
    /// way to tell a book-posture fold from a laptop-posture one — which
77
    /// decides whether a two-pane layout should split across the crease.
78
    HingeAngle,
79
}
80

            
81
impl SensorKind {
82
    /// How many kinds exist — the length of a slot array indexed by
83
    /// [`Self::slot`].
84
    pub const COUNT: usize = 11;
85

            
86
    /// Dense index for this kind, for a fixed-size slot array.
87
    ///
88
    /// An array rather than one named field per kind: the set grew from 3 to
89
    /// 11 and would have needed a new field, two new match arms and a new
90
    /// accessor each time. Indexing keeps adding a kind to one line.
91
    #[must_use]
92
5172
    pub const fn slot(self) -> usize {
93
5172
        match self {
94
1955
            Self::Accelerometer => 0,
95
1625
            Self::Gyroscope => 1,
96
1592
            Self::Magnetometer => 2,
97
            Self::RotationVector => 3,
98
            Self::Gravity => 4,
99
            Self::LinearAcceleration => 5,
100
            Self::AmbientLight => 6,
101
            Self::Proximity => 7,
102
            Self::Barometer => 8,
103
            Self::StepCounter => 9,
104
            Self::HingeAngle => 10,
105
        }
106
5172
    }
107
}
108

            
109
/// One `(x, y, z)` sample from a motion sensor. Units depend on
110
/// [`SensorReading::kind`] (see [`SensorKind`]). All POD / `Copy`.
111
#[repr(C)]
112
#[derive(Debug, Clone, Copy, PartialEq)]
113
pub struct SensorReading {
114
    /// Which sensor produced this reading.
115
    pub kind: SensorKind,
116
    /// X axis (device frame: right), in the kind's unit.
117
    pub x: f32,
118
    /// Y axis (device frame: up), in the kind's unit.
119
    pub y: f32,
120
    /// Z axis (device frame: out of screen toward user), in the kind's unit.
121
    pub z: f32,
122
    /// Monotonic timestamp in milliseconds since program start.
123
    pub timestamp_ms: u64,
124
}
125

            
126
impl SensorReading {
127
    /// The magnitude of the `(x, y, z)` vector — e.g. total acceleration
128
    /// (≈9.81 at rest for the accelerometer) or field strength.
129
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
130
    #[must_use]
131
3471
    pub fn magnitude(&self) -> f32 {
132
3471
        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
133
3471
    }
134
}
135

            
136
// FFI Option wrapper for `CallbackInfo::get_sensor_reading(kind) ->
137
// Option<SensorReading>` (mirrors `OptionLocationFix`).
138
impl_option!(
139
    SensorReading,
140
    OptionSensorReading,
141
    [Debug, Clone, Copy, PartialEq]
142
);
143

            
144
/// The length unit of a [`ProximityDistance`] - the sensor's NATIVE unit,
145
/// kept rather than converted so no precision is invented: Windows reports
146
/// millimetres, Android centimetres, Linux iio metres.
147
#[repr(C)]
148
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
149
pub enum DistanceUnit {
150
    Millimeters,
151
    Centimeters,
152
    Meters,
153
}
154

            
155
/// A measured distance to the nearest object, from a RANGING proximity
156
/// sensor (8e-i-a-i, 8e-i-a-ii).
157
#[repr(C)]
158
#[derive(Debug, Clone, Copy, PartialEq)]
159
pub struct ProximityDistance {
160
    pub value: f32,
161
    pub unit: DistanceUnit,
162
}
163

            
164
impl ProximityDistance {
165
    #[must_use]
166
5
    pub fn in_millimeters(&self) -> f32 {
167
5
        match self.unit {
168
2
            DistanceUnit::Millimeters => self.value,
169
1
            DistanceUnit::Centimeters => self.value * 10.0,
170
2
            DistanceUnit::Meters => self.value * 1000.0,
171
        }
172
5
    }
173

            
174
    #[must_use]
175
2
    pub fn in_centimeters(&self) -> f32 {
176
2
        self.in_millimeters() / 10.0
177
2
    }
178

            
179
    #[must_use]
180
1
    pub fn in_meters(&self) -> f32 {
181
1
        self.in_millimeters() / 1000.0
182
1
    }
183
}
184

            
185
/// What the proximity sensor says (8e-i-a-i, 8e-i-a-ii; USER RULING
186
/// 2026-09-03): a proper model instead of a distance with a made-up value
187
/// for "far".
188
///
189
/// Most phone sensors are BINARY - iOS exposes only
190
/// `UIDevice.proximityState`, Windows only `IsDetected` unless the sensor
191
/// also ranges - and answer [`Self::Near`] / [`Self::Far`]. A ranging sensor
192
/// answers [`Self::Distance`] in its native unit, and whether that is "near"
193
/// is the app's call: a distance is a measurement, not a verdict.
194
#[repr(C, u8)]
195
#[derive(Debug, Clone, Copy, PartialEq)]
196
// `Distance` carries a reading and the other two are bare tags; that asymmetry
197
// is the point of the type (a ranging sensor reports a number, a binary sensor
198
// reports near/far) and boxing an f32 to even the variants out would be worse.
199
#[allow(variant_size_differences)]
200
pub enum Proximity {
201
    /// Something is close - a phone at the ear, a hand over the sensor.
202
    Near,
203
    /// Nothing within the sensor's range.
204
    Far,
205
    /// A measured distance (ranging sensors only).
206
    Distance(ProximityDistance),
207
}
208

            
209
impl Proximity {
210
    /// `Some(true)` near, `Some(false)` far, `None` for a distance - which
211
    /// only the app can turn into a verdict, against its own threshold.
212
    #[must_use]
213
3
    pub const fn is_near(&self) -> Option<bool> {
214
3
        match self {
215
1
            Self::Near => Some(true),
216
1
            Self::Far => Some(false),
217
1
            Self::Distance(_) => None,
218
        }
219
3
    }
220
}
221

            
222
// FFI Option wrapper for `CallbackInfo::get_proximity() -> Option<Proximity>`.
223
impl_option!(Proximity, OptionProximity, [Debug, Clone, Copy, PartialEq]);
224

            
225
#[cfg(test)]
226
#[path = "sensors_test.rs"]
227
mod sensors_test;