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]
157impl NativeSession {
158 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 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 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 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 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 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 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}