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