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#[derive(Debug, thiserror::Error, uniffi::Error)]
13pub enum NativeError {
14 #[error("component is closed")]
16 Closed,
17 #[error("{detail}")]
19 Runtime {
20 detail: String,
22 },
23}
24
25#[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)]
27pub struct NativeEvent {
28 pub name: String,
30 pub value: String,
32}
33
34#[derive(Clone, Copy, uniffi::Enum)]
36pub enum TouchPhase {
37 Down,
40 Move,
42 Up,
44 Cancel,
47}
48
49#[derive(uniffi::Record)]
51pub struct NativeSlot {
52 pub id: u64,
54 pub kind: String,
56 pub value: String,
58 pub x: f32,
60 pub y: f32,
62 pub width: f32,
64 pub height: f32,
66}
67
68#[derive(uniffi::Record)]
70pub struct NativeFrame {
71 pub width: u32,
73 pub height: u32,
75 pub pixels: Vec<u8>,
77 pub slots: Vec<NativeSlot>,
79 pub events: Vec<NativeEvent>,
81 pub next_frame_ms: Option<u64>,
83}
84
85#[uniffi::export(callback_interface)]
87pub trait FrameListener: Send + Sync {
88 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#[derive(uniffi::Object)]
127pub struct NativeSession {
128 sender: mpsc::Sender<Command>,
129 closed: AtomicBool,
130 wake: Arc<Wake>,
131}
132
133impl NativeSession {
134 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 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 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 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 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 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 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 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}