Skip to main content

ink_rs/
input.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Stroke input: the sampled events a stroke is generated from.
6
7use core::time::Duration;
8
9use crate::error::{Result, check};
10use crate::ffi;
11use crate::geometry::Point;
12
13/// Ink spells "this optional field is absent" with sentinel values rather than
14/// an optional type. Zero means absent for a physical length, -1 for pressure
15/// and for each of the stylus angles.
16const ABSENT_LENGTH_CM: f32 = 0.0;
17const ABSENT: f32 = -1.0;
18
19fn to_sentinel(value: Option<f32>, absent: f32) -> f32 {
20    value.unwrap_or(absent)
21}
22
23fn from_sentinel(value: f32, absent: f32) -> Option<f32> {
24    if value == absent { None } else { Some(value) }
25}
26
27/// What produced an input event.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
29pub enum ToolType {
30    #[default]
31    Unknown,
32    Mouse,
33    Touch,
34    Stylus,
35}
36
37impl ToolType {
38    fn to_ffi(self) -> ffi::ToolType {
39        match self {
40            Self::Unknown => ffi::ToolType::kUnknown,
41            Self::Mouse => ffi::ToolType::kMouse,
42            Self::Touch => ffi::ToolType::kTouch,
43            Self::Stylus => ffi::ToolType::kStylus,
44        }
45    }
46
47    fn from_ffi(tool_type: ffi::ToolType) -> Self {
48        match tool_type {
49            t if t == ffi::ToolType::kMouse => Self::Mouse,
50            t if t == ffi::ToolType::kTouch => Self::Touch,
51            t if t == ffi::ToolType::kStylus => Self::Stylus,
52            _ => Self::Unknown,
53        }
54    }
55}
56
57/// One sampled input event.
58///
59/// Every field but `tool_type`, `position` and `elapsed_time` is optional, and
60/// all the inputs in a batch have to agree on which ones are present. Mixing,
61/// say, some events with pressure and some without is rejected when the batch
62/// is built.
63#[derive(Debug, Clone, Copy, PartialEq, Default)]
64pub struct StrokeInput {
65    /// What produced the event.
66    pub tool_type: ToolType,
67    /// Where it happened, in stroke units.
68    pub position: Point,
69    /// Time since the start of the stroke.
70    pub elapsed_time: Duration,
71    /// How long one stroke unit is, in centimetres. Needed by brush behaviours
72    /// that work in physical units.
73    pub stroke_unit_length_cm: Option<f32>,
74    /// Stylus or touch pressure, normally in `0.0..=1.0`.
75    pub pressure: Option<f32>,
76    /// Stylus tilt away from perpendicular, in radians.
77    pub tilt: Option<f32>,
78    /// Direction the stylus is tilted towards, in radians.
79    pub orientation: Option<f32>,
80    /// Rotation of the stylus about its own axis, in radians.
81    pub barrel_twist: Option<f32>,
82}
83
84impl StrokeInput {
85    /// The minimum an input needs: where and when.
86    pub fn new(tool_type: ToolType, position: Point, elapsed_time: Duration) -> Self {
87        Self {
88            tool_type,
89            position,
90            elapsed_time,
91            ..Default::default()
92        }
93    }
94
95    /// Adds pressure to an input.
96    pub fn with_pressure(mut self, pressure: f32) -> Self {
97        self.pressure = Some(pressure);
98        self
99    }
100
101    /// Adds stylus tilt and orientation, both in radians.
102    pub fn with_tilt_orientation(mut self, tilt: f32, orientation: f32) -> Self {
103        self.tilt = Some(tilt);
104        self.orientation = Some(orientation);
105        self
106    }
107
108    pub(crate) fn to_ffi(self) -> ffi::StrokeInput {
109        ffi::StrokeInput {
110            tool_type: self.tool_type.to_ffi(),
111            position: self.position.to_ffi(),
112            elapsed_time_seconds: self.elapsed_time.as_secs_f32(),
113            stroke_unit_length_cm: to_sentinel(self.stroke_unit_length_cm, ABSENT_LENGTH_CM),
114            pressure: to_sentinel(self.pressure, ABSENT),
115            tilt_radians: to_sentinel(self.tilt, ABSENT),
116            orientation_radians: to_sentinel(self.orientation, ABSENT),
117            barrel_twist_radians: to_sentinel(self.barrel_twist, ABSENT),
118        }
119    }
120
121    pub(crate) fn from_ffi(input: ffi::StrokeInput) -> Self {
122        Self {
123            tool_type: ToolType::from_ffi(input.tool_type),
124            position: Point::from_ffi(input.position),
125            elapsed_time: Duration::try_from_secs_f32(input.elapsed_time_seconds)
126                .unwrap_or(Duration::ZERO),
127            stroke_unit_length_cm: from_sentinel(input.stroke_unit_length_cm, ABSENT_LENGTH_CM),
128            pressure: from_sentinel(input.pressure, ABSENT),
129            tilt: from_sentinel(input.tilt_radians, ABSENT),
130            orientation: from_sentinel(input.orientation_radians, ABSENT),
131            barrel_twist: from_sentinel(input.barrel_twist_radians, ABSENT),
132        }
133    }
134}
135
136/// An ordered run of [`StrokeInput`]s.
137///
138/// Ink validates the whole batch up front: times must not go backwards, every
139/// input must report the same tool type, and the optional fields must be
140/// present on all of them or none.
141pub struct StrokeInputBatch {
142    handle: ffi::StrokeInputBatchHandle,
143}
144
145impl StrokeInputBatch {
146    /// Builds a batch from a slice of inputs.
147    pub fn new(inputs: &[StrokeInput]) -> Result<Self> {
148        Self::with_seed(inputs, 0, 0.0)
149    }
150
151    /// Builds a batch, choosing the seed for brushes with randomised noise and
152    /// the starting phase for animated brush paints.
153    pub fn with_seed(
154        inputs: &[StrokeInput],
155        noise_seed: u32,
156        base_paint_animation_phase: f32,
157    ) -> Result<Self> {
158        let converted: Vec<ffi::StrokeInput> = inputs.iter().map(|i| i.to_ffi()).collect();
159        let count = i32::try_from(converted.len()).map_err(|_| {
160            crate::error::Error::new(
161                crate::error::ErrorKind::InvalidArgument,
162                "too many stroke inputs",
163            )
164        })?;
165
166        let mut out = ffi::StrokeInputBatchHandle {
167            handle: core::ptr::null_mut(),
168        };
169        let status = unsafe {
170            ffi::StrokeInputBatchCreate(
171                converted.as_ptr(),
172                count,
173                noise_seed,
174                base_paint_animation_phase,
175                &mut out,
176            )
177        };
178        check(status)?;
179        Ok(Self::from_ffi(out))
180    }
181
182    /// An empty batch.
183    pub fn empty() -> Self {
184        Self::new(&[]).expect("an empty stroke input batch is always valid")
185    }
186
187    pub(crate) fn as_ffi(&self) -> ffi::StrokeInputBatchHandle {
188        self.handle
189    }
190
191    pub(crate) fn from_ffi(handle: ffi::StrokeInputBatchHandle) -> Self {
192        assert!(
193            !handle.handle.is_null(),
194            "ink: failed to allocate stroke input batch"
195        );
196        Self { handle }
197    }
198
199    pub fn len(&self) -> usize {
200        usize::try_from(unsafe { ffi::StrokeInputBatchSize(self.handle) }).unwrap_or(0)
201    }
202
203    pub fn is_empty(&self) -> bool {
204        self.len() == 0
205    }
206
207    /// The input at `index`, or `None` if it is past the end.
208    pub fn get(&self, index: usize) -> Option<StrokeInput> {
209        if index >= self.len() {
210            return None;
211        }
212        let index = i32::try_from(index).ok()?;
213        Some(StrokeInput::from_ffi(unsafe {
214            ffi::StrokeInputBatchGet(self.handle, index)
215        }))
216    }
217
218    /// Appends one input, which must be consistent with what is already here.
219    pub fn push(&mut self, input: StrokeInput) -> Result<()> {
220        check(unsafe { ffi::StrokeInputBatchAppend(self.handle, input.to_ffi()) })
221    }
222
223    /// Appends another batch.
224    pub fn extend_from_batch(&mut self, other: &StrokeInputBatch) -> Result<()> {
225        check(unsafe { ffi::StrokeInputBatchAppendBatch(self.handle, other.as_ffi()) })
226    }
227
228    pub fn clear(&mut self) {
229        unsafe { ffi::StrokeInputBatchClear(self.handle) };
230    }
231
232    /// Time from the first input to the last.
233    ///
234    /// Ink keeps times as `f32` seconds, so this does not round-trip exactly:
235    /// a batch built from 112ms of input reads back as 112.000003ms. Compare
236    /// with a tolerance rather than for equality.
237    pub fn duration(&self) -> Duration {
238        let seconds = unsafe { ffi::StrokeInputBatchDurationSeconds(self.handle) };
239        Duration::try_from_secs_f32(seconds).unwrap_or(Duration::ZERO)
240    }
241
242    /// The tool every input in the batch reports.
243    pub fn tool_type(&self) -> ToolType {
244        ToolType::from_ffi(unsafe { ffi::StrokeInputBatchToolType(self.handle) })
245    }
246
247    /// The seed used by brushes with randomised behaviour.
248    pub fn noise_seed(&self) -> u32 {
249        unsafe { ffi::StrokeInputBatchNoiseSeed(self.handle) }
250    }
251
252    /// Iterates over the inputs, copying each one out as it goes.
253    pub fn iter(&self) -> impl Iterator<Item = StrokeInput> + '_ {
254        (0..self.len()).filter_map(|i| self.get(i))
255    }
256}
257
258impl Clone for StrokeInputBatch {
259    fn clone(&self) -> Self {
260        Self::from_ffi(unsafe { ffi::StrokeInputBatchClone(self.handle) })
261    }
262}
263
264impl Drop for StrokeInputBatch {
265    fn drop(&mut self) {
266        unsafe { ffi::StrokeInputBatchDestroy(self.handle) };
267    }
268}
269
270impl core::fmt::Debug for StrokeInputBatch {
271    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
272        f.debug_struct("StrokeInputBatch")
273            .field("len", &self.len())
274            .field("tool_type", &self.tool_type())
275            .field("duration", &self.duration())
276            .finish()
277    }
278}
279
280impl TryFrom<&[StrokeInput]> for StrokeInputBatch {
281    type Error = crate::error::Error;
282
283    fn try_from(inputs: &[StrokeInput]) -> Result<Self> {
284        Self::new(inputs)
285    }
286}