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