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, String>>,
94 },
95 ForgetHostCalls,
98 OpenUrl(String, AnswerSlot<bool>),
102 Animation(crate::animation::AnimationOp),
104 Animate {
106 op: crate::animation::AnimationOp,
107 animation: crate::animation::AnimationId,
108 end: AnswerSlot<bool>,
109 },
110 ReadValue {
112 node: crate::animation::NodeId,
113 value: AnswerSlot<f32>,
114 },
115 ReportViewable(NodeId),
118 Hint(NodeId),
121 Frame(AnswerSlot<Instant>),
123 Appearance(crate::platform::Appearance),
125 Measure(NodeId, AnswerSlot<Option<crate::Measurement>>),
128}
129
130pub(crate) enum ClipboardRead {
132 Text(AnswerSlot<String>),
134 Has(AnswerSlot<bool>),
136 Image(AnswerSlot<Option<ClipboardImage>>),
138 HasImage(AnswerSlot<bool>),
140 Files(AnswerSlot<Vec<String>>),
142}
143
144#[derive(Debug, Clone, Default, PartialEq, super::JsObject)]
146pub struct ClipboardImage {
147 pub url: String,
150 pub size: Size<DevicePixels>,
152}
153
154#[derive(Debug, Clone, Copy, Default, PartialEq)]
157pub struct ImageSize {
158 pub width: DevicePixels,
160 pub height: DevicePixels,
162}
163
164impl ImageSize {
165 pub fn size(&self) -> Size<DevicePixels> {
167 Size::new(self.width, self.height)
168 }
169}
170
171impl From<ImageSize> for Size<DevicePixels> {
172 fn from(s: ImageSize) -> Self {
173 s.size()
174 }
175}
176
177impl super::JsValue for ImageSize {
179 fn ts_type(types: &mut super::TsTypes) -> String {
180 types.declare("ImageSize", |_| {
181 "/** An image's size in pixels (`Image.getSize`). */\nexport type ImageSize = Size;"
182 .into()
183 })
184 }
185
186 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
187 if value.kind() != super::JsKind::Object {
188 return Err(value.expected("an object"));
189 }
190 let side = |key: &str| -> Result<DevicePixels, super::PropError> {
191 let v = value.field(key)?;
192 DevicePixels::from_js(v.get()).map_err(|e| super::PropError(format!("`{key}`: {e}")))
193 };
194 Ok(ImageSize {
195 width: side("width")?,
196 height: side("height")?,
197 })
198 }
199
200 fn to_js<'a>(
201 &self,
202 host: &'a dyn super::JsHost,
203 ) -> Result<super::JsOwned<'a>, super::PropError> {
204 let owned = super::JsOwned::new(host, host.new_object()?);
205 let object = owned.get().raw();
206 host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
207 host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
208 Ok(owned)
209 }
210}
211
212pub(crate) fn status_bar(patch: StatusBarSetting) -> Action {
214 Action::Command(ROOT_ID, Command::SetStatusBar(patch))
215}
216
217struct Entry {
218 host: NodeId,
219 future: Option<LocalFuture>,
221}
222
223#[derive(Default)]
224struct Inner {
225 tasks: FxHashMap<u64, Entry>,
226 next_task: u64,
227 actions: VecDeque<Action>,
228 failures: Vec<(NodeId, String)>,
229}
230
231#[derive(Default)]
233pub(crate) struct Executor {
234 inner: RefCell<Inner>,
235 ready: Arc<Ready>,
236 runtime: RefCell<Option<Handle>>,
238 animation_ids: std::cell::Cell<u32>,
241 derived: RefCell<super::animated::Derived>,
244 pub(crate) back: Rc<RefCell<super::back::BackListeners>>,
246 pub(crate) keys: Rc<RefCell<super::keys::ViewKeys>>,
248 timers: RefCell<BinaryHeap<Reverse<Timer>>>,
252 next_timer_seq: std::cell::Cell<u64>,
253}
254
255struct Timer {
258 at: Instant,
259 seq: u64,
260 waker: Waker,
261}
262
263impl PartialEq for Timer {
264 fn eq(&self, other: &Self) -> bool {
265 (self.at, self.seq) == (other.at, other.seq)
266 }
267}
268
269impl Eq for Timer {}
270
271impl PartialOrd for Timer {
272 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
273 Some(self.cmp(other))
274 }
275}
276
277impl Ord for Timer {
278 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
279 (self.at, self.seq).cmp(&(other.at, other.seq))
280 }
281}
282
283impl Executor {
284 pub(crate) fn derived(&self) -> std::cell::RefMut<'_, super::animated::Derived> {
286 self.derived.borrow_mut()
287 }
288
289 pub(crate) fn add_timer(&self, at: Instant, waker: Waker) {
291 let seq = self.next_timer_seq.get();
292 self.next_timer_seq.set(seq + 1);
293 self.timers
294 .borrow_mut()
295 .push(Reverse(Timer { at, seq, waker }));
296 }
297
298 pub(crate) fn next_timer(&self) -> Option<Instant> {
300 self.timers.borrow().peek().map(|Reverse(t)| t.at)
301 }
302
303 pub(crate) fn fire_timers(&self, now: Instant) {
305 let mut due = Vec::new();
306 {
307 let mut timers = self.timers.borrow_mut();
308 while timers.peek().is_some_and(|Reverse(t)| t.at <= now) {
309 if let Some(Reverse(timer)) = timers.pop() {
310 due.push(timer.waker);
311 }
312 }
313 }
314 for waker in due {
315 waker.wake();
316 }
317 }
318
319 pub(crate) fn next_animation_id(&self) -> u32 {
321 let n = self.animation_ids.get();
322 self.animation_ids.set(n + 1);
323 2 * n + 1
324 }
325
326 pub(crate) fn set_runtime(&self, runtime: Handle) {
327 *self.runtime.borrow_mut() = Some(runtime);
328 }
329
330 pub(crate) fn set_notify(&self, notify: Notify) {
331 *self.ready.notify.lock().expect("notify lock") = Some(notify);
332 }
333
334 fn spawn(&self, host: NodeId, future: LocalFuture) -> u64 {
335 let id = {
336 let mut inner = self.inner.borrow_mut();
337 inner.next_task += 1;
338 let id = inner.next_task;
339 inner.tasks.insert(
340 id,
341 Entry {
342 host,
343 future: Some(future),
344 },
345 );
346 id
347 };
348 self.ready.ids.lock().expect("ready lock").push(id);
350 let notify = self.ready.notify.lock().expect("notify lock").clone();
351 if let Some(notify) = notify {
352 notify();
353 }
354 id
355 }
356
357 fn cancel(&self, id: u64) {
358 let removed = self.inner.borrow_mut().tasks.remove(&id);
359 drop(removed);
361 }
362
363 pub(crate) fn poll_ready(&self) -> bool {
365 let mut ids = std::mem::take(&mut *self.ready.ids.lock().expect("ready lock"));
366 if ids.is_empty() {
367 return false;
368 }
369 ids.sort_unstable();
370 ids.dedup();
371 let runtime = self.runtime.borrow().clone();
373 let _context = runtime.as_ref().map(Handle::enter);
374 for id in ids {
375 let future = match self.inner.borrow_mut().tasks.get_mut(&id) {
376 Some(entry) => entry.future.take(),
377 None => None,
378 };
379 let Some(mut future) = future else { continue };
380 let waker = Waker::from(Arc::new(TaskWaker {
381 id,
382 ready: self.ready.clone(),
383 }));
384 let done = match super::component::caught(|| {
385 future
386 .as_mut()
387 .poll(&mut TaskContext::from_waker(&waker))
388 .is_ready()
389 }) {
390 Ok(done) => done,
391 Err(message) => {
393 let mut inner = self.inner.borrow_mut();
394 if let Some(entry) = inner.tasks.get(&id) {
395 let host = entry.host;
396 inner.failures.push((host, message));
397 }
398 true
399 }
400 };
401 if done {
402 self.inner.borrow_mut().tasks.remove(&id);
403 drop(future);
404 } else if let Some(entry) = self.inner.borrow_mut().tasks.get_mut(&id) {
405 entry.future = Some(future);
406 }
407 }
408 true
409 }
410
411 #[cfg(test)]
412 pub(crate) fn task_count(&self) -> usize {
413 self.inner.borrow().tasks.len()
414 }
415
416 pub(crate) fn take_failures(&self) -> Vec<(NodeId, String)> {
418 std::mem::take(&mut self.inner.borrow_mut().failures)
419 }
420
421 pub(crate) fn take_actions(&self) -> VecDeque<Action> {
423 std::mem::take(&mut self.inner.borrow_mut().actions)
424 }
425
426 pub(crate) fn act(&self, action: Action) {
427 self.inner.borrow_mut().actions.push_back(action);
428 let notify = self.ready.notify.lock().expect("notify lock").clone();
429 if let Some(notify) = notify {
430 notify();
431 }
432 }
433}
434
435#[must_use = "a dropped task is cancelled: keep it, or detach it"]
439pub struct Task<T> {
440 executor: Weak<Executor>,
441 id: u64,
442 output: Rc<RefCell<Output<T>>>,
443 detached: bool,
444}
445
446pub(crate) struct Output<T> {
448 pub(crate) value: Option<T>,
449 pub(crate) waker: Option<Waker>,
450}
451
452pub(crate) type AnswerSlot<T> = Rc<RefCell<Output<T>>>;
454
455impl<T> Default for Output<T> {
456 fn default() -> Self {
457 Self {
458 value: None,
459 waker: None,
460 }
461 }
462}
463
464impl<T> Output<T> {
465 pub(crate) fn deliver(&mut self, value: T) {
467 self.value = Some(value);
468 if let Some(waker) = self.waker.take() {
469 waker.wake();
470 }
471 }
472}
473
474#[must_use = "an answer does nothing unless awaited"]
477pub struct Answer<T> {
478 slot: Rc<RefCell<Output<T>>>,
479}
480
481pub type DialogAnswer = Answer<i32>;
484
485impl<T> Answer<T> {
486 pub(crate) fn new() -> (Self, Rc<RefCell<Output<T>>>) {
487 let slot = Rc::new(RefCell::new(Output::default()));
488 (Self { slot: slot.clone() }, slot)
489 }
490}
491
492impl<T> std::fmt::Debug for Answer<T> {
493 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494 f.debug_struct("Answer").finish_non_exhaustive()
495 }
496}
497
498impl<T> Future for Answer<T> {
499 type Output = T;
500
501 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
502 let mut slot = self.slot.borrow_mut();
503 match slot.value.take() {
504 Some(value) => Poll::Ready(value),
505 None => {
506 slot.waker = Some(cx.waker().clone());
507 Poll::Pending
508 }
509 }
510 }
511}
512
513impl<T> std::fmt::Debug for Task<T> {
514 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515 f.debug_struct("Task")
516 .field("id", &self.id)
517 .finish_non_exhaustive()
518 }
519}
520
521impl<T> Task<T> {
522 pub fn detach(mut self) {
525 self.detached = true;
526 }
527}
528
529impl<T> Drop for Task<T> {
530 fn drop(&mut self) {
531 if !self.detached
532 && let Some(executor) = self.executor.upgrade()
533 {
534 executor.cancel(self.id);
535 }
536 }
537}
538
539impl<T> Future for Task<T> {
540 type Output = T;
541
542 fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<T> {
543 let mut output = self.output.borrow_mut();
544 match output.value.take() {
545 Some(value) => Poll::Ready(value),
546 None => {
547 output.waker = Some(cx.waker().clone());
548 Poll::Pending
549 }
550 }
551 }
552}
553
554pub(crate) fn spawn_raw(executor: &Rc<Executor>, host: NodeId, future: LocalFuture) -> u64 {
556 executor.spawn(host, future)
557}
558
559pub(crate) fn act_after(
562 executor: &Rc<Executor>,
563 host: NodeId,
564 delay: Duration,
565 action: Action,
566) -> Task<()> {
567 let weak = Rc::downgrade(executor);
568 let acting = weak.clone();
569 let at = crate::time::now() + delay;
571 let id = executor.spawn(
572 host,
573 Box::pin(async move {
574 super::ambient::timer_until(at).await;
575 if let Some(executor) = acting.upgrade() {
576 executor.act(action);
577 }
578 }),
579 );
580 Task {
581 executor: weak,
582 id,
583 output: Rc::new(RefCell::new(Output::default())),
584 detached: false,
585 }
586}
587
588pub(crate) fn spawn_future<R: 'static>(
592 executor: &Rc<Executor>,
593 future: impl Future<Output = R> + 'static,
594) -> Task<R> {
595 let weak = Rc::downgrade(executor);
596 let output = Rc::new(RefCell::new(Output {
597 value: None,
598 waker: None,
599 }));
600 let done = output.clone();
601 let id = executor.spawn(
602 0,
603 Box::pin(async move {
604 let value = future.await;
605 let mut output = done.borrow_mut();
606 output.value = Some(value);
607 if let Some(waker) = output.waker.take() {
608 waker.wake();
609 }
610 }),
611 );
612 Task {
613 executor: weak,
614 id,
615 output,
616 detached: true,
617 }
618}
619
620pub(crate) struct TaskHandle {
622 executor: Weak<Executor>,
623 id: u64,
624}
625
626impl TaskHandle {
627 pub(crate) fn cancel(&self) {
629 if let Some(executor) = self.executor.upgrade() {
630 executor.cancel(self.id);
631 }
632 }
633}
634
635impl<T> Task<T> {
636 pub(crate) fn handle(&self) -> TaskHandle {
638 TaskHandle {
639 executor: self.executor.clone(),
640 id: self.id,
641 }
642 }
643}