anathema_runtime/runtime/
mod.rs

1use std::sync::atomic::Ordering;
2use std::time::{Duration, Instant};
3
4use anathema_backend::{Backend, WidgetCycle};
5use anathema_geometry::Size;
6use anathema_state::{Changes, StateId, States, clear_all_changes, clear_all_subs, drain_changes};
7use anathema_store::tree::root_node;
8use anathema_templates::blueprints::Blueprint;
9use anathema_templates::{Document, Globals};
10use anathema_value_resolver::{AttributeStorage, FunctionTable, Scope};
11use anathema_widgets::components::deferred::{CommandKind, DeferredComponents};
12use anathema_widgets::components::events::Event;
13use anathema_widgets::components::{
14    AnyComponentContext, AssociatedEvents, ComponentKind, ComponentRegistry, Emitter, ViewMessage,
15};
16use anathema_widgets::layout::{LayoutCtx, Viewport};
17use anathema_widgets::query::Children;
18use anathema_widgets::tabindex::{Index, TabIndex};
19use anathema_widgets::{
20    Component, Components, Factory, FloatingWidgets, GlyphMap, WidgetContainer, WidgetId, WidgetKind, WidgetTree,
21    eval_blueprint, update_widget,
22};
23use flume::Receiver;
24use notify::RecommendedWatcher;
25
26pub(crate) use self::error::show_error;
27use crate::builder::Builder;
28pub use crate::error::Result;
29use crate::events::GlobalEventHandler;
30use crate::{Error, REBUILD};
31
32mod error;
33mod testing;
34
35/// Anathema runtime
36pub struct Runtime<G> {
37    pub(super) blueprint: Blueprint,
38    pub(super) globals: Globals,
39    pub(super) factory: Factory,
40    pub(super) states: States,
41    pub(super) component_registry: ComponentRegistry,
42    pub(super) components: Components,
43    pub(super) document: Document,
44    pub(super) floating_widgets: FloatingWidgets,
45    pub(super) assoc_events: AssociatedEvents,
46    pub(super) glyph_map: GlyphMap,
47    pub(super) changes: Changes,
48    pub(super) viewport: Viewport,
49    pub(super) emitter: Emitter,
50    pub(super) sleep_micros: u64,
51    pub(super) message_receiver: flume::Receiver<ViewMessage>,
52    pub(super) dt: Instant,
53    pub(super) _watcher: Option<RecommendedWatcher>,
54    pub(super) deferred_components: DeferredComponents,
55    pub(super) global_event_handler: G,
56    pub(super) function_table: FunctionTable,
57}
58
59impl Runtime<()> {
60    /// Create a runtime builder
61    pub fn builder<B: Backend>(doc: Document, backend: &B) -> Builder<()> {
62        Builder::new(doc, backend.size(), ())
63    }
64}
65
66impl<G: GlobalEventHandler> Runtime<G> {
67    pub(crate) fn new(
68        blueprint: Blueprint,
69        globals: Globals,
70        component_registry: ComponentRegistry,
71        document: Document,
72        factory: Factory,
73        message_receiver: Receiver<ViewMessage>,
74        emitter: Emitter,
75        watcher: Option<RecommendedWatcher>,
76        size: Size,
77        fps: u32,
78        global_event_handler: G,
79        function_table: FunctionTable,
80    ) -> Self {
81        let sleep_micros: u64 = ((1.0 / fps as f64) * 1000.0 * 1000.0) as u64;
82
83        Self {
84            component_registry,
85            components: Components::new(),
86            document,
87            factory,
88            states: States::new(),
89            floating_widgets: FloatingWidgets::empty(),
90            assoc_events: AssociatedEvents::new(),
91            glyph_map: GlyphMap::empty(),
92            blueprint,
93            globals,
94            changes: Changes::empty(),
95            viewport: Viewport::new(size),
96            message_receiver,
97            emitter,
98            dt: Instant::now(),
99            _watcher: watcher,
100            deferred_components: DeferredComponents::new(),
101            sleep_micros,
102            global_event_handler,
103            function_table,
104        }
105    }
106
107    // TODO
108    // Rename Frame as it does not represent an individual frame
109    // but rather something that can continuously draw.
110    pub fn with_frame<B, F>(&mut self, backend: &mut B, mut f: F) -> Result<()>
111    where
112        B: Backend,
113        F: FnMut(&mut B, Frame<'_, '_, G>) -> Result<()>,
114    {
115        let mut tree = WidgetTree::empty();
116        let mut attribute_storage = AttributeStorage::empty();
117        let mut frame = self.next_frame(&mut tree, &mut attribute_storage)?;
118        frame.init_tree()?;
119        f(backend, frame)
120    }
121
122    pub fn run<B: Backend>(&mut self, backend: &mut B) -> Result<()> {
123        let sleep_micros = self.sleep_micros;
124        self.with_frame(backend, |backend, mut frame| {
125            // Perform the initial tick so tab index has a tree to work with.
126            // This means we can not react to any events in this tick as the tree does not
127            // yet have any widgets or components.
128            frame.tick(backend)?;
129
130            let mut tabindex = TabIndex::new(&mut frame.tabindex, frame.tree.view_mut());
131            tabindex.next();
132
133            if let Some(current) = frame.tabindex.as_ref() {
134                frame.with_component(current.widget_id, current.state_id, |comp, children, ctx| {
135                    comp.dyn_component.any_focus(children, ctx)
136                });
137            }
138
139            loop {
140                frame.tick(backend)?;
141                if frame.layout_ctx.stop_runtime {
142                    return Err(Error::Stop);
143                }
144
145                frame.present(backend);
146                frame.cleanup();
147                std::thread::sleep(Duration::from_micros(sleep_micros));
148
149                if REBUILD.swap(false, Ordering::Relaxed) {
150                    frame.force_rebuild()?;
151                    backend.clear();
152                    break Ok(());
153                }
154            }
155        })?;
156
157        Ok(())
158    }
159
160    pub fn next_frame<'frame, 'bp>(
161        &'bp mut self,
162        tree: &'frame mut WidgetTree<'bp>,
163        attribute_storage: &'frame mut AttributeStorage<'bp>,
164    ) -> Result<Frame<'frame, 'bp, G>> {
165        let layout_ctx = LayoutCtx::new(
166            &self.globals,
167            &self.factory,
168            &mut self.states,
169            attribute_storage,
170            &mut self.components,
171            &mut self.component_registry,
172            &mut self.floating_widgets,
173            &mut self.glyph_map,
174            &mut self.viewport,
175            &self.function_table,
176        );
177
178        let inst = Frame {
179            document: &self.document,
180            blueprint: &self.blueprint,
181            tree,
182            layout_ctx,
183            changes: &mut self.changes,
184            sleep_micros: self.sleep_micros,
185
186            assoc_events: &mut self.assoc_events,
187            deferred_components: &mut self.deferred_components,
188
189            emitter: &self.emitter,
190            message_receiver: &self.message_receiver,
191
192            dt: &mut self.dt,
193            needs_layout: true,
194
195            global_event_handler: &self.global_event_handler,
196            tabindex: None,
197        };
198
199        Ok(inst)
200    }
201
202    pub(super) fn reload(&mut self) -> Result<()> {
203        clear_all_changes();
204        clear_all_subs();
205
206        self.components = Components::new();
207        self.floating_widgets = FloatingWidgets::empty();
208
209        // Reload templates
210        self.document.reload_templates()?;
211
212        let (blueprint, globals) = self.document.compile()?;
213        self.blueprint = blueprint;
214        self.globals = globals;
215
216        Ok(())
217    }
218}
219
220pub struct Frame<'rt, 'bp, G> {
221    document: &'bp Document,
222    blueprint: &'bp Blueprint,
223    pub tree: &'rt mut WidgetTree<'bp>,
224    deferred_components: &'rt mut DeferredComponents,
225    layout_ctx: LayoutCtx<'rt, 'bp>,
226    changes: &'rt mut Changes,
227    assoc_events: &'rt mut AssociatedEvents,
228    sleep_micros: u64,
229    emitter: &'rt Emitter,
230    message_receiver: &'rt flume::Receiver<ViewMessage>,
231    dt: &'rt mut Instant,
232    needs_layout: bool,
233    global_event_handler: &'rt G,
234    pub tabindex: Option<Index>,
235}
236
237impl<'rt, 'bp, G: GlobalEventHandler> Frame<'rt, 'bp, G> {
238    pub fn force_rebuild(mut self) -> Result<()> {
239        // call unmount on all components
240        for i in 0..self.layout_ctx.components.len() {
241            let Some((widget_id, state_id)) = self.layout_ctx.components.get_ticking(i) else { continue };
242            let event = Event::Unmount;
243            self.send_event_to_component(event, widget_id, state_id);
244        }
245
246        self.return_state_and_component();
247        Ok(())
248    }
249
250    pub fn handle_global_event(&mut self, event: Event) -> Option<Event> {
251        let mut tabindex = TabIndex::new(&mut self.tabindex, self.tree.view_mut());
252
253        let event = self
254            .global_event_handler
255            .handle(event, &mut tabindex, self.deferred_components);
256
257        if tabindex.changed {
258            let prev = tabindex.consume();
259            if let Some(prev) = prev {
260                self.with_component(prev.widget_id, prev.state_id, |comp, children, ctx| {
261                    comp.dyn_component.any_blur(children, ctx)
262                });
263            }
264
265            if let Some(current) = self.tabindex.as_ref() {
266                self.with_component(current.widget_id, current.state_id, |comp, children, ctx| {
267                    comp.dyn_component.any_focus(children, ctx)
268                });
269            }
270        }
271
272        event
273    }
274
275    pub fn event(&mut self, event: Event) {
276        #[cfg(feature = "profile")]
277        puffin::profile_function!();
278
279        let Some(event) = self.handle_global_event(event) else { return };
280        if let Event::Stop = event {
281            self.layout_ctx.stop_runtime = true;
282            return;
283        }
284
285        match event {
286            Event::Noop => (),
287            Event::Stop => todo!(),
288
289            // Component specific event
290            Event::Blur | Event::Focus | Event::Key(_) => {
291                let Some(Index {
292                    widget_id, state_id, ..
293                }) = self.tabindex
294                else {
295                    return;
296                };
297                self.send_event_to_component(event, widget_id, state_id);
298            }
299            Event::Mouse(_) | Event::Resize(_) => {
300                for i in 0..self.layout_ctx.components.len() {
301                    let Some((widget_id, state_id)) = self.layout_ctx.components.get(i) else { continue };
302                    self.send_event_to_component(event, widget_id, state_id);
303                }
304            }
305            Event::Tick(_) | Event::Mount | Event::Unmount => panic!("this event should never be sent to the runtime"),
306        }
307    }
308
309    // Should be called only once to initialise the node tree.
310    pub fn init_tree(&mut self) -> Result<()> {
311        let mut ctx = self.layout_ctx.eval_ctx(None);
312        eval_blueprint(
313            self.blueprint,
314            &mut ctx,
315            &Scope::root(),
316            root_node(),
317            &mut self.tree.view_mut(),
318        )?;
319
320        Ok(())
321    }
322
323    pub fn tick<B: Backend>(&mut self, backend: &mut B) -> Result<Duration> {
324        #[cfg(feature = "profile")]
325        puffin::GlobalProfiler::lock().new_frame();
326
327        let now = Instant::now();
328        self.init_new_components();
329        let elapsed = self.handle_messages(now);
330        self.poll_events(elapsed, now, backend);
331        self.drain_deferred_commands();
332        self.drain_assoc_events();
333
334        // TODO:
335        // this secondary call is here to deal with changes causing changes
336        // which happens when values are removed or inserted and indices needs updating
337        self.apply_changes()?;
338        self.apply_changes()?;
339
340        self.tick_components(self.dt.elapsed());
341        self.cycle(backend)?;
342
343        *self.dt = Instant::now();
344
345        match self.layout_ctx.stop_runtime {
346            false => Ok(now.elapsed()),
347            true => Err(Error::Stop),
348        }
349    }
350
351    pub fn present<B: Backend>(&mut self, backend: &mut B) -> Duration {
352        #[cfg(feature = "profile")]
353        puffin::profile_function!();
354
355        let now = Instant::now();
356        backend.render(self.layout_ctx.glyph_map);
357        backend.clear();
358        now.elapsed()
359    }
360
361    pub fn cleanup(&mut self) {
362        #[cfg(feature = "profile")]
363        puffin::profile_function!();
364        for key in self.tree.drain_removed() {
365            self.layout_ctx.attribute_storage.try_remove(key);
366            self.layout_ctx.floating_widgets.try_remove(key);
367            self.layout_ctx.components.try_remove(key);
368            if let Some(Index { widget_id, .. }) = self.tabindex {
369                if widget_id == key {
370                    self.tabindex.take();
371                }
372            }
373        }
374    }
375
376    fn handle_messages(&mut self, fps_now: Instant) -> Duration {
377        #[cfg(feature = "profile")]
378        puffin::profile_function!();
379
380        while let Ok(msg) = self.message_receiver.try_recv() {
381            if let Some((widget_id, state_id)) = self
382                .layout_ctx
383                .components
384                .get_by_component_id(msg.recipient())
385                .map(|e| (e.widget_id, e.state_id))
386            {
387                self.with_component(widget_id, state_id, |comp, elements, ctx| {
388                    comp.dyn_component.any_message(elements, ctx, msg.payload())
389                });
390            }
391
392            // Make sure event handling isn't holding up the rest of the event loop.
393            if fps_now.elapsed().as_micros() as u64 >= self.sleep_micros / 2 {
394                break;
395            }
396        }
397
398        fps_now.elapsed()
399    }
400
401    fn poll_events<B: Backend>(&mut self, remaining: Duration, fps_now: Instant, backend: &mut B) {
402        while let Some(event) = backend.next_event(remaining) {
403            if let Event::Resize(size) = event {
404                self.layout_ctx.viewport.resize(size);
405                self.needs_layout = true;
406                backend.resize(size, self.layout_ctx.glyph_map);
407            }
408
409            if let Event::Stop = event {
410                self.layout_ctx.stop_runtime = true;
411                break;
412            }
413
414            self.event(event);
415
416            // Make sure event handling isn't holding up the rest of the event loop.
417            if fps_now.elapsed().as_micros() as u64 > self.sleep_micros {
418                break;
419            }
420        }
421    }
422
423    fn drain_deferred_commands(&mut self) {
424        #[cfg(feature = "profile")]
425        puffin::profile_function!();
426
427        // TODO: let's keep some memory around to drain this into instead of allocating
428        // a new vector every time.
429        // E.g `self.deferred_components.drain_into(&mut self.deferred_buffer)`
430        // Nb: Add drain_into to DeferredComponents
431        let commands = self.deferred_components.drain().collect::<Vec<_>>();
432        for mut cmd in commands {
433            for index in 0..self.layout_ctx.components.len() {
434                let Some((widget_id, state_id)) = self.layout_ctx.components.get(index) else { continue };
435                let Some(comp) = self.tree.get_ref(widget_id) else { continue };
436                let WidgetContainer {
437                    kind: WidgetKind::Component(comp),
438                    ..
439                } = comp
440                else {
441                    continue;
442                };
443                let attributes = self.layout_ctx.attribute_storage.get(widget_id);
444                if !cmd.filter_component(comp, attributes) {
445                    continue;
446                }
447
448                // -----------------------------------------------------------------------------
449                //   - Set focus -
450                //   TODO: here is another candidate for refactoring to make it
451                //   less cludgy and verbose.
452                // -----------------------------------------------------------------------------
453                // Blur the current component if the message is a `Focus` message
454                if let CommandKind::Focus = cmd.kind {
455                    // If this component current has focus ignore this command
456                    if let Some(index) = self.tabindex.as_ref() {
457                        if index.widget_id == widget_id {
458                            continue;
459                        }
460                    }
461
462                    // here we can find the component that should receive focus
463                    let new_index = self
464                        .with_component(widget_id, state_id, |comp, children, ctx| {
465                            if comp.dyn_component.any_accept_focus() {
466                                let index = Index {
467                                    path: children.parent_path().into(),
468                                    index: comp.tabindex,
469                                    widget_id,
470                                    state_id,
471                                };
472
473                                comp.dyn_component.any_focus(children, ctx);
474
475                                Some(index)
476                            } else {
477                                None
478                            }
479                        })
480                        .flatten();
481
482                    if let Some(index) = new_index {
483                        // If there is currently a component with focus that component
484                        // should only lose focus if the selected component accepts focus.
485                        if let Some(old) = self.tabindex.replace(index) {
486                            self.with_component(old.widget_id, old.state_id, |comp, children, ctx| {
487                                comp.dyn_component.any_blur(children, ctx)
488                            });
489                        }
490                    }
491                }
492
493                // -----------------------------------------------------------------------------
494                //   - Send message -
495                // -----------------------------------------------------------------------------
496                if let CommandKind::SendMessage(msg) = cmd.kind {
497                    self.with_component(widget_id, state_id, |comp, children, ctx| {
498                        comp.dyn_component.any_message(children, ctx, msg);
499                    });
500                    break;
501                }
502            }
503        }
504    }
505
506    fn drain_assoc_events(&mut self) {
507        #[cfg(feature = "profile")]
508        puffin::profile_function!();
509
510        while let Some(assoc_event) = self.assoc_events.next() {
511            let mut parent = assoc_event.parent;
512            let external_ident = self.document.strings.get_ref_unchecked(assoc_event.external());
513            let internal_ident = self.document.strings.get_ref_unchecked(assoc_event.internal());
514            let sender = self.document.strings.get_ref_unchecked(assoc_event.sender);
515            let sender_id = assoc_event.sender_id;
516            let mut event = assoc_event.to_event(internal_ident, external_ident, sender, sender_id);
517
518            loop {
519                let Some((widget_id, state_id)) = self.layout_ctx.components.get_by_widget_id(parent.into()) else {
520                    return;
521                };
522
523                let stop_propagation = self
524                    .with_component(widget_id, state_id, |comp, children, ctx| {
525                        let next_parent = ctx.parent();
526                        comp.dyn_component.any_component_event(children, ctx, &mut event);
527
528                        parent = match next_parent {
529                            Some(p) => p,
530                            None => return true,
531                        };
532
533                        event.should_stop_propagation()
534                    })
535                    .unwrap_or(true);
536
537                if stop_propagation {
538                    break;
539                }
540            }
541        }
542    }
543
544    fn cycle<B: Backend>(&mut self, backend: &mut B) -> Result<()> {
545        #[cfg(feature = "profile")]
546        puffin::profile_function!();
547
548        let mut cycle = WidgetCycle::new(backend, self.tree.view_mut(), self.layout_ctx.viewport.constraints());
549        cycle.run(&mut self.layout_ctx, self.needs_layout)?;
550
551        self.needs_layout = false;
552        Ok(())
553    }
554
555    fn apply_changes(&mut self) -> Result<()> {
556        #[cfg(feature = "profile")]
557        puffin::profile_function!();
558
559        drain_changes(self.changes);
560
561        if self.changes.is_empty() {
562            return Ok(());
563        }
564
565        self.needs_layout = true;
566        let mut tree = self.tree.view_mut();
567
568        self.changes.iter().try_for_each(|(sub, change)| {
569            sub.iter().try_for_each(|value_id| {
570                let widget_id = value_id.key();
571
572                if let Some(widget) = tree.get_mut(widget_id) {
573                    if let WidgetKind::Element(element) = &mut widget.kind {
574                        element.invalidate_cache();
575                    }
576                }
577
578                // check that the node hasn't already been removed
579                if !tree.contains(widget_id) {
580                    return Result::Ok(());
581                }
582
583                tree.with_value_mut(widget_id, |_path, widget, tree| {
584                    update_widget(widget, value_id, change, tree, self.layout_ctx.attribute_storage)
585                })
586                .unwrap_or(Ok(()))?;
587
588                Ok(())
589            })?;
590
591            Result::Ok(())
592        })?;
593
594        self.changes.clear();
595
596        Ok(())
597    }
598
599    fn send_event_to_component(&mut self, event: Event, widget_id: WidgetId, state_id: StateId) {
600        self.with_component(widget_id, state_id, |comp, elements, ctx| {
601            comp.dyn_component.any_event(elements, ctx, event);
602        });
603    }
604
605    fn with_component<F, U>(&mut self, widget_id: WidgetId, state_id: StateId, f: F) -> Option<U>
606    where
607        F: FnOnce(&mut Component<'_>, Children<'_, '_>, AnyComponentContext<'_, '_>) -> U,
608    {
609        let mut tree = self.tree.view_mut();
610
611        tree.with_value_mut(widget_id, |_path, container, children| {
612            let WidgetKind::Component(component) = &mut container.kind else {
613                panic!("this is always a component")
614            };
615
616            let Some(state) = self.layout_ctx.states.get_mut(state_id) else {
617                panic!("a component always has a state")
618            };
619
620            self.layout_ctx
621                .attribute_storage
622                .with_mut(widget_id, |attributes, storage| {
623                    let elements = Children::new(children, storage, &mut self.needs_layout);
624
625                    let ctx = AnyComponentContext::new(
626                        component.parent.map(Into::into),
627                        component.name_id,
628                        widget_id,
629                        state_id,
630                        component.assoc_functions,
631                        self.assoc_events,
632                        self.deferred_components,
633                        attributes,
634                        Some(state),
635                        self.emitter,
636                        self.layout_ctx.viewport,
637                        &mut self.layout_ctx.stop_runtime,
638                        &self.document.strings,
639                    );
640
641                    f(component, elements, ctx)
642                })
643        })?
644    }
645
646    fn tick_components(&mut self, dt: Duration) {
647        #[cfg(feature = "profile")]
648        puffin::profile_function!();
649
650        for i in 0..self.layout_ctx.components.len() {
651            let Some((widget_id, state_id)) = self.layout_ctx.components.get_ticking(i) else { continue };
652            let event = Event::Tick(dt);
653            self.send_event_to_component(event, widget_id, state_id);
654        }
655    }
656
657    fn init_new_components(&mut self) {
658        while let Some((widget_id, state_id)) = self.layout_ctx.new_components.pop() {
659            self.with_component(widget_id, state_id, |comp, elements, ctx| {
660                comp.dyn_component.any_event(elements, ctx, Event::Mount);
661            });
662        }
663    }
664
665    // Return the state for each component back into the component registry
666    fn return_state_and_component(self) {
667        // Return all states
668        let mut tree = WidgetTree::empty();
669        std::mem::swap(&mut tree, self.tree);
670
671        for (_, widget) in tree.values().into_iter() {
672            let WidgetKind::Component(comp) = widget.kind else { continue };
673            let ComponentKind::Instance = comp.kind else { continue };
674            let state = self.layout_ctx.states.remove(comp.state_id).take();
675            self.layout_ctx
676                .component_registry
677                .return_component(comp.component_id, comp.dyn_component, state);
678        }
679    }
680
681    // fn display_error(&mut self, backend: &mut impl Backend) {
682    //     let _tpl = "text 'you goofed up'";
683    //     backend.render(self.layout_ctx.glyph_map);
684    // }
685}