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, super::services::FetchFailure>>,
79 ),
80 ReadClipboard(ClipboardRead),
82 MainThread(crate::main_thread::MainThreadTask),
84 RegisterFont(Vec<u8>, AnswerSlot<Result<String, String>>),
87 PickImages(
90 crate::picker::PickRequest,
91 AnswerSlot<Vec<crate::picker::PickedFile>>,
92 ),
93 PickFiles(
96 crate::picker::FilePickRequest,
97 AnswerSlot<Vec<crate::picker::PickedFile>>,
98 ),
99 HostCall {
102 name: String,
103 args: crate::JsonValue,
104 answer: AnswerSlot<Result<crate::JsonValue, super::JsError>>,
105 },
106 HostPost {
109 name: String,
110 args: crate::JsonValue,
111 },
112 ForgetHostCalls,
115 OpenUrl(String, AnswerSlot<bool>),
119 PickScreenColor(AnswerSlot<Option<crate::Hsla>>),
122 Speech(SpeechAction),
124 Notification(NotificationAction),
126 NextUrlSchemeOpen(AnswerSlot<String>),
129 NextOpenFiles(AnswerSlot<Vec<std::path::PathBuf>>),
133 NextSecondInstance(AnswerSlot<crate::single_instance::SecondInstance>),
137 NextAppUrlChange(AnswerSlot<crate::url_scheme::AppUrlChange>),
140 AppUrl(AnswerSlot<Option<String>>),
142 SetAppUrl(String, crate::url_scheme::HistoryBehavior),
145 Audio(AudioAction),
147 WebInputAvailable(AnswerSlot<bool>),
151 WebEvaluateAvailable(AnswerSlot<bool>),
153 WebViewAvailable(AnswerSlot<bool>),
156 FileRequest(crate::file_dialog::FileRequest, FileAnswer),
159 Animation(crate::animation::AnimationOp),
161 Animate {
163 op: crate::animation::AnimationOp,
164 animation: crate::animation::AnimationId,
165 end: AnswerSlot<bool>,
166 },
167 ReadValue {
169 node: crate::animation::NodeId,
170 value: AnswerSlot<f32>,
171 },
172 ReportViewable(NodeId),
175 Hint(NodeId),
178 Frame(AnswerSlot<Instant>),
180 Appearance(crate::platform::Appearance),
182 Tokens(super::Tokens),
184 Translations(crate::i18n::Translations),
186 Locale(Option<crate::platform::Locale>),
189 BuiltInScrollbars(super::ScrollbarSource, Option<super::AnyValue>),
192 Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
195 MeasureScrollPosition(NodeId, AnswerSlot<Option<crate::ListScrollPosition>>),
199 Evaluate(
202 NodeId,
203 String,
204 std::time::Duration,
205 crate::platform::web_evaluation::Slot,
206 ),
207 WebEvaluationTimeout(u32),
209 TransitionTime(NodeId, AnswerSlot<std::time::Duration>),
212 PressAt(NodeId, crate::PressEvent, AnswerSlot<bool>),
216}
217
218pub(crate) enum SpeechAction {
221 Start {
224 id: u32,
225 request: crate::speech::SpeechRequest,
226 sink: crate::speech::SpeechSink,
227 },
228 Stop(u32),
230 Abort(u32),
232 Available(AnswerSlot<bool>),
234}
235
236pub(crate) enum AudioAction {
238 Open {
242 command: crate::audio::AudioCommand,
243 sink: crate::audio::AudioSink,
244 },
245 Command(crate::audio::AudioCommand),
247 Available(AnswerSlot<bool>),
249}
250
251pub(crate) enum NotificationAction {
253 Permission {
256 ask: bool,
257 answer: AnswerSlot<crate::notifications::NotificationPermission>,
258 },
259 Show {
261 notification: crate::notifications::Notification,
262 answer: AnswerSlot<bool>,
263 },
264 Close(String),
266 SetBadge(u32),
268 NextPress(AnswerSlot<String>),
270}
271
272pub(crate) enum FileAnswer {
275 OpenDialog(AnswerSlot<Result<Option<Vec<std::path::PathBuf>>, String>>),
277 SaveDialog(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
279 Done(AnswerSlot<Result<(), String>>),
281 Trash(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
283}
284
285impl FileAnswer {
286 pub(crate) fn deliver(self, mut paths: Vec<std::path::PathBuf>, error: Option<String>) {
289 match self {
290 FileAnswer::OpenDialog(slot) => slot.borrow_mut().deliver(match error {
291 Some(error) => Err(error),
292 None => Ok((!paths.is_empty()).then_some(paths)),
293 }),
294 FileAnswer::SaveDialog(slot) => slot.borrow_mut().deliver(match error {
295 Some(error) => Err(error),
296 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
297 }),
298 FileAnswer::Done(slot) => slot.borrow_mut().deliver(match error {
299 Some(error) => Err(error),
300 None => Ok(()),
301 }),
302 FileAnswer::Trash(slot) => slot.borrow_mut().deliver(match error {
303 Some(error) => Err(error),
304 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
305 }),
306 }
307 }
308}
309
310pub(crate) enum ClipboardRead {
312 Text(AnswerSlot<String>),
314 Has(AnswerSlot<bool>),
316 Image(AnswerSlot<Option<ClipboardImage>>),
319 CheckedImage(AnswerSlot<Result<Option<ClipboardImage>, usize>>),
322 HasImage(AnswerSlot<bool>),
324 Files(AnswerSlot<Vec<String>>),
326}
327
328#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
330pub struct ClipboardImage {
331 pub url: String,
334 pub size: Size<DevicePixels>,
336}
337
338#[derive(Debug, Clone, Copy, Default, PartialEq)]
340pub struct ImageSize {
341 pub width: DevicePixels,
343 pub height: DevicePixels,
345}
346
347impl ImageSize {
348 pub fn size(&self) -> Size<DevicePixels> {
350 Size::new(self.width, self.height)
351 }
352}
353
354impl From<ImageSize> for Size<DevicePixels> {
355 fn from(s: ImageSize) -> Self {
356 s.size()
357 }
358}
359
360impl super::JsValue for ImageSize {
362 fn ts_type(types: &mut super::TsTypes) -> String {
363 <Size<DevicePixels> as super::JsValue>::ts_type(types)
364 }
365
366 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
367 if value.kind() != super::JsKind::Object {
368 return Err(value.expected("an object"));
369 }
370 let side = |key: &str| -> Result<DevicePixels, super::PropError> {
371 let v = value.field(key)?;
372 DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
373 };
374 Ok(ImageSize {
375 width: side("width")?,
376 height: side("height")?,
377 })
378 }
379
380 fn to_js<'a>(
381 &self,
382 host: &'a dyn super::JsHost,
383 ) -> Result<super::JsOwned<'a>, super::PropError> {
384 let owned = super::JsOwned::new(host, host.new_object()?);
385 let object = owned.get().raw();
386 host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
387 host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
388 Ok(owned)
389 }
390}
391
392pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
394 Action::Command(ROOT_ID, Command::SetStatusBar(patch))
395}
396
397struct Entry {
398 host: NodeId,
399 future: Option<LocalFuture>,
401}
402
403#[derive(Default)]
404struct Inner {
405 tasks: FxHashMap<u64, Entry>,
406 next_task: u64,
407 actions: VecDeque<Action>,
408 failures: Vec<(NodeId, String)>,
409}
410
411#[derive(Default)]
413pub(crate) struct Executor {
414 inner: RefCell<Inner>,
415 ready: Arc<Ready>,
416 runtime: RefCell<Option<Handle>>,
418 animation_ids: std::cell::Cell<u32>,
421 derived: RefCell<super::animated::Derived>,
424 pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
426 pub(crate) quit: Rc<RefCell<super::quit::QuitListeners>>,
428 pub(crate) quitting: Rc<std::cell::Cell<usize>>,
430 pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
432 pub(crate) menus: Rc<RefCell<super::menus::ViewMenus>>,
434 pub(crate) watches: Rc<RefCell<super::watch::Watches>>,
436 timers: RefCell<BinaryHeap<Reverse<Timer>>>,
440 next_timer_seq: std::cell::Cell<u64>,
441 answers: RefCell<Answers>,
444 pub(crate) sounds: RefCell<super::audio::Sounds>,
446}
447
448#[derive(Default)]
450struct Answers {
451 waiting: Vec<AfterAnswer>,
453 due: Vec<AfterAnswer>,
456}
457
458pub(crate) struct AfterAnswer {
460 pub(crate) owner: super::Owner,
461 pub(crate) f: Box<dyn FnOnce()>,
462}
463
464struct Timer {
467 at: Instant,
468 seq: u64,
469 waker: Waker,
470}
471
472impl PartialEq for Timer {
473 fn eq(&self, other: &Self) -> bool {
474 (self.at, self.seq) == (other.at, other.seq)
475 }
476}
477
478impl Eq for Timer {}
479
480impl PartialOrd for Timer {
481 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
482 Some(self.cmp(other))
483 }
484}
485
486impl Ord for Timer {
487 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
488 (self.at, self.seq).cmp(&(other.at, other.seq))
489 }
490}
491
492impl Executor {
493 pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
495 self.derived.borrow_mut()
496 }
497
498 pub(crate) fn add_timer(&self, at: Instant, waker: Waker) {
500 let seq = self.next_timer_seq.get();
501 self.next_timer_seq.set(seq + 1);
502 self.timers
503 .borrow_mut()
504 .push(Reverse(Timer { at, seq, waker }));
505 }
506
507 pub(crate) fn next_timer(&self) -> Option<Instant> {
509 self.timers.borrow().peek().map(|Reverse(t)| t.at)
510 }
511
512 pub(crate) fn fire_timers(&self, now: Instant) {
514 let mut due = Vec::new();
515 {
516 let mut timers = self.timers.borrow_mut();
517 while timers.peek().is_some_and(|Reverse(t)| t.at <= now) {
518 if let Some(Reverse(timer)) = timers.pop() {
519 due.push(timer.waker);
520 }
521 }
522 }
523 for waker in due {
524 waker.wake();
525 }
526 }
527
528 pub(crate) fn next_animation_id(&self) -> u32 {
530 let n = self.animation_ids.get();
531 self.animation_ids.set(n + 1);
532 2 * n + 1
533 }
534
535 pub(crate) fn set_runtime(&self, runtime: Handle) {
536 *self.runtime.borrow_mut() = Some(runtime);
537 }
538
539 #[cfg(not(target_arch = "wasm32"))]
541 pub(crate) fn runtime(&self) -> Option<Handle> {
542 self.runtime.borrow().clone()
543 }
544
545 pub(crate) fn set_notify(&self, notify: Notify) {
546 *self.ready.notify.lock().expect("notify lock") = Some(notify);
547 }
548
549 fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
550 let id = {
551 let mut inner = self.inner.borrow_mut();
552 inner.next_task += 1;
553 let id = inner.next_task;
554 inner.tasks.insert(
555 id,
556 Entry {
557 host,
558 future: Some(future),
559 },
560 );
561 id
562 };
563 self.ready.ids.lock().expect("ready lock").push(id);
565 let notify = self.ready.notify.lock().expect("notify lock").clone();
566 if let Some(notify) = notify {
567 notify();
568 }
569 id
570 }
571
572 fn cancel(&self, id: u64) {
573 let removed = self.inner.borrow_mut().tasks.remove(&id);
574 drop(removed);
576 }
577
578 pub(crate) fn poll_ready(&self) -> bool {
580 let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
581 if ids.is_empty() {
582 return false;
583 }
584 ids.sort_unstable();
585 ids.dedup();
586 let runtime = self.runtime.borrow().clone();
588 let _context = runtime.as_ref().map(Handle::enter);
589 for id in ids {
590 let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
591 Some(entry) => entry.future.take(),
592 None => None,
593 };
594 let Some(mut future) = future else { continue };
595 let waker = Waker::from(Arc::new(TaskWaker {
596 id,
597 ready: self.ready.clone(),
598 }));
599 let done = match super::component::caught(|| {
600 future
601 .as_mut()
602 .poll(&mut TaskContext::from_waker(&waker))
603 .is_ready()
604 }) {
605 Ok(done) => done,
606 Err(message) => {
608 let mut inner = self.inner.borrow_mut();
609 if let Some(entry) = inner.tasks.get(&id) {
610 let host = entry.host;
611 inner.failures.push((host, message));
612 }
613 true
614 }
615 };
616 if done {
617 self.inner.borrow_mut().tasks.remove(&id);
618 drop(future);
619 } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
620 entry.future = Some(future);
621 }
622 }
623 true
624 }
625
626 #[cfg(test)]
627 pub(crate) fn task_count(&self) -> usize {
628 self.inner.borrow().tasks.len()
629 }
630
631 pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
633 std::mem::take(&mut self.inner.borrow_mut().failures)
634 }
635
636 pub(crate) fn take_actions(&self) -> VecDeque<Action> {
638 std::mem::take(&mut self.inner.borrow_mut().actions)
639 }
640
641 pub(crate) fn act(&self, action: Action) {
642 self.inner.borrow_mut().actions.push_back(action);
643 let notify = self.ready.notify.lock().expect("notify lock").clone();
644 if let Some(notify) = notify {
645 notify();
646 }
647 }
648
649 pub(crate) fn after_answer(&self, answer: AfterAnswer) {
652 self.answers.borrow_mut().waiting.push(answer);
653 }
654
655 pub(crate) fn hand_answers(&self) {
657 let mut answers = self.answers.borrow_mut();
658 let Answers { waiting, due } = &mut *answers;
659 if !waiting.is_empty() {
660 due.append(waiting);
661 }
662 }
663
664 pub(crate) fn has_due_answers(&self) -> bool {
666 !self.answers.borrow().due.is_empty()
667 }
668
669 #[cfg(test)]
671 pub(crate) fn answers_allocated(&self) -> bool {
672 let answers = self.answers.borrow();
673 answers.waiting.capacity() > 0 || answers.due.capacity() > 0
674 }
675
676 pub(crate) fn take_due_answers(&self) -> Vec<AfterAnswer> {
678 std::mem::take(&mut self.answers.borrow_mut().due)
679 }
680}
681
682#[must_use = "a dropped task is cancelled: keep it, or detach it"]
686pub struct Task<T> {
687 executor: Weak<Executor>,
688 id: u64,
689 output: Rc<RefCell<Output<T>>>,
690 detached: bool,
691}
692
693pub(crate) struct Output<T> {
695 pub(crate) value: Option<T>,
696 pub(crate) waker: Option<Waker>,
697}
698
699pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
701
702impl<T> Default for Output<T> {
703 fn default() -> Self {
704 Self {
705 value: None,
706 waker: None,
707 }
708 }
709}
710
711impl<T> Output<T> {
712 pub(crate) fn deliver(&mut self, value: T) {
714 self.value = Some(value);
715 if let Some(waker) = self.waker.take() {
716 waker.wake();
717 }
718 }
719}
720
721#[must_use = "an answer does nothing unless awaited"]
724pub struct Answer<T> {
725 slot: Rc<RefCell<Output<T>>>,
726}
727
728pub type DialogAnswer = Answer<i32>;
731
732impl<T> Answer<T> {
733 pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
734 let slot = Rc::new(RefCell::new(Output::default()));
735 (Self { slot: slot.clone() }, slot)
736 }
737}
738
739impl<T> std::fmt::Debug for Answer<T> {
740 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
741 f.debug_struct("Answer").finish_non_exhaustive()
742 }
743}
744
745impl<T> Future for Answer<T> {
746 type Output = T;
747
748 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
749 let mut slot = self.slot.borrow_mut();
750 match slot.value.take() {
751 Some(value) => Poll::Ready(value),
752 None => {
753 slot.waker = Some(cx.waker().clone());
754 Poll::Pending
755 }
756 }
757 }
758}
759
760impl<T> std::fmt::Debug for Task<T> {
761 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
762 f.debug_struct("Task")
763 .field("id", &self.id)
764 .finish_non_exhaustive()
765 }
766}
767
768impl<T> Task<T> {
769 pub fn detach(mut self) {
772 self.detached = true;
773 }
774}
775
776impl<T> Drop for Task<T> {
777 fn drop(&mut self) {
778 if !self.detached
779 && let Some(executor) = self.executor.upgrade()
780 {
781 executor.cancel(self.id);
782 }
783 }
784}
785
786impl<T> Future for Task<T> {
787 type Output = T;
788
789 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
790 let mut output = self.output.borrow_mut();
791 match output.value.take() {
792 Some(value) => Poll::Ready(value),
793 None => {
794 output.waker = Some(cx.waker().clone());
795 Poll::Pending
796 }
797 }
798 }
799}
800
801pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
803 executor.spawn(host, future)
804}
805
806pub(crate) fn act_after(
809 executor: &Rc<Executor>,
810 host: NodeId,
811 delay: Duration,
812 action: Action,
813) -> Task<()> {
814 let weak = Rc::downgrade(executor);
815 let acting = weak.clone();
816 let at = crate::time::now() + delay;
818 let id = executor.spawn(
819 host,
820 Box::pin(async move {
821 super::timer_until(at).await;
822 if let Some(executor) = acting.upgrade() {
823 executor.act(action);
824 }
825 }),
826 );
827 Task {
828 executor: weak,
829 id,
830 output: Rc::new(RefCell::new(Output::default())),
831 detached: false,
832 }
833}
834
835pub(crate) fn spawn_future<R: 'static>(
839 executor: &Rc<Executor>,
840 future: impl Future<Output = R> + 'static,
841) -> Task<R> {
842 let weak = Rc::downgrade(executor);
843 let output = Rc::new(RefCell::new(Output {
844 value: None,
845 waker: None,
846 }));
847 let done = output.clone();
848 let id = executor.spawn(
849 0,
850 Box::pin(async move {
851 let value = future.await;
852 let mut output = done.borrow_mut();
853 output.value = Some(value);
854 if let Some(waker) = output.waker.take() {
855 waker.wake();
856 }
857 }),
858 );
859 Task {
860 executor: weak,
861 id,
862 output,
863 detached: true,
864 }
865}
866
867pub(crate) struct TaskHandle {
869 executor: Weak<Executor>,
870 id: u64,
871}
872
873impl TaskHandle {
874 pub(crate) fn cancel(&self) {
876 if let Some(executor) = self.executor.upgrade() {
877 executor.cancel(self.id);
878 }
879 }
880}
881
882impl<T> Task<T> {
883 pub(crate) fn handle(&self) -> TaskHandle {
885 TaskHandle {
886 executor: self.executor.clone(),
887 id: self.id,
888 }
889 }
890}