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]
157impl NativeSession {
158    /// Attaches the platform frame callback and requests an initial frame.
159    pub fn set_listener(&self, listener: Box<dyn FrameListener>) -> Result<(), NativeError> {
160        if self.closed.load(Ordering::Acquire) {
161            return Err(NativeError::Closed);
162        }
163        *self.wake.0.lock().map_err(|_| NativeError::Closed)? = Some(Arc::from(listener));
164        self.wake.request();
165        Ok(())
166    }
167
168    /// Produces the next presentation update. Platform adapters serialize these calls.
169    pub async fn frame(
170        &self,
171        width: u32,
172        height: u32,
173        density: f32,
174    ) -> Result<NativeFrame, NativeError> {
175        let (sender, receiver) = oneshot::channel();
176        self.send(Command::Frame(width, height, density, sender))?;
177        receiver.await.map_err(|_| NativeError::Closed)?
178    }
179
180    /// Delivers application input without exposing rendering internals.
181    pub fn send_event(&self, name: String, value: String) -> Result<(), NativeError> {
182        self.send(Command::Event(NativeEvent { name, value }))?;
183        self.wake.request();
184        Ok(())
185    }
186
187    /// Routes what the finger `pointer` did, at `(x, y)` in logical points.
188    /// `pointer` names one finger from its `Down` to its `Up` or `Cancel`,
189    /// as Android's pointer id does; a host gives each finger its own.
190    pub fn touch(
191        &self,
192        pointer: u64,
193        phase: TouchPhase,
194        x: f32,
195        y: f32,
196    ) -> Result<(), NativeError> {
197        self.send(Command::Touch(pointer, phase, x, y))?;
198        self.wake.request();
199        Ok(())
200    }
201
202    /// Routes a factory event from a mounted native child; stale IDs are ignored.
203    pub fn native_event(&self, id: u64, event: String) -> Result<(), NativeError> {
204        self.send(Command::NativeEvent(id, event))?;
205        self.wake.request();
206        Ok(())
207    }
208
209    /// Suspends hidden or detached content and resumes it when visible.
210    pub fn set_visible(&self, visible: bool) -> Result<(), NativeError> {
211        self.send(Command::Visible(visible))?;
212        if visible {
213            self.wake.request();
214        }
215        Ok(())
216    }
217
218    /// Releases the worker and its composition. Safe to call repeatedly.
219    pub fn shutdown(&self) {
220        if !self.closed.swap(true, Ordering::AcqRel) {
221            if let Ok(mut listener) = self.wake.0.lock() {
222                *listener = None;
223            }
224            let _ = self.sender.send(Command::Close);
225        }
226    }
227}
228
229impl Drop for NativeSession {
230    fn drop(&mut self) {
231        self.shutdown();
232    }
233}