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