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