1use std::{
13 cell::RefCell,
14 cmp::Reverse,
15 collections::{BinaryHeap, VecDeque},
16 future::Future,
17 pin::Pin,
18 rc::{Rc, Weak},
19 sync::{Arc, Mutex},
20 task::{Context as TaskContext, Poll, Wake, Waker},
21 time::Duration,
22};
23
24use rustc_hash::FxHashMap;
25use tokio::runtime::Handle;
26
27use crate::{
28 Command, Dialog, NodeId, ROOT_ID, StatusBarSetting,
29 geometry::{DevicePixels, Size},
30 time::Instant,
31};
32
33type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
34
35pub(crate) type Notify = Arc<dyn Fn() + Send + Sync>;
37
38#[derive(Default)]
40struct Ready {
41 ids: Mutex<Vec<u64>>,
42 notify: Mutex<Option<Notify>>,
43}
44
45struct TaskWaker {
46 id: u64,
47 ready: Arc<Ready>,
48}
49
50impl Wake for TaskWaker {
51 fn wake(self: Arc<Self>) {
52 self.wake_by_ref();
53 }
54
55 fn wake_by_ref(self: &Arc<Self>) {
56 self.ready.ids.lock().expect("ready lock").push(self.id);
57 let notify = self.ready.notify.lock().expect("notify lock").clone();
58 if let Some(notify) = notify {
59 notify();
60 }
61 }
62}
63
64pub(crate) enum Action {
66 Command(NodeId, Command),
67 Dialog(Dialog, Rc<RefCell<Output<i32>>>),
69 Return(u32, super::JsResult),
71 ImageInfo(String, AnswerSlot<Result<ImageSize, String>>),
74 Fetch(
77 Box<crate::platform::HttpRequest>,
78 AnswerSlot<Result<super::services::HttpResponse, String>>,
79 ),
80 ReadClipboard(ClipboardRead),
82 Animation(crate::animation::AnimationOp),
84 Animate {
86 op: crate::animation::AnimationOp,
87 animation: crate::animation::AnimationId,
88 end: AnswerSlot<bool>,
89 },
90 ReadValue {
92 node: crate::animation::NodeId,
93 value: AnswerSlot<f32>,
94 },
95 ReportViewable(NodeId),
98 Hint(NodeId),
101 Frame(AnswerSlot<Instant>),
103 Appearance(crate::platform::Appearance),
105 Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
108}
109
110pub(crate) enum ClipboardRead {
112 Text(AnswerSlot<String>),
114 Has(AnswerSlot<bool>),
116 Image(AnswerSlot<Option<ClipboardImage>>),
118 HasImage(AnswerSlot<bool>),
120 Files(AnswerSlot<Vec<String>>),
122}
123
124#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
126pub struct ClipboardImage {
127 pub url: String,
130 pub size: Size<DevicePixels>,
132}
133
134#[derive(Debug, Clone, Copy, Default, PartialEq)]
137pub struct ImageSize {
138 pub width: DevicePixels,
140 pub height: DevicePixels,
142}
143
144impl ImageSize {
145 pub fn size(&self) -> Size<DevicePixels> {
147 Size::new(self.width, self.height)
148 }
149}
150
151impl From<ImageSize> for Size<DevicePixels> {
152 fn from(s: ImageSize) -> Self {
153 s.size()
154 }
155}
156
157impl super::JsValue for ImageSize {
159 fn ts_type(types: &mut super::TsTypes) -> String {
160 types.declare("ImageSize", |_| {
161 "/** An image's size in pixels (`Image.getSize`). */\nexport type ImageSize = Size;"
162 .into()
163 })
164 }
165
166 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
167 if value.kind() != super::JsKind::Object {
168 return Err(value.expected("an object"));
169 }
170 let side = |key: &str| -> Result<DevicePixels, super::PropError> {
171 let v = value.field(key)?;
172 DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
173 };
174 Ok(ImageSize {
175 width: side("width")?,
176 height: side("height")?,
177 })
178 }
179
180 fn to_js<'a>(
181 &self,
182 host: &'a dyn super::JsHost,
183 ) -> Result<super::JsOwned<'a>, super::PropError> {
184 let owned = super::JsOwned::new(host, host.new_object()?);
185 let object = owned.get().raw();
186 host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
187 host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
188 Ok(owned)
189 }
190}
191
192pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
194 Action::Command(ROOT_ID, Command::SetStatusBar(patch))
195}
196
197struct Entry {
198 host: NodeId,
199 future: Option<LocalFuture>,
201}
202
203#[derive(Default)]
204struct Inner {
205 tasks: FxHashMap<u64, Entry>,
206 next_task: u64,
207 actions: VecDeque<Action>,
208 failures: Vec<(NodeId, String)>,
209}
210
211#[derive(Default)]
213pub(crate) struct Executor {
214 inner: RefCell<Inner>,
215 ready: Arc<Ready>,
216 runtime: RefCell<Option<Handle>>,
218 animation_ids: std::cell::Cell<u32>,
221 derived: RefCell<super::animated::Derived>,
224 pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
226 pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
228 timers: RefCell<BinaryHeap<Reverse<Timer>>>,
232 next_timer_seq: std::cell::Cell<u64>,
233}
234
235struct Timer {
238 at: Instant,
239 seq: u64,
240 waker: Waker,
241}
242
243impl PartialEq for Timer {
244 fn eq(&self, other: &Self) -> bool {
245 (self.at, self.seq) == (other.at, other.seq)
246 }
247}
248
249impl Eq for Timer {}
250
251impl PartialOrd for Timer {
252 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
253 Some(self.cmp(other))
254 }
255}
256
257impl Ord for Timer {
258 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
259 (self.at, self.seq).cmp(&(other.at, other.seq))
260 }
261}
262
263impl Executor {
264 pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
266 self.derived.borrow_mut()
267 }
268
269 pub(crate) fn add_timer(&self, at: Instant, waker: Waker) {
271 let seq = self.next_timer_seq.get();
272 self.next_timer_seq.set(seq + 1);
273 self.timers
274 .borrow_mut()
275 .push(Reverse(Timer { at, seq, waker }));
276 }
277
278 pub(crate) fn next_timer(&self) -> Option<Instant> {
280 self.timers.borrow().peek().map(|Reverse(t)| t.at)
281 }
282
283 pub(crate) fn fire_timers(&self, now: Instant) {
285 let mut due = Vec::new();
286 {
287 let mut timers = self.timers.borrow_mut();
288 while timers.peek().is_some_and(|Reverse(t)| t.at <= now) {
289 if let Some(Reverse(timer)) = timers.pop() {
290 due.push(timer.waker);
291 }
292 }
293 }
294 for waker in due {
295 waker.wake();
296 }
297 }
298
299 pub(crate) fn next_animation_id(&self) -> u32 {
301 let n = self.animation_ids.get();
302 self.animation_ids.set(n + 1);
303 2 * n + 1
304 }
305
306 pub(crate) fn set_runtime(&self, runtime: Handle) {
307 *self.runtime.borrow_mut() = Some(runtime);
308 }
309
310 pub(crate) fn set_notify(&self, notify: Notify) {
311 *self.ready.notify.lock().expect("notify lock") = Some(notify);
312 }
313
314 fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
315 let id = {
316 let mut inner = self.inner.borrow_mut();
317 inner.next_task += 1;
318 let id = inner.next_task;
319 inner.tasks.insert(
320 id,
321 Entry {
322 host,
323 future: Some(future),
324 },
325 );
326 id
327 };
328 self.ready.ids.lock().expect("ready lock").push(id);
330 let notify = self.ready.notify.lock().expect("notify lock").clone();
331 if let Some(notify) = notify {
332 notify();
333 }
334 id
335 }
336
337 fn cancel(&self, id: u64) {
338 let removed = self.inner.borrow_mut().tasks.remove(&id);
339 drop(removed);
341 }
342
343 pub(crate) fn poll_ready(&self) -> bool {
345 let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
346 if ids.is_empty() {
347 return false;
348 }
349 ids.sort_unstable();
350 ids.dedup();
351 let runtime = self.runtime.borrow().clone();
353 let _context = runtime.as_ref().map(Handle::enter);
354 for id in ids {
355 let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
356 Some(entry) => entry.future.take(),
357 None => None,
358 };
359 let Some(mut future) = future else { continue };
360 let waker = Waker::from(Arc::new(TaskWaker {
361 id,
362 ready: self.ready.clone(),
363 }));
364 let done = match super::component::caught(|| {
365 future
366 .as_mut()
367 .poll(&mut TaskContext::from_waker(&waker))
368 .is_ready()
369 }) {
370 Ok(done) => done,
371 Err(message) => {
373 let mut inner = self.inner.borrow_mut();
374 if let Some(entry) = inner.tasks.get(&id) {
375 let host = entry.host;
376 inner.failures.push((host, message));
377 }
378 true
379 }
380 };
381 if done {
382 self.inner.borrow_mut().tasks.remove(&id);
383 drop(future);
384 } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
385 entry.future = Some(future);
386 }
387 }
388 true
389 }
390
391 #[cfg(test)]
392 pub(crate) fn task_count(&self) -> usize {
393 self.inner.borrow().tasks.len()
394 }
395
396 pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
398 std::mem::take(&mut self.inner.borrow_mut().failures)
399 }
400
401 pub(crate) fn take_actions(&self) -> VecDeque<Action> {
403 std::mem::take(&mut self.inner.borrow_mut().actions)
404 }
405
406 pub(crate) fn act(&self, action: Action) {
407 self.inner.borrow_mut().actions.push_back(action);
408 let notify = self.ready.notify.lock().expect("notify lock").clone();
409 if let Some(notify) = notify {
410 notify();
411 }
412 }
413}
414
415#[must_use = "a dropped task is cancelled: keep it, or detach it"]
419pub struct Task<T> {
420 executor: Weak<Executor>,
421 id: u64,
422 output: Rc<RefCell<Output<T>>>,
423 detached: bool,
424}
425
426pub(crate) struct Output<T> {
428 pub(crate) value: Option<T>,
429 pub(crate) waker: Option<Waker>,
430}
431
432pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
434
435impl<T> Default for Output<T> {
436 fn default() -> Self {
437 Self {
438 value: None,
439 waker: None,
440 }
441 }
442}
443
444impl<T> Output<T> {
445 pub(crate) fn deliver(&mut self, value: T) {
447 self.value = Some(value);
448 if let Some(waker) = self.waker.take() {
449 waker.wake();
450 }
451 }
452}
453
454#[must_use = "an answer does nothing unless awaited"]
457pub struct Answer<T> {
458 slot: Rc<RefCell<Output<T>>>,
459}
460
461pub type DialogAnswer = Answer<i32>;
464
465impl<T> Answer<T> {
466 pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
467 let slot = Rc::new(RefCell::new(Output::default()));
468 (Self { slot: slot.clone() }, slot)
469 }
470}
471
472impl<T> std::fmt::Debug for Answer<T> {
473 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474 f.debug_struct("Answer").finish_non_exhaustive()
475 }
476}
477
478impl<T> Future for Answer<T> {
479 type Output = T;
480
481 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
482 let mut slot = self.slot.borrow_mut();
483 match slot.value.take() {
484 Some(value) => Poll::Ready(value),
485 None => {
486 slot.waker = Some(cx.waker().clone());
487 Poll::Pending
488 }
489 }
490 }
491}
492
493impl<T> std::fmt::Debug for Task<T> {
494 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
495 f.debug_struct("Task")
496 .field("id", &self.id)
497 .finish_non_exhaustive()
498 }
499}
500
501impl<T> Task<T> {
502 pub fn detach(mut self) {
505 self.detached = true;
506 }
507}
508
509impl<T> Drop for Task<T> {
510 fn drop(&mut self) {
511 if !self.detached
512 && let Some(executor) = self.executor.upgrade()
513 {
514 executor.cancel(self.id);
515 }
516 }
517}
518
519impl<T> Future for Task<T> {
520 type Output = T;
521
522 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
523 let mut output = self.output.borrow_mut();
524 match output.value.take() {
525 Some(value) => Poll::Ready(value),
526 None => {
527 output.waker = Some(cx.waker().clone());
528 Poll::Pending
529 }
530 }
531 }
532}
533
534pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
536 executor.spawn(host, future)
537}
538
539pub(crate) fn act_after(
542 executor: &Rc<Executor>,
543 host: NodeId,
544 delay: Duration,
545 action: Action,
546) -> Task<()> {
547 let weak = Rc::downgrade(executor);
548 let acting = weak.clone();
549 let at = crate::time::now() + delay;
551 let id = executor.spawn(
552 host,
553 Box::pin(async move {
554 super::ambient::timer_until(at).await;
555 if let Some(executor) = acting.upgrade() {
556 executor.act(action);
557 }
558 }),
559 );
560 Task {
561 executor: weak,
562 id,
563 output: Rc::new(RefCell::new(Output::default())),
564 detached: false,
565 }
566}
567
568pub(crate) fn spawn_future<R: 'static>(
572 executor: &Rc<Executor>,
573 future: impl Future<Output = R> + 'static,
574) -> Task<R> {
575 let weak = Rc::downgrade(executor);
576 let output = Rc::new(RefCell::new(Output {
577 value: None,
578 waker: None,
579 }));
580 let done = output.clone();
581 let id = executor.spawn(
582 0,
583 Box::pin(async move {
584 let value = future.await;
585 let mut output = done.borrow_mut();
586 output.value = Some(value);
587 if let Some(waker) = output.waker.take() {
588 waker.wake();
589 }
590 }),
591 );
592 Task {
593 executor: weak,
594 id,
595 output,
596 detached: true,
597 }
598}
599
600pub(crate) struct TaskHandle {
602 executor: Weak<Executor>,
603 id: u64,
604}
605
606impl TaskHandle {
607 pub(crate) fn cancel(&self) {
609 if let Some(executor) = self.executor.upgrade() {
610 executor.cancel(self.id);
611 }
612 }
613}
614
615impl<T> Task<T> {
616 pub(crate) fn handle(&self) -> TaskHandle {
618 TaskHandle {
619 executor: self.executor.clone(),
620 id: self.id,
621 }
622 }
623}