1use crate::{
2 app::{AppContext, MutableAppContext, WindowInvalidation},
3 elements::Element,
4 font_cache::FontCache,
5 geometry::rect::RectF,
6 json::{self, ToJson},
7 keymap::Keystroke,
8 platform::{CursorStyle, Event},
9 scene::{
10 ClickRegionEvent, CursorRegion, DownOutRegionEvent, DownRegionEvent, DragRegionEvent,
11 HoverRegionEvent, MouseRegionEvent, MoveRegionEvent, UpOutRegionEvent, UpRegionEvent,
12 },
13 text_layout::TextLayoutCache,
14 Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, Appearance, AssetCache, ElementBox,
15 Entity, FontSystem, ModelHandle, MouseButton, MouseMovedEvent, MouseRegion, MouseRegionId,
16 ParentId, ReadModel, ReadView, RenderContext, RenderParams, Scene, UpgradeModelHandle,
17 UpgradeViewHandle, View, ViewHandle, WeakModelHandle, WeakViewHandle,
18};
19use collections::{HashMap, HashSet};
20use pathfinder_geometry::vector::{vec2f, Vector2F};
21use serde_json::json;
22use smallvec::SmallVec;
23use std::{
24 marker::PhantomData,
25 ops::{Deref, DerefMut, Range},
26 sync::Arc,
27};
28
29pub struct Presenter {
30 window_id: usize,
31 pub(crate) rendered_views: HashMap<usize, ElementBox>,
32 cursor_regions: Vec<CursorRegion>,
33 mouse_regions: Vec<(MouseRegion, usize)>,
34 font_cache: Arc<FontCache>,
35 text_layout_cache: TextLayoutCache,
36 asset_cache: Arc<AssetCache>,
37 last_mouse_moved_event: Option<Event>,
38 hovered_region_ids: HashSet<MouseRegionId>,
39 clicked_regions: Vec<MouseRegion>,
40 clicked_button: Option<MouseButton>,
41 mouse_position: Vector2F,
42 titlebar_height: f32,
43 appearance: Appearance,
44}
45
46impl Presenter {
47 pub fn new(
48 window_id: usize,
49 titlebar_height: f32,
50 appearance: Appearance,
51 font_cache: Arc<FontCache>,
52 text_layout_cache: TextLayoutCache,
53 asset_cache: Arc<AssetCache>,
54 cx: &mut MutableAppContext,
55 ) -> Self {
56 Self {
57 window_id,
58 rendered_views: cx.render_views(window_id, titlebar_height, appearance),
59 cursor_regions: Default::default(),
60 mouse_regions: Default::default(),
61 font_cache,
62 text_layout_cache,
63 asset_cache,
64 last_mouse_moved_event: None,
65 hovered_region_ids: Default::default(),
66 clicked_regions: Vec::new(),
67 clicked_button: None,
68 mouse_position: vec2f(0., 0.),
69 titlebar_height,
70 appearance,
71 }
72 }
73
74 pub fn invalidate(
75 &mut self,
76 invalidation: &mut WindowInvalidation,
77 appearance: Appearance,
78 cx: &mut MutableAppContext,
79 ) {
80 cx.start_frame();
81 self.appearance = appearance;
82 for view_id in &invalidation.removed {
83 invalidation.updated.remove(view_id);
84 self.rendered_views.remove(view_id);
85 }
86 for view_id in &invalidation.updated {
87 self.rendered_views.insert(
88 *view_id,
89 cx.render_view(RenderParams {
90 window_id: self.window_id,
91 view_id: *view_id,
92 titlebar_height: self.titlebar_height,
93 hovered_region_ids: self.hovered_region_ids.clone(),
94 clicked_region_ids: self.clicked_button.map(|button| {
95 (
96 self.clicked_regions
97 .iter()
98 .filter_map(MouseRegion::id)
99 .collect(),
100 button,
101 )
102 }),
103 refreshing: false,
104 appearance,
105 })
106 .unwrap(),
107 );
108 }
109 }
110
111 pub fn refresh(
112 &mut self,
113 invalidation: &mut WindowInvalidation,
114 appearance: Appearance,
115 cx: &mut MutableAppContext,
116 ) {
117 self.invalidate(invalidation, appearance, cx);
118 for (view_id, view) in &mut self.rendered_views {
119 if !invalidation.updated.contains(view_id) {
120 *view = cx
121 .render_view(RenderParams {
122 window_id: self.window_id,
123 view_id: *view_id,
124 titlebar_height: self.titlebar_height,
125 hovered_region_ids: self.hovered_region_ids.clone(),
126 clicked_region_ids: self.clicked_button.map(|button| {
127 (
128 self.clicked_regions
129 .iter()
130 .filter_map(MouseRegion::id)
131 .collect(),
132 button,
133 )
134 }),
135 refreshing: true,
136 appearance,
137 })
138 .unwrap();
139 }
140 }
141 }
142
143 pub fn build_scene(
144 &mut self,
145 window_size: Vector2F,
146 scale_factor: f32,
147 refreshing: bool,
148 cx: &mut MutableAppContext,
149 ) -> Scene {
150 let mut scene = Scene::new(scale_factor);
151
152 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
153 self.layout(window_size, refreshing, cx);
154 let mut paint_cx = self.build_paint_context(&mut scene, window_size, cx);
155 paint_cx.paint(
156 root_view_id,
157 Vector2F::zero(),
158 RectF::new(Vector2F::zero(), window_size),
159 );
160 self.text_layout_cache.finish_frame();
161 self.cursor_regions = scene.cursor_regions();
162 self.mouse_regions = scene.mouse_regions();
163
164 if cx.window_is_active(self.window_id) {
165 if let Some(event) = self.last_mouse_moved_event.clone() {
166 self.dispatch_event(event, true, cx);
167 }
168 }
169 } else {
170 log::error!("could not find root_view_id for window {}", self.window_id);
171 }
172
173 scene
174 }
175
176 fn layout(&mut self, window_size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
177 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
178 self.build_layout_context(window_size, refreshing, cx)
179 .layout(root_view_id, SizeConstraint::strict(window_size));
180 }
181 }
182
183 pub fn build_layout_context<'a>(
184 &'a mut self,
185 window_size: Vector2F,
186 refreshing: bool,
187 cx: &'a mut MutableAppContext,
188 ) -> LayoutContext<'a> {
189 LayoutContext {
190 window_id: self.window_id,
191 rendered_views: &mut self.rendered_views,
192 font_cache: &self.font_cache,
193 font_system: cx.platform().fonts(),
194 text_layout_cache: &self.text_layout_cache,
195 asset_cache: &self.asset_cache,
196 view_stack: Vec::new(),
197 refreshing,
198 hovered_region_ids: self.hovered_region_ids.clone(),
199 clicked_region_ids: self.clicked_button.map(|button| {
200 (
201 self.clicked_regions
202 .iter()
203 .filter_map(MouseRegion::id)
204 .collect(),
205 button,
206 )
207 }),
208 titlebar_height: self.titlebar_height,
209 appearance: self.appearance,
210 window_size,
211 app: cx,
212 }
213 }
214
215 pub fn build_paint_context<'a>(
216 &'a mut self,
217 scene: &'a mut Scene,
218 window_size: Vector2F,
219 cx: &'a mut MutableAppContext,
220 ) -> PaintContext {
221 PaintContext {
222 scene,
223 window_size,
224 font_cache: &self.font_cache,
225 text_layout_cache: &self.text_layout_cache,
226 rendered_views: &mut self.rendered_views,
227 view_stack: Vec::new(),
228 app: cx,
229 }
230 }
231
232 pub fn rect_for_text_range(&self, range_utf16: Range<usize>, cx: &AppContext) -> Option<RectF> {
233 cx.focused_view_id(self.window_id).and_then(|view_id| {
234 let cx = MeasurementContext {
235 app: cx,
236 rendered_views: &self.rendered_views,
237 window_id: self.window_id,
238 };
239 cx.rect_for_text_range(view_id, range_utf16)
240 })
241 }
242
243 pub fn dispatch_event(
244 &mut self,
245 event: Event,
246 event_reused: bool,
247 cx: &mut MutableAppContext,
248 ) -> bool {
249 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
250 let mut events_to_send = Vec::new();
251
252 // 1. Allocate the correct set of GPUI events generated from the platform events
253 // -> These are usually small: [Mouse Down] or [Mouse up, Click] or [Mouse Moved, Mouse Dragged?]
254 // -> Also moves around mouse related state
255 match &event {
256 Event::MouseDown(e) => {
257 // Click events are weird because they can be fired after a drag event.
258 // MDN says that browsers handle this by starting from 'the most
259 // specific ancestor element that contained both [positions]'
260 // So we need to store the overlapping regions on mouse down.
261
262 // If there is already clicked_button stored, don't replace it.
263 if self.clicked_button.is_none() {
264 self.clicked_regions = self
265 .mouse_regions
266 .iter()
267 .filter_map(|(region, _)| {
268 region
269 .bounds
270 .contains_point(e.position)
271 .then(|| region.clone())
272 })
273 .collect();
274 self.clicked_button = Some(e.button);
275 }
276
277 events_to_send.push(MouseRegionEvent::Down(DownRegionEvent {
278 region: Default::default(),
279 platform_event: e.clone(),
280 }));
281 events_to_send.push(MouseRegionEvent::DownOut(DownOutRegionEvent {
282 region: Default::default(),
283 platform_event: e.clone(),
284 }));
285 }
286 Event::MouseUp(e) => {
287 // NOTE: The order of event pushes is important! MouseUp events MUST be fired
288 // before click events, and so the UpRegionEvent events need to be pushed before
289 // ClickRegionEvents
290 events_to_send.push(MouseRegionEvent::Up(UpRegionEvent {
291 region: Default::default(),
292 platform_event: e.clone(),
293 }));
294 events_to_send.push(MouseRegionEvent::UpOut(UpOutRegionEvent {
295 region: Default::default(),
296 platform_event: e.clone(),
297 }));
298 events_to_send.push(MouseRegionEvent::Click(ClickRegionEvent {
299 region: Default::default(),
300 platform_event: e.clone(),
301 }));
302 }
303 Event::MouseMoved(
304 e @ MouseMovedEvent {
305 position,
306 pressed_button,
307 ..
308 },
309 ) => {
310 let mut style_to_assign = CursorStyle::Arrow;
311 for region in self.cursor_regions.iter().rev() {
312 if region.bounds.contains_point(*position) {
313 style_to_assign = region.style;
314 break;
315 }
316 }
317 cx.platform().set_cursor_style(style_to_assign);
318
319 if !event_reused {
320 if pressed_button.is_some() {
321 events_to_send.push(MouseRegionEvent::Drag(DragRegionEvent {
322 region: Default::default(),
323 prev_mouse_position: self.mouse_position,
324 platform_event: e.clone(),
325 }));
326 } else if let Some(clicked_button) = self.clicked_button {
327 // Mouse up event happened outside the current window. Simulate mouse up button event
328 let button_event = e.to_button_event(clicked_button);
329 events_to_send.push(MouseRegionEvent::Up(UpRegionEvent {
330 region: Default::default(),
331 platform_event: button_event.clone(),
332 }));
333 events_to_send.push(MouseRegionEvent::UpOut(UpOutRegionEvent {
334 region: Default::default(),
335 platform_event: button_event.clone(),
336 }));
337 events_to_send.push(MouseRegionEvent::Click(ClickRegionEvent {
338 region: Default::default(),
339 platform_event: button_event.clone(),
340 }));
341 }
342
343 events_to_send.push(MouseRegionEvent::Move(MoveRegionEvent {
344 region: Default::default(),
345 platform_event: e.clone(),
346 }));
347 }
348
349 events_to_send.push(MouseRegionEvent::Hover(HoverRegionEvent {
350 region: Default::default(),
351 platform_event: e.clone(),
352 started: false,
353 }));
354
355 self.last_mouse_moved_event = Some(event.clone());
356 }
357
358 _ => {}
359 }
360
361 if let Some(position) = event.position() {
362 self.mouse_position = position;
363 }
364
365 let mut invalidated_views: HashSet<usize> = Default::default();
366 let mut any_event_handled = false;
367 // 2. Process the raw mouse events into region events
368 for mut region_event in events_to_send {
369 let mut valid_regions = Vec::new();
370
371 // GPUI elements are arranged by depth but sibling elements can register overlapping
372 // mouse regions. As such, hover events are only fired on overlapping elements which
373 // are at the same depth as the topmost element which overlaps with the mouse.
374
375 match ®ion_event {
376 MouseRegionEvent::Hover(_) => {
377 let mut top_most_depth = None;
378 let mouse_position = self.mouse_position.clone();
379 for (region, depth) in self.mouse_regions.iter().rev() {
380 // Allow mouse regions to appear transparent to hovers
381 if !region.hoverable {
382 continue;
383 }
384
385 let contains_mouse = region.bounds.contains_point(mouse_position);
386
387 if contains_mouse && top_most_depth.is_none() {
388 top_most_depth = Some(depth);
389 }
390
391 if let Some(region_id) = region.id() {
392 // This unwrap relies on short circuiting boolean expressions
393 // The right side of the && is only executed when contains_mouse
394 // is true, and we know above that when contains_mouse is true
395 // top_most_depth is set
396 if contains_mouse && depth == top_most_depth.unwrap() {
397 //Ensure that hover entrance events aren't sent twice
398 if self.hovered_region_ids.insert(region_id) {
399 valid_regions.push(region.clone());
400 invalidated_views.insert(region.view_id);
401 }
402 } else {
403 // Ensure that hover exit events aren't sent twice
404 if self.hovered_region_ids.remove(®ion_id) {
405 valid_regions.push(region.clone());
406 invalidated_views.insert(region.view_id);
407 }
408 }
409 }
410 }
411 }
412 MouseRegionEvent::Click(e) => {
413 // Only raise click events if the released button is the same as the one stored
414 if self
415 .clicked_button
416 .map(|clicked_button| clicked_button == e.button)
417 .unwrap_or(false)
418 {
419 // Clear clicked regions and clicked button
420 let clicked_regions =
421 std::mem::replace(&mut self.clicked_regions, Vec::new());
422 self.clicked_button = None;
423
424 // Find regions which still overlap with the mouse since the last MouseDown happened
425 for clicked_region in clicked_regions.into_iter().rev() {
426 if clicked_region.bounds.contains_point(e.position) {
427 valid_regions.push(clicked_region);
428 }
429 }
430 }
431 }
432 MouseRegionEvent::Drag(_) => {
433 for clicked_region in self.clicked_regions.iter().rev() {
434 valid_regions.push(clicked_region.clone());
435 }
436 }
437
438 MouseRegionEvent::UpOut(_) | MouseRegionEvent::DownOut(_) => {
439 for (mouse_region, _) in self.mouse_regions.iter().rev() {
440 // NOT contains
441 if !mouse_region.bounds.contains_point(self.mouse_position) {
442 valid_regions.push(mouse_region.clone());
443 }
444 }
445 }
446 _ => {
447 for (mouse_region, _) in self.mouse_regions.iter().rev() {
448 // Contains
449 if mouse_region.bounds.contains_point(self.mouse_position) {
450 valid_regions.push(mouse_region.clone());
451 }
452 }
453 }
454 }
455
456 //3. Fire region events
457 let hovered_region_ids = self.hovered_region_ids.clone();
458 for valid_region in valid_regions.into_iter() {
459 let mut event_cx = self.build_event_context(&mut invalidated_views, cx);
460
461 region_event.set_region(valid_region.bounds);
462 if let MouseRegionEvent::Hover(e) = &mut region_event {
463 e.started = valid_region
464 .id()
465 .map(|region_id| hovered_region_ids.contains(®ion_id))
466 .unwrap_or(false)
467 }
468 // Handle Down events if the MouseRegion has a Click handler. This makes the api more intuitive as you would
469 // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
470 // This behavior can be overridden by adding a Down handler that calls cx.propogate_event
471 if let MouseRegionEvent::Down(e) = ®ion_event {
472 if valid_region
473 .handlers
474 .contains_handler(MouseRegionEvent::click_disc(), Some(e.button))
475 {
476 event_cx.handled = true;
477 }
478 }
479
480 if let Some(callback) = valid_region.handlers.get(®ion_event.handler_key()) {
481 event_cx.handled = true;
482 event_cx.invalidated_views.insert(valid_region.view_id);
483 event_cx.with_current_view(valid_region.view_id, {
484 let region_event = region_event.clone();
485 |cx| {
486 callback(region_event, cx);
487 }
488 });
489 }
490
491 any_event_handled = any_event_handled || event_cx.handled;
492 // For bubbling events, if the event was handled, don't continue dispatching
493 // This only makes sense for local events.
494 if event_cx.handled && region_event.is_capturable() {
495 break;
496 }
497 }
498 }
499
500 if !any_event_handled && !event_reused {
501 let mut event_cx = self.build_event_context(&mut invalidated_views, cx);
502 any_event_handled = event_cx.dispatch_event(root_view_id, &event);
503 }
504
505 for view_id in invalidated_views {
506 cx.notify_view(self.window_id, view_id);
507 }
508
509 any_event_handled
510 } else {
511 false
512 }
513 }
514
515 pub fn build_event_context<'a>(
516 &'a mut self,
517 invalidated_views: &'a mut HashSet<usize>,
518 cx: &'a mut MutableAppContext,
519 ) -> EventContext<'a> {
520 EventContext {
521 rendered_views: &mut self.rendered_views,
522 font_cache: &self.font_cache,
523 text_layout_cache: &self.text_layout_cache,
524 view_stack: Default::default(),
525 invalidated_views,
526 notify_count: 0,
527 handled: false,
528 window_id: self.window_id,
529 app: cx,
530 }
531 }
532
533 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
534 let view = cx.root_view(self.window_id)?;
535 Some(json!({
536 "root_view": view.debug_json(cx),
537 "root_element": self.rendered_views.get(&view.id())
538 .map(|root_element| {
539 root_element.debug(&DebugContext {
540 rendered_views: &self.rendered_views,
541 font_cache: &self.font_cache,
542 app: cx,
543 })
544 })
545 }))
546 }
547}
548
549pub struct LayoutContext<'a> {
550 window_id: usize,
551 rendered_views: &'a mut HashMap<usize, ElementBox>,
552 view_stack: Vec<usize>,
553 pub font_cache: &'a Arc<FontCache>,
554 pub font_system: Arc<dyn FontSystem>,
555 pub text_layout_cache: &'a TextLayoutCache,
556 pub asset_cache: &'a AssetCache,
557 pub app: &'a mut MutableAppContext,
558 pub refreshing: bool,
559 pub window_size: Vector2F,
560 titlebar_height: f32,
561 appearance: Appearance,
562 hovered_region_ids: HashSet<MouseRegionId>,
563 clicked_region_ids: Option<(Vec<MouseRegionId>, MouseButton)>,
564}
565
566impl<'a> LayoutContext<'a> {
567 pub(crate) fn keystrokes_for_action(
568 &self,
569 action: &dyn Action,
570 ) -> Option<SmallVec<[Keystroke; 2]>> {
571 self.app
572 .keystrokes_for_action(self.window_id, &self.view_stack, action)
573 }
574
575 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
576 let print_error = |view_id| {
577 format!(
578 "{} with id {}",
579 self.app.name_for_view(self.window_id, view_id).unwrap(),
580 view_id,
581 )
582 };
583 match (
584 self.view_stack.last(),
585 self.app.parents.get(&(self.window_id, view_id)),
586 ) {
587 (Some(layout_parent), Some(ParentId::View(app_parent))) => {
588 if layout_parent != app_parent {
589 panic!(
590 "View {} was laid out with parent {} when it was constructed with parent {}",
591 print_error(view_id),
592 print_error(*layout_parent),
593 print_error(*app_parent))
594 }
595 }
596 (None, Some(ParentId::View(app_parent))) => panic!(
597 "View {} was laid out without a parent when it was constructed with parent {}",
598 print_error(view_id),
599 print_error(*app_parent)
600 ),
601 (Some(layout_parent), Some(ParentId::Root)) => panic!(
602 "View {} was laid out with parent {} when it was constructed as a window root",
603 print_error(view_id),
604 print_error(*layout_parent),
605 ),
606 (_, None) => panic!(
607 "View {} did not have a registered parent in the app context",
608 print_error(view_id),
609 ),
610 _ => {}
611 }
612
613 self.view_stack.push(view_id);
614 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
615 let size = rendered_view.layout(constraint, self);
616 self.rendered_views.insert(view_id, rendered_view);
617 self.view_stack.pop();
618 size
619 }
620
621 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
622 where
623 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
624 V: View,
625 {
626 handle.update(self.app, |view, cx| {
627 let mut render_cx = RenderContext {
628 app: cx,
629 window_id: handle.window_id(),
630 view_id: handle.id(),
631 view_type: PhantomData,
632 titlebar_height: self.titlebar_height,
633 hovered_region_ids: self.hovered_region_ids.clone(),
634 clicked_region_ids: self.clicked_region_ids.clone(),
635 refreshing: self.refreshing,
636 appearance: self.appearance,
637 };
638 f(view, &mut render_cx)
639 })
640 }
641}
642
643impl<'a> Deref for LayoutContext<'a> {
644 type Target = MutableAppContext;
645
646 fn deref(&self) -> &Self::Target {
647 self.app
648 }
649}
650
651impl<'a> DerefMut for LayoutContext<'a> {
652 fn deref_mut(&mut self) -> &mut Self::Target {
653 self.app
654 }
655}
656
657impl<'a> ReadView for LayoutContext<'a> {
658 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
659 self.app.read_view(handle)
660 }
661}
662
663impl<'a> ReadModel for LayoutContext<'a> {
664 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
665 self.app.read_model(handle)
666 }
667}
668
669impl<'a> UpgradeModelHandle for LayoutContext<'a> {
670 fn upgrade_model_handle<T: Entity>(
671 &self,
672 handle: &WeakModelHandle<T>,
673 ) -> Option<ModelHandle<T>> {
674 self.app.upgrade_model_handle(handle)
675 }
676
677 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
678 self.app.model_handle_is_upgradable(handle)
679 }
680
681 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
682 self.app.upgrade_any_model_handle(handle)
683 }
684}
685
686impl<'a> UpgradeViewHandle for LayoutContext<'a> {
687 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
688 self.app.upgrade_view_handle(handle)
689 }
690
691 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
692 self.app.upgrade_any_view_handle(handle)
693 }
694}
695
696pub struct PaintContext<'a> {
697 rendered_views: &'a mut HashMap<usize, ElementBox>,
698 view_stack: Vec<usize>,
699 pub window_size: Vector2F,
700 pub scene: &'a mut Scene,
701 pub font_cache: &'a FontCache,
702 pub text_layout_cache: &'a TextLayoutCache,
703 pub app: &'a AppContext,
704}
705
706impl<'a> PaintContext<'a> {
707 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
708 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
709 self.view_stack.push(view_id);
710 tree.paint(origin, visible_bounds, self);
711 self.rendered_views.insert(view_id, tree);
712 self.view_stack.pop();
713 }
714 }
715
716 #[inline]
717 pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
718 where
719 F: FnOnce(&mut Self),
720 {
721 self.scene.push_layer(clip_bounds);
722 f(self);
723 self.scene.pop_layer();
724 }
725
726 pub fn current_view_id(&self) -> usize {
727 *self.view_stack.last().unwrap()
728 }
729}
730
731impl<'a> Deref for PaintContext<'a> {
732 type Target = AppContext;
733
734 fn deref(&self) -> &Self::Target {
735 self.app
736 }
737}
738
739pub struct EventContext<'a> {
740 rendered_views: &'a mut HashMap<usize, ElementBox>,
741 pub font_cache: &'a FontCache,
742 pub text_layout_cache: &'a TextLayoutCache,
743 pub app: &'a mut MutableAppContext,
744 pub window_id: usize,
745 pub notify_count: usize,
746 view_stack: Vec<usize>,
747 handled: bool,
748 invalidated_views: &'a mut HashSet<usize>,
749}
750
751impl<'a> EventContext<'a> {
752 fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
753 if let Some(mut element) = self.rendered_views.remove(&view_id) {
754 let result =
755 self.with_current_view(view_id, |this| element.dispatch_event(event, this));
756 self.rendered_views.insert(view_id, element);
757 result
758 } else {
759 false
760 }
761 }
762
763 fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
764 where
765 F: FnOnce(&mut Self) -> T,
766 {
767 self.view_stack.push(view_id);
768 let result = f(self);
769 self.view_stack.pop();
770 result
771 }
772
773 pub fn window_id(&self) -> usize {
774 self.window_id
775 }
776
777 pub fn view_id(&self) -> Option<usize> {
778 self.view_stack.last().copied()
779 }
780
781 pub fn is_parent_view_focused(&self) -> bool {
782 if let Some(parent_view_id) = self.view_stack.last() {
783 self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
784 } else {
785 false
786 }
787 }
788
789 pub fn focus_parent_view(&mut self) {
790 if let Some(parent_view_id) = self.view_stack.last() {
791 self.app.focus(self.window_id, Some(*parent_view_id))
792 }
793 }
794
795 pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
796 self.app
797 .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
798 }
799
800 pub fn dispatch_action<A: Action>(&mut self, action: A) {
801 self.dispatch_any_action(Box::new(action));
802 }
803
804 pub fn notify(&mut self) {
805 self.notify_count += 1;
806 if let Some(view_id) = self.view_stack.last() {
807 self.invalidated_views.insert(*view_id);
808 }
809 }
810
811 pub fn notify_count(&self) -> usize {
812 self.notify_count
813 }
814
815 pub fn propogate_event(&mut self) {
816 self.handled = false;
817 }
818}
819
820impl<'a> Deref for EventContext<'a> {
821 type Target = MutableAppContext;
822
823 fn deref(&self) -> &Self::Target {
824 self.app
825 }
826}
827
828impl<'a> DerefMut for EventContext<'a> {
829 fn deref_mut(&mut self) -> &mut Self::Target {
830 self.app
831 }
832}
833
834pub struct MeasurementContext<'a> {
835 app: &'a AppContext,
836 rendered_views: &'a HashMap<usize, ElementBox>,
837 pub window_id: usize,
838}
839
840impl<'a> Deref for MeasurementContext<'a> {
841 type Target = AppContext;
842
843 fn deref(&self) -> &Self::Target {
844 self.app
845 }
846}
847
848impl<'a> MeasurementContext<'a> {
849 fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
850 let element = self.rendered_views.get(&view_id)?;
851 element.rect_for_text_range(range_utf16, self)
852 }
853}
854
855pub struct DebugContext<'a> {
856 rendered_views: &'a HashMap<usize, ElementBox>,
857 pub font_cache: &'a FontCache,
858 pub app: &'a AppContext,
859}
860
861#[derive(Clone, Copy, Debug, Eq, PartialEq)]
862pub enum Axis {
863 Horizontal,
864 Vertical,
865}
866
867impl Axis {
868 pub fn invert(self) -> Self {
869 match self {
870 Self::Horizontal => Self::Vertical,
871 Self::Vertical => Self::Horizontal,
872 }
873 }
874}
875
876impl ToJson for Axis {
877 fn to_json(&self) -> serde_json::Value {
878 match self {
879 Axis::Horizontal => json!("horizontal"),
880 Axis::Vertical => json!("vertical"),
881 }
882 }
883}
884
885pub trait Vector2FExt {
886 fn along(self, axis: Axis) -> f32;
887}
888
889impl Vector2FExt for Vector2F {
890 fn along(self, axis: Axis) -> f32 {
891 match axis {
892 Axis::Horizontal => self.x(),
893 Axis::Vertical => self.y(),
894 }
895 }
896}
897
898#[derive(Copy, Clone, Debug)]
899pub struct SizeConstraint {
900 pub min: Vector2F,
901 pub max: Vector2F,
902}
903
904impl SizeConstraint {
905 pub fn new(min: Vector2F, max: Vector2F) -> Self {
906 Self { min, max }
907 }
908
909 pub fn strict(size: Vector2F) -> Self {
910 Self {
911 min: size,
912 max: size,
913 }
914 }
915
916 pub fn strict_along(axis: Axis, max: f32) -> Self {
917 match axis {
918 Axis::Horizontal => Self {
919 min: vec2f(max, 0.0),
920 max: vec2f(max, f32::INFINITY),
921 },
922 Axis::Vertical => Self {
923 min: vec2f(0.0, max),
924 max: vec2f(f32::INFINITY, max),
925 },
926 }
927 }
928
929 pub fn max_along(&self, axis: Axis) -> f32 {
930 match axis {
931 Axis::Horizontal => self.max.x(),
932 Axis::Vertical => self.max.y(),
933 }
934 }
935
936 pub fn min_along(&self, axis: Axis) -> f32 {
937 match axis {
938 Axis::Horizontal => self.min.x(),
939 Axis::Vertical => self.min.y(),
940 }
941 }
942
943 pub fn constrain(&self, size: Vector2F) -> Vector2F {
944 vec2f(
945 size.x().min(self.max.x()).max(self.min.x()),
946 size.y().min(self.max.y()).max(self.min.y()),
947 )
948 }
949}
950
951impl Default for SizeConstraint {
952 fn default() -> Self {
953 SizeConstraint {
954 min: Vector2F::zero(),
955 max: Vector2F::splat(f32::INFINITY),
956 }
957 }
958}
959
960impl ToJson for SizeConstraint {
961 fn to_json(&self) -> serde_json::Value {
962 json!({
963 "min": self.min.to_json(),
964 "max": self.max.to_json(),
965 })
966 }
967}
968
969pub struct ChildView {
970 view: AnyViewHandle,
971}
972
973impl ChildView {
974 pub fn new(view: impl Into<AnyViewHandle>) -> Self {
975 Self { view: view.into() }
976 }
977}
978
979impl Element for ChildView {
980 type LayoutState = ();
981 type PaintState = ();
982
983 fn layout(
984 &mut self,
985 constraint: SizeConstraint,
986 cx: &mut LayoutContext,
987 ) -> (Vector2F, Self::LayoutState) {
988 let size = cx.layout(self.view.id(), constraint);
989 (size, ())
990 }
991
992 fn paint(
993 &mut self,
994 bounds: RectF,
995 visible_bounds: RectF,
996 _: &mut Self::LayoutState,
997 cx: &mut PaintContext,
998 ) -> Self::PaintState {
999 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
1000 }
1001
1002 fn dispatch_event(
1003 &mut self,
1004 event: &Event,
1005 _: RectF,
1006 _: RectF,
1007 _: &mut Self::LayoutState,
1008 _: &mut Self::PaintState,
1009 cx: &mut EventContext,
1010 ) -> bool {
1011 cx.dispatch_event(self.view.id(), event)
1012 }
1013
1014 fn rect_for_text_range(
1015 &self,
1016 range_utf16: Range<usize>,
1017 _: RectF,
1018 _: RectF,
1019 _: &Self::LayoutState,
1020 _: &Self::PaintState,
1021 cx: &MeasurementContext,
1022 ) -> Option<RectF> {
1023 cx.rect_for_text_range(self.view.id(), range_utf16)
1024 }
1025
1026 fn debug(
1027 &self,
1028 bounds: RectF,
1029 _: &Self::LayoutState,
1030 _: &Self::PaintState,
1031 cx: &DebugContext,
1032 ) -> serde_json::Value {
1033 json!({
1034 "type": "ChildView",
1035 "view_id": self.view.id(),
1036 "bounds": bounds.to_json(),
1037 "view": self.view.debug_json(cx.app),
1038 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
1039 view.debug(cx)
1040 } else {
1041 json!(null)
1042 }
1043 })
1044 }
1045}