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