Skip to main content

cranpose_native/
session.rs

1use std::sync::{
2    Arc, Mutex,
3    atomic::{AtomicBool, Ordering},
4    mpsc,
5};
6
7use tokio::sync::oneshot;
8
9use crate::{NativeContent, worker};
10
11/// A native hosting failure.
12#[derive(Debug, thiserror::Error, uniffi::Error)]
13pub enum NativeError {
14    /// The component has shut down.
15    #[error("component is closed")]
16    Closed,
17    /// Rendering or platform integration failed.
18    #[error("{detail}")]
19    Runtime {
20        /// Description of the failure.
21        detail: String,
22    },
23}
24
25/// One application event exchanged with the native host.
26#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
27pub struct NativeEvent {
28    /// Application-defined event name.
29    pub name: String,
30    /// Application-defined event value.
31    pub value: String,
32}
33
34/// What one finger did, in logical host coordinates.
35#[derive(Clone, Copy, uniffi::Enum)]
36pub enum TouchPhase {
37    /// The finger touched. The first finger down starts a gesture; each one
38    /// after it joins that gesture, as a pinch's second finger does.
39    Down,
40    /// The finger moved.
41    Move,
42    /// The finger lifted. The first finger's lift ends the gesture.
43    Up,
44    /// The system took the finger, as a scrolling parent does. The first
45    /// finger's cancel cancels the gesture.
46    Cancel,
47}
48
49/// One mounted native child.
50#[derive(uniffi::Record)]
51pub struct NativeSlot {
52    /// Stable identity within the session.
53    pub id: u64,
54    /// Registered platform factory name.
55    pub kind: String,
56    /// Factory configuration.
57    pub value: String,
58    /// Logical horizontal offset.
59    pub x: f32,
60    /// Logical vertical offset.
61    pub y: f32,
62    /// Logical width.
63    pub width: f32,
64    /// Logical height.
65    pub height: f32,
66}
67
68/// A presentation update. Empty pixels preserve the currently presented image and slots.
69#[derive(uniffi::Record)]
70pub struct NativeFrame {
71    /// Physical image width.
72    pub width: u32,
73    /// Physical image height.
74    pub height: u32,
75    /// Premultiplied RGBA pixels, empty when unchanged.
76    pub pixels: Vec<u8>,
77    /// Complete native-child snapshot accompanying a changed image.
78    pub slots: Vec<NativeSlot>,
79    /// Application events emitted since the preceding frame.
80    pub events: Vec<NativeEvent>,
81    /// Delay until the next scheduled update, absent when idle.
82    pub next_frame_ms: Option<u64>,
83}
84
85/// Wakes a platform view when its composition needs a frame.
86#[uniffi::export(callback_interface)]
87pub trait FrameListener: Send + Sync {
88    /// Schedule a frame on the platform UI thread.
89    fn request_frame(&self);
90}
91
92pub(crate) enum Command {
93    Frame(
94        u32,
95        u32,
96        f32,
97        oneshot::Sender<Result<NativeFrame, NativeError>>,
98    ),
99    Touch(u64, TouchPhase, f32, f32),
100    Event(NativeEvent),
101    NativeEvent(u64, String),
102    Visible(bool),
103    Close,
104}
105
106#[derive(Default)]
107pub(crate) struct Wake(Mutex<Option<Arc<dyn FrameListener>>>);
108
109impl Wake {
110    pub(crate) fn request(&self) {
111        let listener = self
112            .0
113            .lock()
114            .ok()
115            .and_then(|guard| guard.as_ref().map(Arc::clone));
116        if let Some(listener) = listener {
117            listener.request_frame();
118        }
119    }
120}
121
122/// Owns an embedded composition and its worker thread.
123///
124/// Platform `CranposeView` adapters drive this session automatically. An application
125/// creates one with `NativeSession::new` and supplies only its content and events.
126#[derive(uniffi::Object)]
127pub struct NativeSession {
128    sender: mpsc::Sender<Command>,
129    closed: AtomicBool,
130    wake: Arc<Wake>,
131}
132
133impl NativeSession {
134    /// Constructs content on the owning worker. Captures crossing into this factory
135    /// must be Send; the composition and its state stay on that worker afterwards.
136    pub fn new(factory: impl FnOnce() -> NativeContent + Send + 'static) -> Arc<Self> {
137        let (sender, receiver) = mpsc::channel();
138        let wake = Arc::new(Wake::default());
139        let worker_wake = Arc::clone(&wake);
140        std::thread::spawn(move || worker::run(receiver, factory, worker_wake));
141        Arc::new(Self {
142            sender,
143            closed: AtomicBool::new(false),
144            wake,
145        })
146    }
147
148    fn send(&self, command: Command) -> Result<(), NativeError> {
149        if self.closed.load(Ordering::Acquire) {
150            return Err(NativeError::Closed);
151        }
152        self.sender.send(command).map_err(|_| NativeError::Closed)
153    }
154}
155
156#[uniffi::export]
157#[expect(clippy::multiple_inherent_impl, reason = "uniffi exports whole impls")]
158impl NativeSession {
159    /// Attaches the platform frame callback and requests an initial frame.
160    pub fn set_listener(&self, listener: Box<dyn FrameListener>) -> Result<(), NativeError> {
161        if self.closed.load(Ordering::Acquire) {
162            return Err(NativeError::Closed);
163        }
164        *self.wake.0.lock().map_err(|_| NativeError::Closed)? = Some(Arc::from(listener));
165        self.wake.request();
166        Ok(())
167    }
168
169    /// Produces the next presentation update. Platform adapters serialize these calls.
170    pub async fn frame(
171        &self,
172        width: u32,
173        height: u32,
174        density: f32,
175    ) -> Result<NativeFrame, NativeError> {
176        let (sender, receiver) = oneshot::channel();
177        self.send(Command::Frame(width, height, density, sender))?;
178        receiver.await.map_err(|_| NativeError::Closed)?
179    }
180
181    /// Delivers application input without exposing rendering internals.
182    pub fn send_event(&self, name: String, value: String) -> Result<(), NativeError> {
183        self.send(Command::Event(NativeEvent { name, value }))?;
184        self.wake.request();
185        Ok(())
186    }
187
188    /// Routes what the finger `pointer` did, at `(x, y)` in logical points.
189    /// `pointer` names one finger from its `Down` to its `Up` or `Cancel`,
190    /// as Android's pointer id does; a host gives each finger its own.
191    pub fn touch(
192        &self,
193        pointer: u64,
194        phase: TouchPhase,
195        x: f32,
196        y: f32,
197    ) -> Result<(), NativeError> {
198        self.send(Command::Touch(pointer, phase, x, y))?;
199        self.wake.request();
200        Ok(())
201    }
202
203    /// Routes a factory event from a mounted native child; stale IDs are ignored.
204    pub fn native_event(&self, id: u64, event: String) -> Result<(), NativeError> {
205        self.send(Command::NativeEvent(id, event))?;
206        self.wake.request();
207        Ok(())
208    }
209
210    /// Suspends hidden or detached content and resumes it when visible.
211    pub fn set_visible(&self, visible: bool) -> Result<(), NativeError> {
212        self.send(Command::Visible(visible))?;
213        if visible {
214            self.wake.request();
215        }
216        Ok(())
217    }
218
219    /// Releases the worker and its composition. Safe to call repeatedly.
220    pub fn shutdown(&self) {
221        if !self.closed.swap(true, Ordering::AcqRel) {
222            if let Ok(mut listener) = self.wake.0.lock() {
223                *listener = None;
224            }
225            let _ = self.sender.send(Command::Close);
226        }
227    }
228}
229
230impl Drop for NativeSession {
231    fn drop(&mut self) {
232        self.shutdown();
233    }
234}