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 || region.notify_on_move {
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 || region.notify_on_move {
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 valid_regions.push(region.clone());
406 if region.notify_on_click {
407 notified_views.insert(region.id().view_id());
408 }
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 MouseEvent::Move(_) => {
451 for (mouse_region, _) in self.mouse_regions.iter().rev() {
452 if mouse_region.bounds.contains_point(self.mouse_position) {
453 valid_regions.push(mouse_region.clone());
454 if mouse_region.notify_on_move {
455 notified_views.insert(mouse_region.id().view_id());
456 }
457 }
458 }
459 }
460 _ => {
461 for (mouse_region, _) in self.mouse_regions.iter().rev() {
462 // Contains
463 if mouse_region.bounds.contains_point(self.mouse_position) {
464 valid_regions.push(mouse_region.clone());
465 }
466 }
467 }
468 }
469
470 //3. Fire region events
471 let hovered_region_ids = self.hovered_region_ids.clone();
472 for valid_region in valid_regions.into_iter() {
473 let mut event_cx = self.build_event_context(&mut notified_views, cx);
474
475 mouse_event.set_region(valid_region.bounds);
476 if let MouseEvent::Hover(e) = &mut mouse_event {
477 e.started = hovered_region_ids.contains(&valid_region.id())
478 }
479 // Handle Down events if the MouseRegion has a Click or Drag handler. This makes the api more intuitive as you would
480 // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
481 // This behavior can be overridden by adding a Down handler that calls cx.propogate_event
482 if let MouseEvent::Down(e) = &mouse_event {
483 if valid_region
484 .handlers
485 .contains_handler(MouseEvent::click_disc(), Some(e.button))
486 || valid_region
487 .handlers
488 .contains_handler(MouseEvent::drag_disc(), Some(e.button))
489 {
490 event_cx.handled = true;
491 }
492 }
493
494 if let Some(callback) = valid_region.handlers.get(&mouse_event.handler_key()) {
495 event_cx.handled = true;
496 event_cx.with_current_view(valid_region.id().view_id(), {
497 let region_event = mouse_event.clone();
498 |cx| callback(region_event, cx)
499 });
500 }
501
502 any_event_handled = any_event_handled || event_cx.handled;
503 // For bubbling events, if the event was handled, don't continue dispatching
504 // This only makes sense for local events.
505 if event_cx.handled && mouse_event.is_capturable() {
506 break;
507 }
508 }
509 }
510
511 for view_id in notified_views {
512 cx.notify_view(self.window_id, view_id);
513 }
514
515 any_event_handled
516 }
517
518 pub fn build_event_context<'a>(
519 &'a mut self,
520 notified_views: &'a mut HashSet<usize>,
521 cx: &'a mut MutableAppContext,
522 ) -> EventContext<'a> {
523 EventContext {
524 font_cache: &self.font_cache,
525 text_layout_cache: &self.text_layout_cache,
526 view_stack: Default::default(),
527 notified_views,
528 notify_count: 0,
529 handled: false,
530 window_id: self.window_id,
531 app: cx,
532 }
533 }
534
535 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
536 let view = cx.root_view(self.window_id)?;
537 Some(json!({
538 "root_view": view.debug_json(cx),
539 "root_element": self.rendered_views.get(&view.id())
540 .map(|root_element| {
541 root_element.debug(&DebugContext {
542 rendered_views: &self.rendered_views,
543 font_cache: &self.font_cache,
544 app: cx,
545 })
546 })
547 }))
548 }
549}
550
551pub struct LayoutContext<'a> {
552 window_id: usize,
553 rendered_views: &'a mut HashMap<usize, ElementBox>,
554 view_stack: Vec<usize>,
555 pub font_cache: &'a Arc<FontCache>,
556 pub font_system: Arc<dyn FontSystem>,
557 pub text_layout_cache: &'a TextLayoutCache,
558 pub asset_cache: &'a AssetCache,
559 pub app: &'a mut MutableAppContext,
560 pub refreshing: bool,
561 pub window_size: Vector2F,
562 titlebar_height: f32,
563 appearance: Appearance,
564 hovered_region_ids: HashSet<MouseRegionId>,
565 clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
566}
567
568impl<'a> LayoutContext<'a> {
569 pub(crate) fn keystrokes_for_action(
570 &self,
571 action: &dyn Action,
572 ) -> Option<SmallVec<[Keystroke; 2]>> {
573 self.app
574 .keystrokes_for_action(self.window_id, &self.view_stack, action)
575 }
576
577 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
578 let print_error = |view_id| {
579 format!(
580 "{} with id {}",
581 self.app.name_for_view(self.window_id, view_id).unwrap(),
582 view_id,
583 )
584 };
585 match (
586 self.view_stack.last(),
587 self.app.parents.get(&(self.window_id, view_id)),
588 ) {
589 (Some(layout_parent), Some(ParentId::View(app_parent))) => {
590 if layout_parent != app_parent {
591 panic!(
592 "View {} was laid out with parent {} when it was constructed with parent {}",
593 print_error(view_id),
594 print_error(*layout_parent),
595 print_error(*app_parent))
596 }
597 }
598 (None, Some(ParentId::View(app_parent))) => panic!(
599 "View {} was laid out without a parent when it was constructed with parent {}",
600 print_error(view_id),
601 print_error(*app_parent)
602 ),
603 (Some(layout_parent), Some(ParentId::Root)) => panic!(
604 "View {} was laid out with parent {} when it was constructed as a window root",
605 print_error(view_id),
606 print_error(*layout_parent),
607 ),
608 (_, None) => panic!(
609 "View {} did not have a registered parent in the app context",
610 print_error(view_id),
611 ),
612 _ => {}
613 }
614
615 self.view_stack.push(view_id);
616 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
617 let size = rendered_view.layout(constraint, self);
618 self.rendered_views.insert(view_id, rendered_view);
619 self.view_stack.pop();
620 size
621 }
622
623 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
624 where
625 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
626 V: View,
627 {
628 handle.update(self.app, |view, cx| {
629 let mut render_cx = RenderContext {
630 app: cx,
631 window_id: handle.window_id(),
632 view_id: handle.id(),
633 view_type: PhantomData,
634 titlebar_height: self.titlebar_height,
635 hovered_region_ids: self.hovered_region_ids.clone(),
636 clicked_region_ids: self.clicked_region_ids.clone(),
637 refreshing: self.refreshing,
638 appearance: self.appearance,
639 };
640 f(view, &mut render_cx)
641 })
642 }
643}
644
645impl<'a> Deref for LayoutContext<'a> {
646 type Target = MutableAppContext;
647
648 fn deref(&self) -> &Self::Target {
649 self.app
650 }
651}
652
653impl<'a> DerefMut for LayoutContext<'a> {
654 fn deref_mut(&mut self) -> &mut Self::Target {
655 self.app
656 }
657}
658
659impl<'a> ReadView for LayoutContext<'a> {
660 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
661 self.app.read_view(handle)
662 }
663}
664
665impl<'a> ReadModel for LayoutContext<'a> {
666 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
667 self.app.read_model(handle)
668 }
669}
670
671impl<'a> UpgradeModelHandle for LayoutContext<'a> {
672 fn upgrade_model_handle<T: Entity>(
673 &self,
674 handle: &WeakModelHandle<T>,
675 ) -> Option<ModelHandle<T>> {
676 self.app.upgrade_model_handle(handle)
677 }
678
679 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
680 self.app.model_handle_is_upgradable(handle)
681 }
682
683 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
684 self.app.upgrade_any_model_handle(handle)
685 }
686}
687
688impl<'a> UpgradeViewHandle for LayoutContext<'a> {
689 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
690 self.app.upgrade_view_handle(handle)
691 }
692
693 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
694 self.app.upgrade_any_view_handle(handle)
695 }
696}
697
698pub struct PaintContext<'a> {
699 rendered_views: &'a mut HashMap<usize, ElementBox>,
700 view_stack: Vec<usize>,
701 pub window_size: Vector2F,
702 pub scene: &'a mut Scene,
703 pub font_cache: &'a FontCache,
704 pub text_layout_cache: &'a TextLayoutCache,
705 pub app: &'a AppContext,
706}
707
708impl<'a> PaintContext<'a> {
709 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
710 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
711 self.view_stack.push(view_id);
712 tree.paint(origin, visible_bounds, self);
713 self.rendered_views.insert(view_id, tree);
714 self.view_stack.pop();
715 }
716 }
717
718 #[inline]
719 pub fn paint_stacking_context<F>(&mut self, clip_bounds: Option<RectF>, f: F)
720 where
721 F: FnOnce(&mut Self),
722 {
723 self.scene.push_stacking_context(clip_bounds);
724 f(self);
725 self.scene.pop_stacking_context();
726 }
727
728 #[inline]
729 pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
730 where
731 F: FnOnce(&mut Self),
732 {
733 self.scene.push_layer(clip_bounds);
734 f(self);
735 self.scene.pop_layer();
736 }
737
738 pub fn current_view_id(&self) -> usize {
739 *self.view_stack.last().unwrap()
740 }
741}
742
743impl<'a> Deref for PaintContext<'a> {
744 type Target = AppContext;
745
746 fn deref(&self) -> &Self::Target {
747 self.app
748 }
749}
750
751pub struct EventContext<'a> {
752 pub font_cache: &'a FontCache,
753 pub text_layout_cache: &'a TextLayoutCache,
754 pub app: &'a mut MutableAppContext,
755 pub window_id: usize,
756 pub notify_count: usize,
757 view_stack: Vec<usize>,
758 handled: bool,
759 notified_views: &'a mut HashSet<usize>,
760}
761
762impl<'a> EventContext<'a> {
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.notified_views.insert(*view_id);
808 }
809 }
810
811 pub fn notify_count(&self) -> usize {
812 self.notify_count
813 }
814
815 pub fn propagate_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 pub fn component(&self, point: Vector2F) -> f32 {
876 match self {
877 Self::Horizontal => point.x(),
878 Self::Vertical => point.y(),
879 }
880 }
881}
882
883impl ToJson for Axis {
884 fn to_json(&self) -> serde_json::Value {
885 match self {
886 Axis::Horizontal => json!("horizontal"),
887 Axis::Vertical => json!("vertical"),
888 }
889 }
890}
891
892pub trait Vector2FExt {
893 fn along(self, axis: Axis) -> f32;
894}
895
896impl Vector2FExt for Vector2F {
897 fn along(self, axis: Axis) -> f32 {
898 match axis {
899 Axis::Horizontal => self.x(),
900 Axis::Vertical => self.y(),
901 }
902 }
903}
904
905#[derive(Copy, Clone, Debug)]
906pub struct SizeConstraint {
907 pub min: Vector2F,
908 pub max: Vector2F,
909}
910
911impl SizeConstraint {
912 pub fn new(min: Vector2F, max: Vector2F) -> Self {
913 Self { min, max }
914 }
915
916 pub fn strict(size: Vector2F) -> Self {
917 Self {
918 min: size,
919 max: size,
920 }
921 }
922
923 pub fn strict_along(axis: Axis, max: f32) -> Self {
924 match axis {
925 Axis::Horizontal => Self {
926 min: vec2f(max, 0.0),
927 max: vec2f(max, f32::INFINITY),
928 },
929 Axis::Vertical => Self {
930 min: vec2f(0.0, max),
931 max: vec2f(f32::INFINITY, max),
932 },
933 }
934 }
935
936 pub fn max_along(&self, axis: Axis) -> f32 {
937 match axis {
938 Axis::Horizontal => self.max.x(),
939 Axis::Vertical => self.max.y(),
940 }
941 }
942
943 pub fn min_along(&self, axis: Axis) -> f32 {
944 match axis {
945 Axis::Horizontal => self.min.x(),
946 Axis::Vertical => self.min.y(),
947 }
948 }
949
950 pub fn constrain(&self, size: Vector2F) -> Vector2F {
951 vec2f(
952 size.x().min(self.max.x()).max(self.min.x()),
953 size.y().min(self.max.y()).max(self.min.y()),
954 )
955 }
956}
957
958impl Default for SizeConstraint {
959 fn default() -> Self {
960 SizeConstraint {
961 min: Vector2F::zero(),
962 max: Vector2F::splat(f32::INFINITY),
963 }
964 }
965}
966
967impl ToJson for SizeConstraint {
968 fn to_json(&self) -> serde_json::Value {
969 json!({
970 "min": self.min.to_json(),
971 "max": self.max.to_json(),
972 })
973 }
974}
975
976pub struct ChildView {
977 view: AnyWeakViewHandle,
978 view_name: &'static str,
979}
980
981impl ChildView {
982 pub fn new(view: impl Into<AnyViewHandle>, cx: &AppContext) -> Self {
983 let view = view.into();
984 let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
985 Self {
986 view: view.downgrade(),
987 view_name,
988 }
989 }
990}
991
992impl Element for ChildView {
993 type LayoutState = bool;
994 type PaintState = ();
995
996 fn layout(
997 &mut self,
998 constraint: SizeConstraint,
999 cx: &mut LayoutContext,
1000 ) -> (Vector2F, Self::LayoutState) {
1001 if cx.rendered_views.contains_key(&self.view.id()) {
1002 let size = cx.layout(self.view.id(), constraint);
1003 (size, true)
1004 } else {
1005 log::error!(
1006 "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1007 self.view.id(),
1008 self.view_name
1009 );
1010 (Vector2F::zero(), false)
1011 }
1012 }
1013
1014 fn paint(
1015 &mut self,
1016 bounds: RectF,
1017 visible_bounds: RectF,
1018 view_is_valid: &mut Self::LayoutState,
1019 cx: &mut PaintContext,
1020 ) {
1021 if *view_is_valid {
1022 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
1023 } else {
1024 log::error!(
1025 "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1026 self.view.id(),
1027 self.view_name
1028 );
1029 }
1030 }
1031
1032 fn rect_for_text_range(
1033 &self,
1034 range_utf16: Range<usize>,
1035 _: RectF,
1036 _: RectF,
1037 view_is_valid: &Self::LayoutState,
1038 _: &Self::PaintState,
1039 cx: &MeasurementContext,
1040 ) -> Option<RectF> {
1041 if *view_is_valid {
1042 cx.rect_for_text_range(self.view.id(), range_utf16)
1043 } else {
1044 log::error!(
1045 "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1046 self.view.id(),
1047 self.view_name
1048 );
1049 None
1050 }
1051 }
1052
1053 fn debug(
1054 &self,
1055 bounds: RectF,
1056 _: &Self::LayoutState,
1057 _: &Self::PaintState,
1058 cx: &DebugContext,
1059 ) -> serde_json::Value {
1060 json!({
1061 "type": "ChildView",
1062 "view_id": self.view.id(),
1063 "bounds": bounds.to_json(),
1064 "view": if let Some(view) = self.view.upgrade(cx.app) {
1065 view.debug_json(cx.app)
1066 } else {
1067 json!(null)
1068 },
1069 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
1070 view.debug(cx)
1071 } else {
1072 json!(null)
1073 }
1074 })
1075 }
1076}