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