1use std::{
13 cell::RefCell,
14 collections::{BTreeMap, VecDeque},
15 future::Future,
16 pin::Pin,
17 rc::{Rc, Weak},
18 sync::{Arc, Mutex},
19 task::{Context as TaskContext, Poll, Wake, Waker},
20 time::Duration,
21};
22
23use rustc_hash::FxHashMap;
24use tokio::runtime::Handle;
25
26use crate::{
27 Command, Dialog, NodeId, ROOT_ID, StatusBarSetting,
28 geometry::{DevicePixels, Size},
29 time::Instant,
30};
31
32type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
33
34pub(crate) type Notify = Arc<dyn Fn() + Send + Sync>;
36
37#[derive(Default)]
39struct Ready {
40 ids: Mutex<Vec<u64>>,
41 notify: Mutex<Option<Notify>>,
42}
43
44struct TaskWaker {
45 id: u64,
46 ready: Arc<Ready>,
47}
48
49impl Wake for TaskWaker {
50 fn wake(self: Arc<Self>) {
51 self.wake_by_ref();
52 }
53
54 fn wake_by_ref(self: &Arc<Self>) {
55 self.ready.ids.lock().expect("ready lock").push(self.id);
56 let notify = self.ready.notify.lock().expect("notify lock").clone();
57 if let Some(notify) = notify {
58 notify();
59 }
60 }
61}
62
63pub(crate) enum Action {
65 Command(NodeId, Command),
66 Dialog(Dialog, Rc<RefCell<Output<i32>>>),
68 Return(u32, super::JsResult),
70 ImageInfo(String, AnswerSlot<Result<ImageSize, String>>),
73 Fetch(
76 Box<crate::platform::HttpRequest>,
77 AnswerSlot<Result<super::services::HttpResponse, super::services::FetchFailure>>,
78 ),
79 ReadClipboard(ClipboardRead),
81 MainThread(crate::main_thread::MainThreadTask),
83 RegisterFont(Vec<u8>, AnswerSlot<Result<String, String>>),
86 PickImages(
89 crate::picker::PickRequest,
90 AnswerSlot<Vec<crate::picker::PickedFile>>,
91 ),
92 PickFiles(
95 crate::picker::FilePickRequest,
96 AnswerSlot<Vec<crate::picker::PickedFile>>,
97 ),
98 HostCall {
101 name: String,
102 args: crate::JsonValue,
103 answer: AnswerSlot<Result<crate::JsonValue, super::JsError>>,
104 },
105 HostPost {
108 name: String,
109 args: crate::JsonValue,
110 },
111 ForgetHostCalls,
114 OpenUrl(String, AnswerSlot<bool>),
118 PickScreenColor(AnswerSlot<Option<crate::Hsla>>),
121 Speech(SpeechAction),
123 Notification(NotificationAction),
125 NextUrlSchemeOpen(AnswerSlot<String>),
128 NextOpenFiles(AnswerSlot<Vec<std::path::PathBuf>>),
132 NextSecondInstance(AnswerSlot<crate::single_instance::SecondInstance>),
136 NextAppUrlChange(AnswerSlot<crate::url_scheme::AppUrlChange>),
139 AppUrl(AnswerSlot<Option<String>>),
141 SetAppUrl(String, crate::url_scheme::HistoryBehavior),
144 Audio(AudioAction),
146 WebInputAvailable(AnswerSlot<bool>),
150 WebEvaluateAvailable(AnswerSlot<bool>),
152 WebViewAvailable(AnswerSlot<bool>),
155 FileRequest(crate::file_dialog::FileRequest, FileAnswer),
158 Animation(crate::animation::AnimationOp),
160 Animate {
162 op: crate::animation::AnimationOp,
163 animation: crate::animation::AnimationId,
164 end: AnswerSlot<bool>,
165 },
166 ReadValue {
168 node: crate::animation::NodeId,
169 value: AnswerSlot<f32>,
170 },
171 ReportViewable(NodeId),
174 Hint(NodeId),
177 Frame(AnswerSlot<Instant>),
179 Appearance(crate::platform::Appearance),
181 Tokens(super::Tokens),
183 Translations(crate::i18n::Translations),
185 Locale(Option<crate::platform::Locale>),
188 BuiltInScrollbars(super::ScrollbarSource, Option<super::AnyValue>),
191 Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
194 MeasureScrollPosition(NodeId, AnswerSlot<Option<crate::ListScrollPosition>>),
198 Evaluate(
201 NodeId,
202 String,
203 std::time::Duration,
204 crate::platform::web_evaluation::Slot,
205 ),
206 WebEvaluationTimeout(u32),
208 TransitionTime(NodeId, AnswerSlot<std::time::Duration>),
211 PressAt(NodeId, crate::PressEvent, AnswerSlot<bool>),
215}
216
217pub(crate) enum SpeechAction {
220 Start {
223 id: u32,
224 request: crate::speech::SpeechRequest,
225 sink: crate::speech::SpeechSink,
226 },
227 Stop(u32),
229 Abort(u32),
231 Available(AnswerSlot<bool>),
233}
234
235pub(crate) enum AudioAction {
237 Open {
241 command: crate::audio::AudioCommand,
242 sink: crate::audio::AudioSink,
243 },
244 Command(crate::audio::AudioCommand),
246 Available(AnswerSlot<bool>),
248}
249
250pub(crate) enum NotificationAction {
252 Permission {
255 ask: bool,
256 answer: AnswerSlot<crate::notifications::NotificationPermission>,
257 },
258 Show {
260 notification: crate::notifications::Notification,
261 answer: AnswerSlot<bool>,
262 },
263 Close(String),
265 SetBadge(u32),
267 NextPress(AnswerSlot<String>),
269}
270
271pub(crate) enum FileAnswer {
274 OpenDialog(AnswerSlot<Result<Option<Vec<std::path::PathBuf>>, String>>),
276 SaveDialog(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
278 Done(AnswerSlot<Result<(), String>>),
280 Trash(AnswerSlot<Result<Option<std::path::PathBuf>, String>>),
282}
283
284impl FileAnswer {
285 pub(crate) fn deliver(self, mut paths: Vec<std::path::PathBuf>, error: Option<String>) {
288 match self {
289 FileAnswer::OpenDialog(slot) => slot.borrow_mut().deliver(match error {
290 Some(error) => Err(error),
291 None => Ok((!paths.is_empty()).then_some(paths)),
292 }),
293 FileAnswer::SaveDialog(slot) => slot.borrow_mut().deliver(match error {
294 Some(error) => Err(error),
295 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
296 }),
297 FileAnswer::Done(slot) => slot.borrow_mut().deliver(match error {
298 Some(error) => Err(error),
299 None => Ok(()),
300 }),
301 FileAnswer::Trash(slot) => slot.borrow_mut().deliver(match error {
302 Some(error) => Err(error),
303 None => Ok((!paths.is_empty()).then(|| paths.swap_remove(0))),
304 }),
305 }
306 }
307}
308
309pub(crate) enum ClipboardRead {
311 Text(AnswerSlot<String>),
313 Has(AnswerSlot<bool>),
315 Image(AnswerSlot<Option<ClipboardImage>>),
318 CheckedImage(AnswerSlot<Result<Option<ClipboardImage>, usize>>),
321 HasImage(AnswerSlot<bool>),
323 Files(AnswerSlot<Vec<String>>),
325}
326
327#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
329pub struct ClipboardImage {
330 pub url: String,
333 pub size: Size<DevicePixels>,
335}
336
337#[derive(Debug, Clone, Copy, Default, PartialEq)]
339pub struct ImageSize {
340 pub width: DevicePixels,
342 pub height: DevicePixels,
344}
345
346impl ImageSize {
347 pub fn size(&self) -> Size<DevicePixels> {
349 Size::new(self.width, self.height)
350 }
351}
352
353impl From<ImageSize> for Size<DevicePixels> {
354 fn from(s: ImageSize) -> Self {
355 s.size()
356 }
357}
358
359impl super::JsValue for ImageSize {
361 fn ts_type(types: &mut super::TsTypes) -> String {
362 <Size<DevicePixels> as super::JsValue>::ts_type(types)
363 }
364
365 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
366 if value.kind() != super::JsKind::Object {
367 return Err(value.expected("an object"));
368 }
369 let side = |key: &str| -> Result<DevicePixels, super::PropError> {
370 let v = value.field(key)?;
371 DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
372 };
373 Ok(ImageSize {
374 width: side("width")?,
375 height: side("height")?,
376 })
377 }
378
379 fn to_js<'a>(
380 &self,
381 host: &'a dyn super::JsHost,
382 ) -> Result<super::JsOwned<'a>, super::PropError> {
383 let owned = super::JsOwned::new(host, host.new_object()?);
384 let object = owned.get().raw();
385 host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
386 host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
387 Ok(owned)
388 }
389}
390
391pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
393 Action::Command(ROOT_ID, Command::SetStatusBar(patch))
394}
395
396struct Entry {
397 host: NodeId,
398 future: Option<LocalFuture>,
400}
401
402#[derive(Default)]
403struct Inner {
404 tasks: FxHashMap<u64, Entry>,
405 next_task: u64,
406 actions: VecDeque<Action>,
407 failures: Vec<(NodeId, String)>,
408}
409
410#[derive(Default)]
412pub(crate) struct Executor {
413 inner: RefCell<Inner>,
414 ready: Arc<Ready>,
415 runtime: RefCell<Option<Handle>>,
417 animation_ids: std::cell::Cell<u32>,
420 derived: RefCell<super::animated::Derived>,
423 pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
425 pub(crate) quit: Rc<RefCell<super::quit::QuitListeners>>,
427 pub(crate) quitting: Rc<std::cell::Cell<usize>>,
429 pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
431 pub(crate) menus: Rc<RefCell<super::menus::ViewMenus>>,
433 pub(crate) watches: Rc<RefCell<super::watch::Watches>>,
435 timers: Arc<Timers>,
439 answers: RefCell<Answers>,
442 pub(crate) sounds: RefCell<super::audio::Sounds>,
444}
445
446#[derive(Default)]
448struct Answers {
449 waiting: Vec<AfterAnswer>,
451 due: Vec<AfterAnswer>,
454}
455
456pub(crate) struct AfterAnswer {
458 pub(crate) owner: super::Owner,
459 pub(crate) f: Box<dyn FnOnce()>,
460}
461
462#[derive(Default)]
467struct Timers(Mutex<TimerQueue>);
468
469#[derive(Default)]
470struct TimerQueue {
471 next_seq: u64,
472 wakers: BTreeMap<(Instant, u64), Waker>,
473}
474
475impl Timers {
476 fn queue(&self) -> std::sync::MutexGuard<'_, TimerQueue> {
477 self.0
478 .lock()
479 .unwrap_or_else(std::sync::PoisonError::into_inner)
480 }
481}
482
483#[derive(Debug)]
486pub(crate) struct TimerKey {
487 timers: std::sync::Weak<Timers>,
488 key: (Instant, u64),
489}
490
491impl TimerKey {
492 pub(crate) fn set_waker(&self, waker: &Waker) {
495 let Some(timers) = self.timers.upgrade() else {
496 return;
497 };
498 let old = {
499 let mut queue = timers.queue();
500 match queue.wakers.get_mut(&self.key) {
501 Some(kept) if !kept.will_wake(waker) => {
502 Some(std::mem::replace(kept, waker.clone()))
503 }
504 _ => None,
505 }
506 };
507 drop(old);
509 }
510}
511
512impl Drop for TimerKey {
513 fn drop(&mut self) {
514 let Some(timers) = self.timers.upgrade() else {
515 return;
516 };
517 let waker = timers.queue().wakers.remove(&self.key);
518 drop(waker);
519 }
520}
521
522impl Executor {
523 pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
525 self.derived.borrow_mut()
526 }
527
528 pub(crate) fn add_timer(&self, at: Instant, waker: Waker) -> TimerKey {
530 let mut queue = self.timers.queue();
531 let key = (at, queue.next_seq);
532 queue.next_seq += 1;
533 queue.wakers.insert(key, waker);
534 TimerKey {
535 timers: Arc::downgrade(&self.timers),
536 key,
537 }
538 }
539
540 pub(crate) fn next_timer(&self) -> Option<Instant> {
542 self.timers
543 .queue()
544 .wakers
545 .first_key_value()
546 .map(|(&(at, _), _)| at)
547 }
548
549 pub(crate) fn fire_timers(&self, now: Instant) {
551 let mut due = Vec::new();
552 {
553 let mut queue = self.timers.queue();
554 while let Some(timer) = queue.wakers.first_entry()
555 && timer.key().0 <= now
556 {
557 due.push(timer.remove());
558 }
559 }
560 for waker in due {
562 waker.wake();
563 }
564 }
565
566 pub(crate) fn next_animation_id(&self) -> u32 {
568 let n = self.animation_ids.get();
569 self.animation_ids.set(n + 1);
570 2 * n + 1
571 }
572
573 pub(crate) fn set_runtime(&self, runtime: Handle) {
574 *self.runtime.borrow_mut() = Some(runtime);
575 }
576
577 #[cfg(not(target_arch = "wasm32"))]
579 pub(crate) fn runtime(&self) -> Option<Handle> {
580 self.runtime.borrow().clone()
581 }
582
583 pub(crate) fn set_notify(&self, notify: Notify) {
584 *self.ready.notify.lock().expect("notify lock") = Some(notify);
585 }
586
587 fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
588 let id = {
589 let mut inner = self.inner.borrow_mut();
590 inner.next_task += 1;
591 let id = inner.next_task;
592 inner.tasks.insert(
593 id,
594 Entry {
595 host,
596 future: Some(future),
597 },
598 );
599 id
600 };
601 self.ready.ids.lock().expect("ready lock").push(id);
603 let notify = self.ready.notify.lock().expect("notify lock").clone();
604 if let Some(notify) = notify {
605 notify();
606 }
607 id
608 }
609
610 fn cancel(&self, id: u64) {
611 let removed = self.inner.borrow_mut().tasks.remove(&id);
612 drop(removed);
614 }
615
616 pub(crate) fn poll_ready(&self) -> bool {
618 let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
619 if ids.is_empty() {
620 return false;
621 }
622 ids.sort_unstable();
623 ids.dedup();
624 let runtime = self.runtime.borrow().clone();
626 let _context = runtime.as_ref().map(Handle::enter);
627 for id in ids {
628 let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
629 Some(entry) => entry.future.take(),
630 None => None,
631 };
632 let Some(mut future) = future else { continue };
633 let waker = Waker::from(Arc::new(TaskWaker {
634 id,
635 ready: self.ready.clone(),
636 }));
637 let done = match super::component::caught(|| {
638 future
639 .as_mut()
640 .poll(&mut TaskContext::from_waker(&waker))
641 .is_ready()
642 }) {
643 Ok(done) => done,
644 Err(message) => {
646 let mut inner = self.inner.borrow_mut();
647 if let Some(entry) = inner.tasks.get(&id) {
648 let host = entry.host;
649 inner.failures.push((host, message));
650 }
651 true
652 }
653 };
654 if done {
655 self.inner.borrow_mut().tasks.remove(&id);
656 drop(future);
657 } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
658 entry.future = Some(future);
659 }
660 }
661 true
662 }
663
664 #[cfg(test)]
665 pub(crate) fn task_count(&self) -> usize {
666 self.inner.borrow().tasks.len()
667 }
668
669 pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
671 std::mem::take(&mut self.inner.borrow_mut().failures)
672 }
673
674 pub(crate) fn take_actions(&self) -> VecDeque<Action> {
676 std::mem::take(&mut self.inner.borrow_mut().actions)
677 }
678
679 pub(crate) fn act(&self, action: Action) {
680 self.inner.borrow_mut().actions.push_back(action);
681 let notify = self.ready.notify.lock().expect("notify lock").clone();
682 if let Some(notify) = notify {
683 notify();
684 }
685 }
686
687 pub(crate) fn after_answer(&self, answer: AfterAnswer) {
690 self.answers.borrow_mut().waiting.push(answer);
691 }
692
693 pub(crate) fn hand_answers(&self) {
695 let mut answers = self.answers.borrow_mut();
696 let Answers { waiting, due } = &mut *answers;
697 if !waiting.is_empty() {
698 due.append(waiting);
699 }
700 }
701
702 pub(crate) fn has_due_answers(&self) -> bool {
704 !self.answers.borrow().due.is_empty()
705 }
706
707 #[cfg(test)]
709 pub(crate) fn answers_allocated(&self) -> bool {
710 let answers = self.answers.borrow();
711 answers.waiting.capacity() > 0 || answers.due.capacity() > 0
712 }
713
714 pub(crate) fn take_due_answers(&self) -> Vec<AfterAnswer> {
716 std::mem::take(&mut self.answers.borrow_mut().due)
717 }
718}
719
720#[must_use = "a dropped task is cancelled: keep it, or detach it"]
724pub struct Task<T> {
725 executor: Weak<Executor>,
726 id: u64,
727 output: Rc<RefCell<Output<T>>>,
728 detached: bool,
729}
730
731pub(crate) struct Output<T> {
733 pub(crate) value: Option<T>,
734 pub(crate) waker: Option<Waker>,
735}
736
737pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
739
740impl<T> Default for Output<T> {
741 fn default() -> Self {
742 Self {
743 value: None,
744 waker: None,
745 }
746 }
747}
748
749impl<T> Output<T> {
750 pub(crate) fn deliver(&mut self, value: T) {
752 self.value = Some(value);
753 if let Some(waker) = self.waker.take() {
754 waker.wake();
755 }
756 }
757}
758
759#[must_use = "an answer does nothing unless awaited"]
762pub struct Answer<T> {
763 slot: Rc<RefCell<Output<T>>>,
764}
765
766pub type DialogAnswer = Answer<i32>;
769
770impl<T> Answer<T> {
771 pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
772 let slot = Rc::new(RefCell::new(Output::default()));
773 (Self { slot: slot.clone() }, slot)
774 }
775}
776
777impl<T> std::fmt::Debug for Answer<T> {
778 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
779 f.debug_struct("Answer").finish_non_exhaustive()
780 }
781}
782
783impl<T> Future for Answer<T> {
784 type Output = T;
785
786 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
787 let mut slot = self.slot.borrow_mut();
788 match slot.value.take() {
789 Some(value) => Poll::Ready(value),
790 None => {
791 slot.waker = Some(cx.waker().clone());
792 Poll::Pending
793 }
794 }
795 }
796}
797
798impl<T> std::fmt::Debug for Task<T> {
799 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
800 f.debug_struct("Task")
801 .field("id", &self.id)
802 .finish_non_exhaustive()
803 }
804}
805
806impl<T> Task<T> {
807 pub fn detach(mut self) {
810 self.detached = true;
811 }
812}
813
814impl<T> Drop for Task<T> {
815 fn drop(&mut self) {
816 if !self.detached
817 && let Some(executor) = self.executor.upgrade()
818 {
819 executor.cancel(self.id);
820 }
821 }
822}
823
824impl<T> Future for Task<T> {
825 type Output = T;
826
827 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
828 let mut output = self.output.borrow_mut();
829 match output.value.take() {
830 Some(value) => Poll::Ready(value),
831 None => {
832 output.waker = Some(cx.waker().clone());
833 Poll::Pending
834 }
835 }
836 }
837}
838
839pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
841 executor.spawn(host, future)
842}
843
844pub(crate) fn act_after(
847 executor: &Rc<Executor>,
848 host: NodeId,
849 delay: Duration,
850 action: Action,
851) -> Task<()> {
852 let weak = Rc::downgrade(executor);
853 let acting = weak.clone();
854 let at = crate::time::now() + delay;
856 let id = executor.spawn(
857 host,
858 Box::pin(async move {
859 super::timer_until(at).await;
860 if let Some(executor) = acting.upgrade() {
861 executor.act(action);
862 }
863 }),
864 );
865 Task {
866 executor: weak,
867 id,
868 output: Rc::new(RefCell::new(Output::default())),
869 detached: false,
870 }
871}
872
873pub(crate) fn spawn_future<R: 'static>(
877 executor: &Rc<Executor>,
878 future: impl Future<Output = R> + 'static,
879) -> Task<R> {
880 let weak = Rc::downgrade(executor);
881 let output = Rc::new(RefCell::new(Output {
882 value: None,
883 waker: None,
884 }));
885 let done = output.clone();
886 let id = executor.spawn(
887 0,
888 Box::pin(async move {
889 let value = future.await;
890 let mut output = done.borrow_mut();
891 output.value = Some(value);
892 if let Some(waker) = output.waker.take() {
893 waker.wake();
894 }
895 }),
896 );
897 Task {
898 executor: weak,
899 id,
900 output,
901 detached: true,
902 }
903}
904
905pub(crate) struct TaskHandle {
907 executor: Weak<Executor>,
908 id: u64,
909}
910
911impl TaskHandle {
912 pub(crate) fn cancel(&self) {
914 if let Some(executor) = self.executor.upgrade() {
915 executor.cancel(self.id);
916 }
917 }
918}
919
920impl<T> Task<T> {
921 pub(crate) fn handle(&self) -> TaskHandle {
923 TaskHandle {
924 executor: self.executor.clone(),
925 id: self.id,
926 }
927 }
928}