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(MouseEvent::click_disc(), Some(e.button))
479 || valid_region
480 .handlers
481 .contains(MouseEvent::drag_disc(), Some(e.button))
482 {
483 event_cx.handled = true;
484 }
485 }
486
487 // `event_consumed` should only be true if there are any handlers for this event.
488 let mut event_consumed = event_cx.handled;
489 if let Some(callbacks) = valid_region.handlers.get(&mouse_event.handler_key()) {
490 event_consumed = true;
491 for callback in callbacks {
492 event_cx.handled = true;
493 event_cx.with_current_view(valid_region.id().view_id(), {
494 let region_event = mouse_event.clone();
495 |cx| callback(region_event, cx)
496 });
497 event_consumed &= event_cx.handled;
498 any_event_handled |= event_cx.handled;
499 }
500 }
501
502 any_event_handled |= event_cx.handled;
503
504 // For bubbling events, if the event was handled, don't continue dispatching.
505 // This only makes sense for local events which return false from is_capturable.
506 if event_consumed && mouse_event.is_capturable() {
507 break;
508 }
509 }
510 }
511
512 for view_id in notified_views {
513 cx.notify_view(self.window_id, view_id);
514 }
515
516 any_event_handled
517 }
518
519 pub fn build_event_context<'a>(
520 &'a mut self,
521 notified_views: &'a mut HashSet<usize>,
522 cx: &'a mut MutableAppContext,
523 ) -> EventContext<'a> {
524 EventContext {
525 font_cache: &self.font_cache,
526 text_layout_cache: &self.text_layout_cache,
527 view_stack: Default::default(),
528 notified_views,
529 notify_count: 0,
530 handled: false,
531 window_id: self.window_id,
532 app: cx,
533 }
534 }
535
536 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
537 let view = cx.root_view(self.window_id)?;
538 Some(json!({
539 "root_view": view.debug_json(cx),
540 "root_element": self.rendered_views.get(&view.id())
541 .map(|root_element| {
542 root_element.debug(&DebugContext {
543 rendered_views: &self.rendered_views,
544 font_cache: &self.font_cache,
545 app: cx,
546 })
547 })
548 }))
549 }
550}
551
552pub struct LayoutContext<'a> {
553 window_id: usize,
554 rendered_views: &'a mut HashMap<usize, ElementBox>,
555 view_stack: Vec<usize>,
556 pub font_cache: &'a Arc<FontCache>,
557 pub font_system: Arc<dyn FontSystem>,
558 pub text_layout_cache: &'a TextLayoutCache,
559 pub asset_cache: &'a AssetCache,
560 pub app: &'a mut MutableAppContext,
561 pub refreshing: bool,
562 pub window_size: Vector2F,
563 titlebar_height: f32,
564 appearance: Appearance,
565 hovered_region_ids: HashSet<MouseRegionId>,
566 clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
567}
568
569impl<'a> LayoutContext<'a> {
570 pub(crate) fn keystrokes_for_action(
571 &self,
572 action: &dyn Action,
573 ) -> Option<SmallVec<[Keystroke; 2]>> {
574 self.app
575 .keystrokes_for_action(self.window_id, &self.view_stack, action)
576 }
577
578 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
579 let print_error = |view_id| {
580 format!(
581 "{} with id {}",
582 self.app.name_for_view(self.window_id, view_id).unwrap(),
583 view_id,
584 )
585 };
586 match (
587 self.view_stack.last(),
588 self.app.parents.get(&(self.window_id, view_id)),
589 ) {
590 (Some(layout_parent), Some(ParentId::View(app_parent))) => {
591 if layout_parent != app_parent {
592 panic!(
593 "View {} was laid out with parent {} when it was constructed with parent {}",
594 print_error(view_id),
595 print_error(*layout_parent),
596 print_error(*app_parent))
597 }
598 }
599 (None, Some(ParentId::View(app_parent))) => panic!(
600 "View {} was laid out without a parent when it was constructed with parent {}",
601 print_error(view_id),
602 print_error(*app_parent)
603 ),
604 (Some(layout_parent), Some(ParentId::Root)) => panic!(
605 "View {} was laid out with parent {} when it was constructed as a window root",
606 print_error(view_id),
607 print_error(*layout_parent),
608 ),
609 (_, None) => panic!(
610 "View {} did not have a registered parent in the app context",
611 print_error(view_id),
612 ),
613 _ => {}
614 }
615
616 self.view_stack.push(view_id);
617 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
618 let size = rendered_view.layout(constraint, self);
619 self.rendered_views.insert(view_id, rendered_view);
620 self.view_stack.pop();
621 size
622 }
623
624 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
625 where
626 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
627 V: View,
628 {
629 handle.update(self.app, |view, cx| {
630 let mut render_cx = RenderContext {
631 app: cx,
632 window_id: handle.window_id(),
633 view_id: handle.id(),
634 view_type: PhantomData,
635 titlebar_height: self.titlebar_height,
636 hovered_region_ids: self.hovered_region_ids.clone(),
637 clicked_region_ids: self.clicked_region_ids.clone(),
638 refreshing: self.refreshing,
639 appearance: self.appearance,
640 };
641 f(view, &mut render_cx)
642 })
643 }
644}
645
646impl<'a> Deref for LayoutContext<'a> {
647 type Target = MutableAppContext;
648
649 fn deref(&self) -> &Self::Target {
650 self.app
651 }
652}
653
654impl<'a> DerefMut for LayoutContext<'a> {
655 fn deref_mut(&mut self) -> &mut Self::Target {
656 self.app
657 }
658}
659
660impl<'a> ReadView for LayoutContext<'a> {
661 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
662 self.app.read_view(handle)
663 }
664}
665
666impl<'a> ReadModel for LayoutContext<'a> {
667 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
668 self.app.read_model(handle)
669 }
670}
671
672impl<'a> UpgradeModelHandle for LayoutContext<'a> {
673 fn upgrade_model_handle<T: Entity>(
674 &self,
675 handle: &WeakModelHandle<T>,
676 ) -> Option<ModelHandle<T>> {
677 self.app.upgrade_model_handle(handle)
678 }
679
680 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
681 self.app.model_handle_is_upgradable(handle)
682 }
683
684 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
685 self.app.upgrade_any_model_handle(handle)
686 }
687}
688
689impl<'a> UpgradeViewHandle for LayoutContext<'a> {
690 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
691 self.app.upgrade_view_handle(handle)
692 }
693
694 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
695 self.app.upgrade_any_view_handle(handle)
696 }
697}
698
699pub struct PaintContext<'a> {
700 rendered_views: &'a mut HashMap<usize, ElementBox>,
701 view_stack: Vec<usize>,
702 pub window_size: Vector2F,
703 pub scene: &'a mut SceneBuilder,
704 pub font_cache: &'a FontCache,
705 pub text_layout_cache: &'a TextLayoutCache,
706 pub app: &'a AppContext,
707}
708
709impl<'a> PaintContext<'a> {
710 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
711 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
712 self.view_stack.push(view_id);
713 tree.paint(origin, visible_bounds, self);
714 self.rendered_views.insert(view_id, tree);
715 self.view_stack.pop();
716 }
717 }
718
719 #[inline]
720 pub fn paint_stacking_context<F>(
721 &mut self,
722 clip_bounds: Option<RectF>,
723 z_index: Option<usize>,
724 f: F,
725 ) where
726 F: FnOnce(&mut Self),
727 {
728 self.scene.push_stacking_context(clip_bounds, z_index);
729 f(self);
730 self.scene.pop_stacking_context();
731 }
732
733 #[inline]
734 pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
735 where
736 F: FnOnce(&mut Self),
737 {
738 self.scene.push_layer(clip_bounds);
739 f(self);
740 self.scene.pop_layer();
741 }
742
743 pub fn current_view_id(&self) -> usize {
744 *self.view_stack.last().unwrap()
745 }
746}
747
748impl<'a> Deref for PaintContext<'a> {
749 type Target = AppContext;
750
751 fn deref(&self) -> &Self::Target {
752 self.app
753 }
754}
755
756pub struct EventContext<'a> {
757 pub font_cache: &'a FontCache,
758 pub text_layout_cache: &'a TextLayoutCache,
759 pub app: &'a mut MutableAppContext,
760 pub window_id: usize,
761 pub notify_count: usize,
762 view_stack: Vec<usize>,
763 handled: bool,
764 notified_views: &'a mut HashSet<usize>,
765}
766
767impl<'a> EventContext<'a> {
768 fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
769 where
770 F: FnOnce(&mut Self) -> T,
771 {
772 self.view_stack.push(view_id);
773 let result = f(self);
774 self.view_stack.pop();
775 result
776 }
777
778 pub fn window_id(&self) -> usize {
779 self.window_id
780 }
781
782 pub fn view_id(&self) -> Option<usize> {
783 self.view_stack.last().copied()
784 }
785
786 pub fn is_parent_view_focused(&self) -> bool {
787 if let Some(parent_view_id) = self.view_stack.last() {
788 self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
789 } else {
790 false
791 }
792 }
793
794 pub fn focus_parent_view(&mut self) {
795 if let Some(parent_view_id) = self.view_stack.last() {
796 self.app.focus(self.window_id, Some(*parent_view_id))
797 }
798 }
799
800 pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
801 self.app
802 .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
803 }
804
805 pub fn dispatch_action<A: Action>(&mut self, action: A) {
806 self.dispatch_any_action(Box::new(action));
807 }
808
809 pub fn notify(&mut self) {
810 self.notify_count += 1;
811 if let Some(view_id) = self.view_stack.last() {
812 self.notified_views.insert(*view_id);
813 }
814 }
815
816 pub fn notify_count(&self) -> usize {
817 self.notify_count
818 }
819
820 pub fn propagate_event(&mut self) {
821 self.handled = false;
822 }
823}
824
825impl<'a> Deref for EventContext<'a> {
826 type Target = MutableAppContext;
827
828 fn deref(&self) -> &Self::Target {
829 self.app
830 }
831}
832
833impl<'a> DerefMut for EventContext<'a> {
834 fn deref_mut(&mut self) -> &mut Self::Target {
835 self.app
836 }
837}
838
839pub struct MeasurementContext<'a> {
840 app: &'a AppContext,
841 rendered_views: &'a HashMap<usize, ElementBox>,
842 pub window_id: usize,
843}
844
845impl<'a> Deref for MeasurementContext<'a> {
846 type Target = AppContext;
847
848 fn deref(&self) -> &Self::Target {
849 self.app
850 }
851}
852
853impl<'a> MeasurementContext<'a> {
854 fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
855 let element = self.rendered_views.get(&view_id)?;
856 element.rect_for_text_range(range_utf16, self)
857 }
858}
859
860pub struct DebugContext<'a> {
861 rendered_views: &'a HashMap<usize, ElementBox>,
862 pub font_cache: &'a FontCache,
863 pub app: &'a AppContext,
864}
865
866#[derive(Clone, Copy, Debug, Eq, PartialEq)]
867pub enum Axis {
868 Horizontal,
869 Vertical,
870}
871
872impl Axis {
873 pub fn invert(self) -> Self {
874 match self {
875 Self::Horizontal => Self::Vertical,
876 Self::Vertical => Self::Horizontal,
877 }
878 }
879
880 pub fn component(&self, point: Vector2F) -> f32 {
881 match self {
882 Self::Horizontal => point.x(),
883 Self::Vertical => point.y(),
884 }
885 }
886}
887
888impl ToJson for Axis {
889 fn to_json(&self) -> serde_json::Value {
890 match self {
891 Axis::Horizontal => json!("horizontal"),
892 Axis::Vertical => json!("vertical"),
893 }
894 }
895}
896
897pub trait Vector2FExt {
898 fn along(self, axis: Axis) -> f32;
899}
900
901impl Vector2FExt for Vector2F {
902 fn along(self, axis: Axis) -> f32 {
903 match axis {
904 Axis::Horizontal => self.x(),
905 Axis::Vertical => self.y(),
906 }
907 }
908}
909
910#[derive(Copy, Clone, Debug)]
911pub struct SizeConstraint {
912 pub min: Vector2F,
913 pub max: Vector2F,
914}
915
916impl SizeConstraint {
917 pub fn new(min: Vector2F, max: Vector2F) -> Self {
918 Self { min, max }
919 }
920
921 pub fn strict(size: Vector2F) -> Self {
922 Self {
923 min: size,
924 max: size,
925 }
926 }
927
928 pub fn strict_along(axis: Axis, max: f32) -> Self {
929 match axis {
930 Axis::Horizontal => Self {
931 min: vec2f(max, 0.0),
932 max: vec2f(max, f32::INFINITY),
933 },
934 Axis::Vertical => Self {
935 min: vec2f(0.0, max),
936 max: vec2f(f32::INFINITY, max),
937 },
938 }
939 }
940
941 pub fn max_along(&self, axis: Axis) -> f32 {
942 match axis {
943 Axis::Horizontal => self.max.x(),
944 Axis::Vertical => self.max.y(),
945 }
946 }
947
948 pub fn min_along(&self, axis: Axis) -> f32 {
949 match axis {
950 Axis::Horizontal => self.min.x(),
951 Axis::Vertical => self.min.y(),
952 }
953 }
954
955 pub fn constrain(&self, size: Vector2F) -> Vector2F {
956 vec2f(
957 size.x().min(self.max.x()).max(self.min.x()),
958 size.y().min(self.max.y()).max(self.min.y()),
959 )
960 }
961}
962
963impl Default for SizeConstraint {
964 fn default() -> Self {
965 SizeConstraint {
966 min: Vector2F::zero(),
967 max: Vector2F::splat(f32::INFINITY),
968 }
969 }
970}
971
972impl ToJson for SizeConstraint {
973 fn to_json(&self) -> serde_json::Value {
974 json!({
975 "min": self.min.to_json(),
976 "max": self.max.to_json(),
977 })
978 }
979}
980
981pub struct ChildView {
982 view: AnyWeakViewHandle,
983 view_name: &'static str,
984}
985
986impl ChildView {
987 pub fn new(view: impl Into<AnyViewHandle>, cx: &AppContext) -> Self {
988 let view = view.into();
989 let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
990 Self {
991 view: view.downgrade(),
992 view_name,
993 }
994 }
995}
996
997impl Element for ChildView {
998 type LayoutState = bool;
999 type PaintState = ();
1000
1001 fn layout(
1002 &mut self,
1003 constraint: SizeConstraint,
1004 cx: &mut LayoutContext,
1005 ) -> (Vector2F, Self::LayoutState) {
1006 if cx.rendered_views.contains_key(&self.view.id()) {
1007 let size = cx.layout(self.view.id(), constraint);
1008 (size, true)
1009 } else {
1010 log::error!(
1011 "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1012 self.view.id(),
1013 self.view_name
1014 );
1015 (Vector2F::zero(), false)
1016 }
1017 }
1018
1019 fn paint(
1020 &mut self,
1021 bounds: RectF,
1022 visible_bounds: RectF,
1023 view_is_valid: &mut Self::LayoutState,
1024 cx: &mut PaintContext,
1025 ) {
1026 if *view_is_valid {
1027 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
1028 } else {
1029 log::error!(
1030 "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1031 self.view.id(),
1032 self.view_name
1033 );
1034 }
1035 }
1036
1037 fn rect_for_text_range(
1038 &self,
1039 range_utf16: Range<usize>,
1040 _: RectF,
1041 _: RectF,
1042 view_is_valid: &Self::LayoutState,
1043 _: &Self::PaintState,
1044 cx: &MeasurementContext,
1045 ) -> Option<RectF> {
1046 if *view_is_valid {
1047 cx.rect_for_text_range(self.view.id(), range_utf16)
1048 } else {
1049 log::error!(
1050 "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1051 self.view.id(),
1052 self.view_name
1053 );
1054 None
1055 }
1056 }
1057
1058 fn debug(
1059 &self,
1060 bounds: RectF,
1061 _: &Self::LayoutState,
1062 _: &Self::PaintState,
1063 cx: &DebugContext,
1064 ) -> serde_json::Value {
1065 json!({
1066 "type": "ChildView",
1067 "view_id": self.view.id(),
1068 "bounds": bounds.to_json(),
1069 "view": if let Some(view) = self.view.upgrade(cx.app) {
1070 view.debug_json(cx.app)
1071 } else {
1072 json!(null)
1073 },
1074 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
1075 view.debug(cx)
1076 } else {
1077 json!(null)
1078 }
1079 })
1080 }
1081}