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_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
712 where
713 F: FnOnce(&mut Self),
714 {
715 self.scene.push_layer(clip_bounds);
716 f(self);
717 self.scene.pop_layer();
718 }
719
720 pub fn current_view_id(&self) -> usize {
721 *self.view_stack.last().unwrap()
722 }
723}
724
725impl<'a> Deref for PaintContext<'a> {
726 type Target = AppContext;
727
728 fn deref(&self) -> &Self::Target {
729 self.app
730 }
731}
732
733pub struct EventContext<'a> {
734 pub font_cache: &'a FontCache,
735 pub text_layout_cache: &'a TextLayoutCache,
736 pub app: &'a mut MutableAppContext,
737 pub window_id: usize,
738 pub notify_count: usize,
739 view_stack: Vec<usize>,
740 handled: bool,
741 notified_views: &'a mut HashSet<usize>,
742}
743
744impl<'a> EventContext<'a> {
745 fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
746 where
747 F: FnOnce(&mut Self) -> T,
748 {
749 self.view_stack.push(view_id);
750 let result = f(self);
751 self.view_stack.pop();
752 result
753 }
754
755 pub fn window_id(&self) -> usize {
756 self.window_id
757 }
758
759 pub fn view_id(&self) -> Option<usize> {
760 self.view_stack.last().copied()
761 }
762
763 pub fn is_parent_view_focused(&self) -> bool {
764 if let Some(parent_view_id) = self.view_stack.last() {
765 self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
766 } else {
767 false
768 }
769 }
770
771 pub fn focus_parent_view(&mut self) {
772 if let Some(parent_view_id) = self.view_stack.last() {
773 self.app.focus(self.window_id, Some(*parent_view_id))
774 }
775 }
776
777 pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
778 self.app
779 .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
780 }
781
782 pub fn dispatch_action<A: Action>(&mut self, action: A) {
783 self.dispatch_any_action(Box::new(action));
784 }
785
786 pub fn notify(&mut self) {
787 self.notify_count += 1;
788 if let Some(view_id) = self.view_stack.last() {
789 self.notified_views.insert(*view_id);
790 }
791 }
792
793 pub fn notify_count(&self) -> usize {
794 self.notify_count
795 }
796
797 pub fn propogate_event(&mut self) {
798 self.handled = false;
799 }
800}
801
802impl<'a> Deref for EventContext<'a> {
803 type Target = MutableAppContext;
804
805 fn deref(&self) -> &Self::Target {
806 self.app
807 }
808}
809
810impl<'a> DerefMut for EventContext<'a> {
811 fn deref_mut(&mut self) -> &mut Self::Target {
812 self.app
813 }
814}
815
816pub struct MeasurementContext<'a> {
817 app: &'a AppContext,
818 rendered_views: &'a HashMap<usize, ElementBox>,
819 pub window_id: usize,
820}
821
822impl<'a> Deref for MeasurementContext<'a> {
823 type Target = AppContext;
824
825 fn deref(&self) -> &Self::Target {
826 self.app
827 }
828}
829
830impl<'a> MeasurementContext<'a> {
831 fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
832 let element = self.rendered_views.get(&view_id)?;
833 element.rect_for_text_range(range_utf16, self)
834 }
835}
836
837pub struct DebugContext<'a> {
838 rendered_views: &'a HashMap<usize, ElementBox>,
839 pub font_cache: &'a FontCache,
840 pub app: &'a AppContext,
841}
842
843#[derive(Clone, Copy, Debug, Eq, PartialEq)]
844pub enum Axis {
845 Horizontal,
846 Vertical,
847}
848
849impl Axis {
850 pub fn invert(self) -> Self {
851 match self {
852 Self::Horizontal => Self::Vertical,
853 Self::Vertical => Self::Horizontal,
854 }
855 }
856}
857
858impl ToJson for Axis {
859 fn to_json(&self) -> serde_json::Value {
860 match self {
861 Axis::Horizontal => json!("horizontal"),
862 Axis::Vertical => json!("vertical"),
863 }
864 }
865}
866
867pub trait Vector2FExt {
868 fn along(self, axis: Axis) -> f32;
869}
870
871impl Vector2FExt for Vector2F {
872 fn along(self, axis: Axis) -> f32 {
873 match axis {
874 Axis::Horizontal => self.x(),
875 Axis::Vertical => self.y(),
876 }
877 }
878}
879
880#[derive(Copy, Clone, Debug)]
881pub struct SizeConstraint {
882 pub min: Vector2F,
883 pub max: Vector2F,
884}
885
886impl SizeConstraint {
887 pub fn new(min: Vector2F, max: Vector2F) -> Self {
888 Self { min, max }
889 }
890
891 pub fn strict(size: Vector2F) -> Self {
892 Self {
893 min: size,
894 max: size,
895 }
896 }
897
898 pub fn strict_along(axis: Axis, max: f32) -> Self {
899 match axis {
900 Axis::Horizontal => Self {
901 min: vec2f(max, 0.0),
902 max: vec2f(max, f32::INFINITY),
903 },
904 Axis::Vertical => Self {
905 min: vec2f(0.0, max),
906 max: vec2f(f32::INFINITY, max),
907 },
908 }
909 }
910
911 pub fn max_along(&self, axis: Axis) -> f32 {
912 match axis {
913 Axis::Horizontal => self.max.x(),
914 Axis::Vertical => self.max.y(),
915 }
916 }
917
918 pub fn min_along(&self, axis: Axis) -> f32 {
919 match axis {
920 Axis::Horizontal => self.min.x(),
921 Axis::Vertical => self.min.y(),
922 }
923 }
924
925 pub fn constrain(&self, size: Vector2F) -> Vector2F {
926 vec2f(
927 size.x().min(self.max.x()).max(self.min.x()),
928 size.y().min(self.max.y()).max(self.min.y()),
929 )
930 }
931}
932
933impl Default for SizeConstraint {
934 fn default() -> Self {
935 SizeConstraint {
936 min: Vector2F::zero(),
937 max: Vector2F::splat(f32::INFINITY),
938 }
939 }
940}
941
942impl ToJson for SizeConstraint {
943 fn to_json(&self) -> serde_json::Value {
944 json!({
945 "min": self.min.to_json(),
946 "max": self.max.to_json(),
947 })
948 }
949}
950
951pub struct ChildView {
952 view: AnyWeakViewHandle,
953 view_name: &'static str,
954}
955
956impl ChildView {
957 pub fn new(view: impl Into<AnyViewHandle>, cx: &AppContext) -> Self {
958 let view = view.into();
959 let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
960 Self {
961 view: view.downgrade(),
962 view_name,
963 }
964 }
965}
966
967impl Element for ChildView {
968 type LayoutState = bool;
969 type PaintState = ();
970
971 fn layout(
972 &mut self,
973 constraint: SizeConstraint,
974 cx: &mut LayoutContext,
975 ) -> (Vector2F, Self::LayoutState) {
976 if cx.rendered_views.contains_key(&self.view.id()) {
977 let size = cx.layout(self.view.id(), constraint);
978 (size, true)
979 } else {
980 log::error!(
981 "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
982 self.view.id(),
983 self.view_name
984 );
985 (Vector2F::zero(), false)
986 }
987 }
988
989 fn paint(
990 &mut self,
991 bounds: RectF,
992 visible_bounds: RectF,
993 view_is_valid: &mut Self::LayoutState,
994 cx: &mut PaintContext,
995 ) {
996 if *view_is_valid {
997 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
998 } else {
999 log::error!(
1000 "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1001 self.view.id(),
1002 self.view_name
1003 );
1004 }
1005 }
1006
1007 fn rect_for_text_range(
1008 &self,
1009 range_utf16: Range<usize>,
1010 _: RectF,
1011 _: RectF,
1012 view_is_valid: &Self::LayoutState,
1013 _: &Self::PaintState,
1014 cx: &MeasurementContext,
1015 ) -> Option<RectF> {
1016 if *view_is_valid {
1017 cx.rect_for_text_range(self.view.id(), range_utf16)
1018 } else {
1019 log::error!(
1020 "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1021 self.view.id(),
1022 self.view_name
1023 );
1024 None
1025 }
1026 }
1027
1028 fn debug(
1029 &self,
1030 bounds: RectF,
1031 _: &Self::LayoutState,
1032 _: &Self::PaintState,
1033 cx: &DebugContext,
1034 ) -> serde_json::Value {
1035 json!({
1036 "type": "ChildView",
1037 "view_id": self.view.id(),
1038 "bounds": bounds.to_json(),
1039 "view": if let Some(view) = self.view.upgrade(cx.app) {
1040 view.debug_json(cx.app)
1041 } else {
1042 json!(null)
1043 },
1044 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
1045 view.debug(cx)
1046 } else {
1047 json!(null)
1048 }
1049 })
1050 }
1051}