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 PickImages(
85 crate::picker::PickRequest,
86 AnswerSlot<Vec<crate::picker::PickedFile>>,
87 ),
88 HostCall {
91 name: String,
92 args: crate::JsonValue,
93 answer: AnswerSlot<Result<crate::JsonValue, super::JsError>>,
94 },
95 ForgetHostCalls,
98 OpenUrl(String, AnswerSlot<bool>),
102 PickScreenColor(AnswerSlot<Option<crate::Hsla>>),
105 Speech(SpeechAction),
107 WebInputAvailable(AnswerSlot<bool>),
111 FileRequest(crate::file_dialog::FileRequest, FileAnswer),
114 Animation(crate::animation::AnimationOp),
116 Animate {
118 op: crate::animation::AnimationOp,
119 animation: crate::animation::AnimationId,
120 end: AnswerSlot<bool>,
121 },
122 ReadValue {
124 node: crate::animation::NodeId,
125 value: AnswerSlot<f32>,
126 },
127 ReportViewable(NodeId),
130 Hint(NodeId),
133 Frame(AnswerSlot<Instant>),
135 Appearance(crate::platform::Appearance),
137 Tokens(super::Tokens),
139 BuiltInScrollbars(super::ScrollbarSource, Option<super::AnyValue>),
142 Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
145 TransitionTime(NodeId, AnswerSlot<std::time::Duration>),
148}
149
150pub(crate) enum SpeechAction {
153 Start {
156 id: u32,
157 request: crate::speech::SpeechRequest,
158 sink: crate::speech::SpeechSink,
159 },
160 Stop(u32),
162 Abort(u32),
164 Available(AnswerSlot<bool>),
166}
167
168pub(crate) enum FileAnswer {
171 OpenDialog(AnswerSlot<Result<Option<Vec<std::path::PathBuf>>, String>>),
173 SaveDialog(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
175 Done(AnswerSlot<Result<(), String>>),
177 Trash(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
179}
180
181impl FileAnswer {
182 pub(crate) fn deliver(self, mut paths: Vec<std::path::PathBuf>, error: Option<String>) {
185 match self {
186 FileAnswer::OpenDialog(slot) => slot.borrow_mut().deliver(match error {
187 Some(error) => Err(error),
188 None => Ok((!paths.is_empty()).then_some(paths)),
189 }),
190 FileAnswer::SaveDialog(slot) => slot.borrow_mut().deliver(match error {
191 Some(error) => Err(error),
192 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
193 }),
194 FileAnswer::Done(slot) => slot.borrow_mut().deliver(match error {
195 Some(error) => Err(error),
196 None => Ok(()),
197 }),
198 FileAnswer::Trash(slot) => slot.borrow_mut().deliver(match error {
199 Some(error) => Err(error),
200 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
201 }),
202 }
203 }
204}
205
206pub(crate) enum ClipboardRead {
208 Text(AnswerSlot<String>),
210 Has(AnswerSlot<bool>),
212 Image(AnswerSlot<Option<ClipboardImage>>),
215 CheckedImage(AnswerSlot<Result<Option<ClipboardImage>, usize>>),
218 HasImage(AnswerSlot<bool>),
220 Files(AnswerSlot<Vec<String>>),
222}
223
224#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
226pub struct ClipboardImage {
227 pub url: String,
230 pub size: Size<DevicePixels>,
232}
233
234#[derive(Debug, Clone, Copy, Default, PartialEq)]
236pub struct ImageSize {
237 pub width: DevicePixels,
239 pub height: DevicePixels,
241}
242
243impl ImageSize {
244 pub fn size(&self) -> Size<DevicePixels> {
246 Size::new(self.width, self.height)
247 }
248}
249
250impl From<ImageSize> for Size<DevicePixels> {
251 fn from(s: ImageSize) -> Self {
252 s.size()
253 }
254}
255
256impl super::JsValue for ImageSize {
258 fn ts_type(types: &mut super::TsTypes) -> String {
259 <Size<DevicePixels> as super::JsValue>::ts_type(types)
260 }
261
262 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
263 if value.kind() != super::JsKind::Object {
264 return Err(value.expected("an object"));
265 }
266 let side = |key: &str| -> Result<DevicePixels, super::PropError> {
267 let v = value.field(key)?;
268 DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
269 };
270 Ok(ImageSize {
271 width: side("width")?,
272 height: side("height")?,
273 })
274 }
275
276 fn to_js<'a>(
277 &self,
278 host: &'a dyn super::JsHost,
279 ) -> Result<super::JsOwned<'a>, super::PropError> {
280 let owned = super::JsOwned::new(host, host.new_object()?);
281 let object = owned.get().raw();
282 host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
283 host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
284 Ok(owned)
285 }
286}
287
288pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
290 Action::Command(ROOT_ID, Command::SetStatusBar(patch))
291}
292
293struct Entry {
294 host: NodeId,
295 future: Option<LocalFuture>,
297}
298
299#[derive(Default)]
300struct Inner {
301 tasks: FxHashMap<u64, Entry>,
302 next_task: u64,
303 actions: VecDeque<Action>,
304 failures: Vec<(NodeId, String)>,
305}
306
307#[derive(Default)]
309pub(crate) struct Executor {
310 inner: RefCell<Inner>,
311 ready: Arc<Ready>,
312 runtime: RefCell<Option<Handle>>,
314 animation_ids: std::cell::Cell<u32>,
317 derived: RefCell<super::animated::Derived>,
320 pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
322 pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
324 pub(crate) menus: Rc<RefCell<super::menus::ViewMenus>>,
326 pub(crate) watches: Rc<RefCell<super::watch::Watches>>,
328 timers: RefCell<BinaryHeap<Reverse<Timer>>>,
332 next_timer_seq: std::cell::Cell<u64>,
333 answers: RefCell<Answers>,
336}
337
338#[derive(Default)]
340struct Answers {
341 waiting: Vec<AfterAnswer>,
343 due: Vec<AfterAnswer>,
346}
347
348pub(crate) struct AfterAnswer {
350 pub(crate) owner: super::Owner,
351 pub(crate) f: Box<dyn FnOnce()>,
352}
353
354struct Timer {
357 at: Instant,
358 seq: u64,
359 waker: Waker,
360}
361
362impl PartialEq for Timer {
363 fn eq(&self, other: &Self) -> bool {
364 (self.at, self.seq) == (other.at, other.seq)
365 }
366}
367
368impl Eq for Timer {}
369
370impl PartialOrd for Timer {
371 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
372 Some(self.cmp(other))
373 }
374}
375
376impl Ord for Timer {
377 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
378 (self.at, self.seq).cmp(&(other.at, other.seq))
379 }
380}
381
382impl Executor {
383 pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
385 self.derived.borrow_mut()
386 }
387
388 pub(crate) fn add_timer(&self, at: Instant, waker: Waker) {
390 let seq = self.next_timer_seq.get();
391 self.next_timer_seq.set(seq + 1);
392 self.timers
393 .borrow_mut()
394 .push(Reverse(Timer { at, seq, waker }));
395 }
396
397 pub(crate) fn next_timer(&self) -> Option<Instant> {
399 self.timers.borrow().peek().map(|Reverse(t)| t.at)
400 }
401
402 pub(crate) fn fire_timers(&self, now: Instant) {
404 let mut due = Vec::new();
405 {
406 let mut timers = self.timers.borrow_mut();
407 while timers.peek().is_some_and(|Reverse(t)| t.at <= now) {
408 if let Some(Reverse(timer)) = timers.pop() {
409 due.push(timer.waker);
410 }
411 }
412 }
413 for waker in due {
414 waker.wake();
415 }
416 }
417
418 pub(crate) fn next_animation_id(&self) -> u32 {
420 let n = self.animation_ids.get();
421 self.animation_ids.set(n + 1);
422 2 * n + 1
423 }
424
425 pub(crate) fn set_runtime(&self, runtime: Handle) {
426 *self.runtime.borrow_mut() = Some(runtime);
427 }
428
429 pub(crate) fn set_notify(&self, notify: Notify) {
430 *self.ready.notify.lock().expect("notify lock") = Some(notify);
431 }
432
433 fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
434 let id = {
435 let mut inner = self.inner.borrow_mut();
436 inner.next_task += 1;
437 let id = inner.next_task;
438 inner.tasks.insert(
439 id,
440 Entry {
441 host,
442 future: Some(future),
443 },
444 );
445 id
446 };
447 self.ready.ids.lock().expect("ready lock").push(id);
449 let notify = self.ready.notify.lock().expect("notify lock").clone();
450 if let Some(notify) = notify {
451 notify();
452 }
453 id
454 }
455
456 fn cancel(&self, id: u64) {
457 let removed = self.inner.borrow_mut().tasks.remove(&id);
458 drop(removed);
460 }
461
462 pub(crate) fn poll_ready(&self) -> bool {
464 let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
465 if ids.is_empty() {
466 return false;
467 }
468 ids.sort_unstable();
469 ids.dedup();
470 let runtime = self.runtime.borrow().clone();
472 let _context = runtime.as_ref().map(Handle::enter);
473 for id in ids {
474 let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
475 Some(entry) => entry.future.take(),
476 None => None,
477 };
478 let Some(mut future) = future else { continue };
479 let waker = Waker::from(Arc::new(TaskWaker {
480 id,
481 ready: self.ready.clone(),
482 }));
483 let done = match super::component::caught(|| {
484 future
485 .as_mut()
486 .poll(&mut TaskContext::from_waker(&waker))
487 .is_ready()
488 }) {
489 Ok(done) => done,
490 Err(message) => {
492 let mut inner = self.inner.borrow_mut();
493 if let Some(entry) = inner.tasks.get(&id) {
494 let host = entry.host;
495 inner.failures.push((host, message));
496 }
497 true
498 }
499 };
500 if done {
501 self.inner.borrow_mut().tasks.remove(&id);
502 drop(future);
503 } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
504 entry.future = Some(future);
505 }
506 }
507 true
508 }
509
510 #[cfg(test)]
511 pub(crate) fn task_count(&self) -> usize {
512 self.inner.borrow().tasks.len()
513 }
514
515 pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
517 std::mem::take(&mut self.inner.borrow_mut().failures)
518 }
519
520 pub(crate) fn take_actions(&self) -> VecDeque<Action> {
522 std::mem::take(&mut self.inner.borrow_mut().actions)
523 }
524
525 pub(crate) fn act(&self, action: Action) {
526 self.inner.borrow_mut().actions.push_back(action);
527 let notify = self.ready.notify.lock().expect("notify lock").clone();
528 if let Some(notify) = notify {
529 notify();
530 }
531 }
532
533 pub(crate) fn after_answer(&self, answer: AfterAnswer) {
536 self.answers.borrow_mut().waiting.push(answer);
537 }
538
539 pub(crate) fn hand_answers(&self) {
541 let mut answers = self.answers.borrow_mut();
542 let Answers { waiting, due } = &mut *answers;
543 if !waiting.is_empty() {
544 due.append(waiting);
545 }
546 }
547
548 pub(crate) fn has_due_answers(&self) -> bool {
550 !self.answers.borrow().due.is_empty()
551 }
552
553 #[cfg(test)]
555 pub(crate) fn answers_allocated(&self) -> bool {
556 let answers = self.answers.borrow();
557 answers.waiting.capacity() > 0 || answers.due.capacity() > 0
558 }
559
560 pub(crate) fn take_due_answers(&self) -> Vec<AfterAnswer> {
562 std::mem::take(&mut self.answers.borrow_mut().due)
563 }
564}
565
566#[must_use = "a dropped task is cancelled: keep it, or detach it"]
570pub struct Task<T> {
571 executor: Weak<Executor>,
572 id: u64,
573 output: Rc<RefCell<Output<T>>>,
574 detached: bool,
575}
576
577pub(crate) struct Output<T> {
579 pub(crate) value: Option<T>,
580 pub(crate) waker: Option<Waker>,
581}
582
583pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
585
586impl<T> Default for Output<T> {
587 fn default() -> Self {
588 Self {
589 value: None,
590 waker: None,
591 }
592 }
593}
594
595impl<T> Output<T> {
596 pub(crate) fn deliver(&mut self, value: T) {
598 self.value = Some(value);
599 if let Some(waker) = self.waker.take() {
600 waker.wake();
601 }
602 }
603}
604
605#[must_use = "an answer does nothing unless awaited"]
608pub struct Answer<T> {
609 slot: Rc<RefCell<Output<T>>>,
610}
611
612pub type DialogAnswer = Answer<i32>;
615
616impl<T> Answer<T> {
617 pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
618 let slot = Rc::new(RefCell::new(Output::default()));
619 (Self { slot: slot.clone() }, slot)
620 }
621}
622
623impl<T> std::fmt::Debug for Answer<T> {
624 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
625 f.debug_struct("Answer").finish_non_exhaustive()
626 }
627}
628
629impl<T> Future for Answer<T> {
630 type Output = T;
631
632 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
633 let mut slot = self.slot.borrow_mut();
634 match slot.value.take() {
635 Some(value) => Poll::Ready(value),
636 None => {
637 slot.waker = Some(cx.waker().clone());
638 Poll::Pending
639 }
640 }
641 }
642}
643
644impl<T> std::fmt::Debug for Task<T> {
645 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
646 f.debug_struct("Task")
647 .field("id", &self.id)
648 .finish_non_exhaustive()
649 }
650}
651
652impl<T> Task<T> {
653 pub fn detach(mut self) {
656 self.detached = true;
657 }
658}
659
660impl<T> Drop for Task<T> {
661 fn drop(&mut self) {
662 if !self.detached
663 && let Some(executor) = self.executor.upgrade()
664 {
665 executor.cancel(self.id);
666 }
667 }
668}
669
670impl<T> Future for Task<T> {
671 type Output = T;
672
673 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
674 let mut output = self.output.borrow_mut();
675 match output.value.take() {
676 Some(value) => Poll::Ready(value),
677 None => {
678 output.waker = Some(cx.waker().clone());
679 Poll::Pending
680 }
681 }
682 }
683}
684
685pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
687 executor.spawn(host, future)
688}
689
690pub(crate) fn act_after(
693 executor: &Rc<Executor>,
694 host: NodeId,
695 delay: Duration,
696 action: Action,
697) -> Task<()> {
698 let weak = Rc::downgrade(executor);
699 let acting = weak.clone();
700 let at = crate::time::now() + delay;
702 let id = executor.spawn(
703 host,
704 Box::pin(async move {
705 super::timer_until(at).await;
706 if let Some(executor) = acting.upgrade() {
707 executor.act(action);
708 }
709 }),
710 );
711 Task {
712 executor: weak,
713 id,
714 output: Rc::new(RefCell::new(Output::default())),
715 detached: false,
716 }
717}
718
719pub(crate) fn spawn_future<R: 'static>(
723 executor: &Rc<Executor>,
724 future: impl Future<Output = R> + 'static,
725) -> Task<R> {
726 let weak = Rc::downgrade(executor);
727 let output = Rc::new(RefCell::new(Output {
728 value: None,
729 waker: None,
730 }));
731 let done = output.clone();
732 let id = executor.spawn(
733 0,
734 Box::pin(async move {
735 let value = future.await;
736 let mut output = done.borrow_mut();
737 output.value = Some(value);
738 if let Some(waker) = output.waker.take() {
739 waker.wake();
740 }
741 }),
742 );
743 Task {
744 executor: weak,
745 id,
746 output,
747 detached: true,
748 }
749}
750
751pub(crate) struct TaskHandle {
753 executor: Weak<Executor>,
754 id: u64,
755}
756
757impl TaskHandle {
758 pub(crate) fn cancel(&self) {
760 if let Some(executor) = self.executor.upgrade() {
761 executor.cancel(self.id);
762 }
763 }
764}
765
766impl<T> Task<T> {
767 pub(crate) fn handle(&self) -> TaskHandle {
769 TaskHandle {
770 executor: self.executor.clone(),
771 id: self.id,
772 }
773 }
774}