Skip to main content

inset_shell/
lib.rs

1//! The one [`EmbedderClient`] the framework provides: owns the [`AppCell`] and
2//! translates host pushes into binding methods.
3//!
4//! Dart has no type for this — the engine owns the isolate. [`App`] stays in
5//! foundation. This crate sits above scheduler and gestures so the isolate
6//! can name both.
7#![feature(arbitrary_self_types)]
8
9use std::cell::RefMut;
10use std::rc::Rc;
11use std::time::Duration;
12
13use inset_embedder::{
14    EmbedderClient, Frame, Instant, KeyData, PlatformRef, PointerDataPacket, TextEditingValue,
15    TextInputAction, ViewFocusEvent, ViewId,
16};
17use inset_foundation::{App, AppCell};
18use inset_gestures::GestureBinding;
19use inset_painting::PaintingBinding;
20use inset_rendering::RendererBinding;
21use inset_scheduler::SchedulerBinding;
22use inset_services::{KeyEventManager, TextInput};
23
24/// Host-facing isolate: the [`AppCell`] plus the methods the embedder pushes.
25///
26/// Every push is one turn: the `App` is borrowed for the binding call and released before the
27/// cell's checkpoint, where the microtasks and futures the event queued run.
28pub struct Shell {
29    app: Rc<AppCell>,
30    platform: PlatformRef,
31    /// The platform time the app clock was last advanced to.
32    clock: Duration,
33    /// The platform's `now` at its `elapsed` zero, known once a frame has reported its `elapsed`; lets every push, not only a frame or wake, move the app clock to the platform's.
34    origin: Option<Instant>,
35}
36
37impl Shell {
38    /// Builds the heap from `platform`, then runs application setup.
39    ///
40    /// Setup (later widgets `run_app`) requests the first frame when it
41    /// installs work that needs one.
42    pub fn new(platform: PlatformRef, setup: impl FnOnce(&mut App)) -> Shell {
43        let shell = Shell {
44            app: AppCell::with_platform(platform.clone()),
45            platform,
46            clock: Duration::ZERO,
47            origin: None,
48        };
49        shell.turn(|app| {
50            // Flutter's engine collects the platform's fonts before the framework runs.
51            PaintingBinding::instance(app).install_platform_fonts(app);
52            setup(app);
53        });
54        shell
55    }
56
57    /// The `App`, borrowed until the guard drops. A host that needs a full turn — a borrow, then
58    /// the checkpoint — takes [`cell`](Self::cell).
59    pub fn app(&self) -> RefMut<'_, App> {
60        self.app.borrow_mut()
61    }
62
63    pub fn cell(&self) -> &Rc<AppCell> {
64        &self.app
65    }
66
67    /// One platform event: `f` on the borrowed `App`, then the checkpoint.
68    fn turn<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
69        let result = f(&mut self.app.borrow_mut());
70        self.app.checkpoint();
71        result
72    }
73
74    /// An input or platform push: the app clock catches up with the platform's first, as Dart's
75    /// timers measure real time from the moment they are created, then the turn runs.
76    fn push<R>(&mut self, f: impl FnOnce(&mut App) -> R) -> R {
77        if let Some(origin) = self.origin {
78            let elapsed = self.platform.now().saturating_duration_since(origin);
79            self.advance_clock(elapsed);
80        }
81        self.turn(f)
82    }
83
84    /// Moves the app clock up to the platform's `elapsed`, firing the timers that came due.
85    fn advance_clock(&mut self, elapsed: Duration) {
86        if elapsed <= self.clock {
87            return;
88        }
89        self.app.elapse(elapsed - self.clock);
90        self.clock = elapsed;
91    }
92}
93
94impl EmbedderClient for Shell {
95    fn frame(&mut self, frame: Frame) {
96        self.origin = Some(self.platform.now() - frame.elapsed);
97        self.advance_clock(frame.elapsed);
98        // The engine runs `_beginFrame` and `_drawFrame` as two native tasks: two turns.
99        self.turn(|app| SchedulerBinding::on_begin_frame(app, Some(frame.elapsed)));
100        self.turn(SchedulerBinding::on_draw_frame);
101    }
102
103    fn view_added(&mut self, _id: ViewId) {}
104
105    fn view_metrics_changed(&mut self, _id: ViewId) {
106        self.push(|app| RendererBinding::instance(app).handle_metrics_changed(app));
107    }
108
109    fn view_removed(&mut self, _id: ViewId) {}
110
111    fn view_focus_changed(&mut self, event: ViewFocusEvent) {
112        self.push(|app| {
113            let callback = app.platform_callbacks().on_view_focus_change.clone();
114            if let Some(callback) = callback {
115                callback(app, event);
116            }
117        });
118    }
119
120    fn pointer_data_packet(&mut self, packet: PointerDataPacket) {
121        self.push(|app| GestureBinding::instance(app).handle_pointer_data_packet(app, packet));
122    }
123
124    fn key_data(&mut self, data: KeyData) -> bool {
125        self.push(|app| KeyEventManager::instance(app).handle_key_data(app, data))
126    }
127
128    fn platform_brightness_changed(&mut self) {
129        self.push(|app| {
130            let callback = app
131                .platform_callbacks()
132                .on_platform_brightness_changed
133                .clone();
134            if let Some(callback) = callback {
135                callback.call(app);
136            }
137        });
138    }
139
140    fn locales_changed(&mut self) {
141        self.push(|app| {
142            let callback = app.platform_callbacks().on_locale_changed.clone();
143            if let Some(callback) = callback {
144                callback.call(app);
145            }
146        });
147    }
148
149    fn system_fonts_changed(&mut self) {
150        self.push(|app| {
151            PaintingBinding::instance(app).handle_system_fonts_did_change(app);
152        });
153    }
154
155    fn wake(&mut self, elapsed: Duration) {
156        self.advance_clock(elapsed);
157        // A wake with no time behind it is a post from a native callback.
158        self.app.wake();
159    }
160
161    fn text_input_editing_value(&mut self, _view: ViewId, value: TextEditingValue) {
162        self.push(|app| TextInput::instance(app).update_editing_value(app, value));
163    }
164
165    fn text_input_action(&mut self, _view: ViewId, action: TextInputAction) {
166        self.push(|app| TextInput::instance(app).perform_action(app, action));
167    }
168
169    fn text_input_closed(&mut self, _view: ViewId) {
170        self.push(|app| TextInput::instance(app).connection_closed(app));
171    }
172
173    fn system_context_menu_hidden(&mut self) {
174        self.push(inset_services::SystemContextMenuController::dispatch_system_hide);
175    }
176
177    fn custom_context_menu_action(&mut self, callback_id: &str) {
178        let callback_id = callback_id.to_string();
179        self.push(move |app| {
180            inset_services::SystemContextMenuController::dispatch_custom_action(app, &callback_id);
181        });
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use std::cell::Cell;
188    use std::rc::Rc;
189    use std::time::Duration;
190
191    use inset_embedder::{
192        EmbedderClient, Frame, KeyData, KeyEventType, PointerChange, PointerData,
193        PointerDataPacket, PointerDeviceKind, ViewId,
194    };
195    use inset_foundation::App;
196    use inset_gestures::{GestureBinding, PointerRoute};
197    use inset_scheduler::SchedulerBinding;
198    use inset_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey, PhysicalKeyboardKey};
199    use inset_test::{TestPlatform, TestView};
200
201    use super::Shell;
202
203    /// A platform with the one view a pointer packet or a focus event is addressed to.
204    fn platform_with_a_view() -> TestPlatform {
205        TestPlatform::new().with_view(Rc::new(TestView::new(0.0, 0.0)))
206    }
207
208    #[test]
209    fn new_runs_setup_and_frame_runs_both_scheduler_phases() {
210        let platform = Rc::new(TestPlatform::new());
211        let mut setup_ran = false;
212        let mut shell = Shell::new(platform.clone(), |_app: &mut App| {
213            setup_ran = true;
214        });
215        assert!(setup_ran);
216        assert_eq!(platform.frames_requested(), 0);
217
218        SchedulerBinding::schedule_frame(&mut shell.app());
219        assert_eq!(platform.frames_requested(), 1);
220        shell.frame(Frame {
221            elapsed: Duration::from_millis(16),
222        });
223    }
224
225    #[test]
226    fn pointer_data_packet_reaches_gesture_binding() {
227        let ran = Rc::new(Cell::new(false));
228        let ran_flag = Rc::clone(&ran);
229        let platform = Rc::new(platform_with_a_view());
230        let mut shell = Shell::new(platform, |app| {
231            let binding = GestureBinding::instance(app);
232            binding.pointer_router(app).add_route(
233                app,
234                1,
235                PointerRoute::new(move |_app, _event| {
236                    ran_flag.set(true);
237                }),
238                None,
239            );
240        });
241
242        shell.pointer_data_packet(PointerDataPacket::new(vec![PointerData {
243            change: PointerChange::Down,
244            kind: PointerDeviceKind::Mouse,
245            buttons: 1,
246            pointer_identifier: 1,
247            ..PointerData::default()
248        }]));
249        assert!(ran.get());
250    }
251
252    #[test]
253    fn key_data_reaches_the_hardware_keyboard() {
254        let seen = Rc::new(Cell::new(0));
255        let seen_flag = Rc::clone(&seen);
256        let platform = Rc::new(TestPlatform::new());
257        let mut shell = Shell::new(platform, |app| {
258            HardwareKeyboard::instance(app).add_handler(
259                app,
260                Rc::new(move |_app: &mut App, _event: &KeyEvent| {
261                    seen_flag.set(seen_flag.get() + 1);
262                    true
263                }),
264            );
265        });
266
267        let key_a = KeyData {
268            event_type: KeyEventType::Down,
269            physical: PhysicalKeyboardKey::KEY_A.usb_hid_usage,
270            logical: LogicalKeyboardKey::KEY_A.key_id,
271            character: Some("a".to_owned()),
272            ..KeyData::default()
273        };
274        assert!(shell.key_data(key_a), "the handler claimed the event");
275        assert_eq!(seen.get(), 1);
276
277        let keyboard = HardwareKeyboard::instance(&mut shell.app());
278        assert!(keyboard.is_logical_key_pressed(&shell.app(), LogicalKeyboardKey::KEY_A));
279    }
280
281    #[test]
282    fn wake_and_frame_advance_the_app_clock_and_fire_due_timers() {
283        let platform = Rc::new(TestPlatform::new());
284        let fired = Rc::new(Cell::new(Vec::new()));
285        let mut shell = Shell::new(platform, |app| {
286            for (name, delay) in [("early", 10), ("late", 30)] {
287                let fired = Rc::clone(&fired);
288                inset_foundation::Timer::new(
289                    app,
290                    Duration::from_millis(delay),
291                    inset_foundation::Listener::new(move |_app| {
292                        let mut log = fired.take();
293                        log.push(name);
294                        fired.set(log);
295                    }),
296                );
297            }
298        });
299        assert!(fired.take().is_empty());
300
301        shell.wake(Duration::from_millis(15));
302        assert_eq!(fired.take(), vec!["early"]);
303
304        shell.frame(Frame {
305            elapsed: Duration::from_millis(32),
306        });
307        assert_eq!(fired.take(), vec!["late"]);
308    }
309
310    #[test]
311    fn view_focus_is_delivered_through_the_dispatcher_callback() {
312        use inset_embedder::{ViewFocusDirection, ViewFocusEvent, ViewFocusState};
313        let received = Rc::new(Cell::new(None));
314        let sink = received.clone();
315        let platform = Rc::new(platform_with_a_view());
316        let mut shell = Shell::new(platform, move |app| {
317            app.platform_callbacks_mut().on_view_focus_change = Some(Rc::new(move |app, event| {
318                let sink = sink.clone();
319                app.schedule_microtask(inset_foundation::Listener::new(move |_| {
320                    sink.set(Some(event))
321                }));
322            }));
323        });
324        shell.view_focus_changed(ViewFocusEvent {
325            view_id: ViewId(0),
326            state: ViewFocusState::Focused,
327            direction: ViewFocusDirection::Backward,
328        });
329        let event = received
330            .get()
331            .expect("the shell checkpoints the callback's microtask");
332        assert_eq!(event.view_id, ViewId(0));
333        assert_eq!(event.state, ViewFocusState::Focused);
334        assert_eq!(event.direction, ViewFocusDirection::Backward);
335    }
336}