1use crate::{
2 elements::AnyRootElement,
3 geometry::rect::RectF,
4 json::ToJson,
5 keymap_matcher::{Binding, KeymapContext, Keystroke, MatchResult},
6 platform::{
7 self, Appearance, CursorStyle, Event, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent,
8 MouseButton, MouseMovedEvent, PromptLevel, WindowBounds,
9 },
10 scene::{
11 CursorRegion, MouseClick, MouseClickOut, MouseDown, MouseDownOut, MouseDrag, MouseEvent,
12 MouseHover, MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut, Scene,
13 },
14 text_layout::TextLayoutCache,
15 util::post_inc,
16 Action, AnyView, AnyViewHandle, AppContext, BorrowAppContext, BorrowWindowContext, Effect,
17 Element, Entity, Handle, LayoutContext, MouseRegion, MouseRegionId, SceneBuilder, Subscription,
18 View, ViewContext, ViewHandle, WindowInvalidation,
19};
20use anyhow::{anyhow, bail, Result};
21use collections::{HashMap, HashSet};
22use pathfinder_geometry::vector::{vec2f, Vector2F};
23use postage::oneshot;
24use serde_json::json;
25use smallvec::SmallVec;
26use sqlez::{
27 bindable::{Bind, Column, StaticColumnCount},
28 statement::Statement,
29};
30use std::{
31 any::TypeId,
32 mem,
33 ops::{Deref, DerefMut, Range},
34};
35use util::ResultExt;
36use uuid::Uuid;
37
38use super::{Reference, ViewMetadata};
39
40pub struct Window {
41 pub(crate) root_view: Option<AnyViewHandle>,
42 pub(crate) focused_view_id: Option<usize>,
43 pub(crate) parents: HashMap<usize, usize>,
44 pub(crate) is_active: bool,
45 pub(crate) is_fullscreen: bool,
46 pub(crate) invalidation: Option<WindowInvalidation>,
47 pub(crate) platform_window: Box<dyn platform::Window>,
48 pub(crate) rendered_views: HashMap<usize, Box<dyn AnyRootElement>>,
49 titlebar_height: f32,
50 appearance: Appearance,
51 cursor_regions: Vec<CursorRegion>,
52 mouse_regions: Vec<(MouseRegion, usize)>,
53 last_mouse_moved_event: Option<Event>,
54 pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
55 pub(crate) clicked_region_ids: HashSet<MouseRegionId>,
56 pub(crate) clicked_region: Option<(MouseRegionId, MouseButton)>,
57 mouse_position: Vector2F,
58 text_layout_cache: TextLayoutCache,
59}
60
61impl Window {
62 pub fn new<V, F>(
63 window_id: usize,
64 platform_window: Box<dyn platform::Window>,
65 cx: &mut AppContext,
66 build_view: F,
67 ) -> Self
68 where
69 F: FnOnce(&mut ViewContext<V>) -> V,
70 V: View,
71 {
72 let titlebar_height = platform_window.titlebar_height();
73 let appearance = platform_window.appearance();
74 let mut window = Self {
75 root_view: None,
76 focused_view_id: None,
77 parents: Default::default(),
78 is_active: false,
79 invalidation: None,
80 is_fullscreen: false,
81 platform_window,
82 rendered_views: Default::default(),
83 cursor_regions: Default::default(),
84 mouse_regions: Default::default(),
85 text_layout_cache: TextLayoutCache::new(cx.font_system.clone()),
86 last_mouse_moved_event: None,
87 hovered_region_ids: Default::default(),
88 clicked_region_ids: Default::default(),
89 clicked_region: None,
90 mouse_position: vec2f(0., 0.),
91 titlebar_height,
92 appearance,
93 };
94
95 let mut window_context = WindowContext::mutable(cx, &mut window, window_id);
96 let root_view = window_context.add_view(|cx| build_view(cx));
97 if let Some(invalidation) = window_context.window.invalidation.take() {
98 window_context.invalidate(invalidation, appearance);
99 }
100 window.focused_view_id = Some(root_view.id());
101 window.root_view = Some(root_view.into_any());
102 window
103 }
104
105 pub fn root_view(&self) -> &AnyViewHandle {
106 &self
107 .root_view
108 .as_ref()
109 .expect("root_view called during window construction")
110 }
111}
112
113pub struct WindowContext<'a> {
114 pub(crate) app_context: Reference<'a, AppContext>,
115 pub(crate) window: Reference<'a, Window>,
116 pub(crate) window_id: usize,
117 pub(crate) removed: bool,
118}
119
120impl Deref for WindowContext<'_> {
121 type Target = AppContext;
122
123 fn deref(&self) -> &Self::Target {
124 &self.app_context
125 }
126}
127
128impl DerefMut for WindowContext<'_> {
129 fn deref_mut(&mut self) -> &mut Self::Target {
130 &mut self.app_context
131 }
132}
133
134impl BorrowAppContext for WindowContext<'_> {
135 fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
136 self.app_context.read_with(f)
137 }
138
139 fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
140 self.app_context.update(f)
141 }
142}
143
144impl BorrowWindowContext for WindowContext<'_> {
145 fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
146 if self.window_id == window_id {
147 f(self)
148 } else {
149 panic!("read_with called with id of window that does not belong to this context")
150 }
151 }
152
153 fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
154 if self.window_id == window_id {
155 f(self)
156 } else {
157 panic!("update called with id of window that does not belong to this context")
158 }
159 }
160}
161
162impl<'a> WindowContext<'a> {
163 pub fn mutable(
164 app_context: &'a mut AppContext,
165 window: &'a mut Window,
166 window_id: usize,
167 ) -> Self {
168 Self {
169 app_context: Reference::Mutable(app_context),
170 window: Reference::Mutable(window),
171 window_id,
172 removed: false,
173 }
174 }
175
176 pub fn immutable(app_context: &'a AppContext, window: &'a Window, window_id: usize) -> Self {
177 Self {
178 app_context: Reference::Immutable(app_context),
179 window: Reference::Immutable(window),
180 window_id,
181 removed: false,
182 }
183 }
184
185 pub fn remove_window(&mut self) {
186 self.removed = true;
187 }
188
189 pub fn window_id(&self) -> usize {
190 self.window_id
191 }
192
193 pub fn app_context(&mut self) -> &mut AppContext {
194 &mut self.app_context
195 }
196
197 pub fn root_view(&self) -> &AnyViewHandle {
198 self.window.root_view()
199 }
200
201 pub fn window_size(&self) -> Vector2F {
202 self.window.platform_window.content_size()
203 }
204
205 pub fn text_layout_cache(&self) -> &TextLayoutCache {
206 &self.window.text_layout_cache
207 }
208
209 pub(crate) fn update_any_view<F, T>(&mut self, view_id: usize, f: F) -> Option<T>
210 where
211 F: FnOnce(&mut dyn AnyView, &mut Self) -> T,
212 {
213 let window_id = self.window_id;
214 let mut view = self.views.remove(&(window_id, view_id))?;
215 let result = f(view.as_mut(), self);
216 self.views.insert((window_id, view_id), view);
217 Some(result)
218 }
219
220 pub(crate) fn update_view<T, S>(
221 &mut self,
222 handle: &ViewHandle<T>,
223 update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
224 ) -> S
225 where
226 T: View,
227 {
228 self.update_any_view(handle.view_id, |view, cx| {
229 let mut cx = ViewContext::mutable(cx, handle.view_id);
230 update(
231 view.as_any_mut()
232 .downcast_mut()
233 .expect("downcast is type safe"),
234 &mut cx,
235 )
236 })
237 .expect("view is already on the stack")
238 }
239
240 pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut WindowContext)) {
241 let window_id = self.window_id;
242 self.app_context.defer(move |cx| {
243 cx.update_window(window_id, |cx| callback(cx));
244 })
245 }
246
247 pub fn update_global<T, F, U>(&mut self, update: F) -> U
248 where
249 T: 'static,
250 F: FnOnce(&mut T, &mut Self) -> U,
251 {
252 AppContext::update_global_internal(self, |global, cx| update(global, cx))
253 }
254
255 pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
256 where
257 T: 'static + Default,
258 F: FnOnce(&mut T, &mut Self) -> U,
259 {
260 AppContext::update_default_global_internal(self, |global, cx| update(global, cx))
261 }
262
263 pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
264 where
265 E: Entity,
266 E::Event: 'static,
267 H: Handle<E>,
268 F: 'static + FnMut(H, &E::Event, &mut WindowContext),
269 {
270 self.subscribe_internal(handle, move |emitter, event, cx| {
271 callback(emitter, event, cx);
272 true
273 })
274 }
275
276 pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
277 where
278 E: Entity,
279 E::Event: 'static,
280 H: Handle<E>,
281 F: 'static + FnMut(H, &E::Event, &mut WindowContext) -> bool,
282 {
283 let window_id = self.window_id;
284 self.app_context
285 .subscribe_internal(handle, move |emitter, event, cx| {
286 cx.update_window(window_id, |cx| callback(emitter, event, cx))
287 .unwrap_or(false)
288 })
289 }
290
291 pub(crate) fn observe_window_activation<F>(&mut self, callback: F) -> Subscription
292 where
293 F: 'static + FnMut(bool, &mut WindowContext) -> bool,
294 {
295 let window_id = self.window_id;
296 let subscription_id = post_inc(&mut self.next_subscription_id);
297 self.pending_effects
298 .push_back(Effect::WindowActivationObservation {
299 window_id,
300 subscription_id,
301 callback: Box::new(callback),
302 });
303 Subscription::WindowActivationObservation(
304 self.window_activation_observations
305 .subscribe(window_id, subscription_id),
306 )
307 }
308
309 pub(crate) fn observe_fullscreen<F>(&mut self, callback: F) -> Subscription
310 where
311 F: 'static + FnMut(bool, &mut WindowContext) -> bool,
312 {
313 let window_id = self.window_id;
314 let subscription_id = post_inc(&mut self.next_subscription_id);
315 self.pending_effects
316 .push_back(Effect::WindowFullscreenObservation {
317 window_id,
318 subscription_id,
319 callback: Box::new(callback),
320 });
321 Subscription::WindowActivationObservation(
322 self.window_activation_observations
323 .subscribe(window_id, subscription_id),
324 )
325 }
326
327 pub(crate) fn observe_window_bounds<F>(&mut self, callback: F) -> Subscription
328 where
329 F: 'static + FnMut(WindowBounds, Uuid, &mut WindowContext) -> bool,
330 {
331 let window_id = self.window_id;
332 let subscription_id = post_inc(&mut self.next_subscription_id);
333 self.pending_effects
334 .push_back(Effect::WindowBoundsObservation {
335 window_id,
336 subscription_id,
337 callback: Box::new(callback),
338 });
339 Subscription::WindowBoundsObservation(
340 self.window_bounds_observations
341 .subscribe(window_id, subscription_id),
342 )
343 }
344
345 pub fn observe_keystrokes<F>(&mut self, callback: F) -> Subscription
346 where
347 F: 'static
348 + FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut WindowContext) -> bool,
349 {
350 let window_id = self.window_id;
351 let subscription_id = post_inc(&mut self.next_subscription_id);
352 self.keystroke_observations
353 .add_callback(window_id, subscription_id, Box::new(callback));
354 Subscription::KeystrokeObservation(
355 self.keystroke_observations
356 .subscribe(window_id, subscription_id),
357 )
358 }
359
360 pub(crate) fn available_actions(
361 &self,
362 view_id: usize,
363 ) -> Vec<(&'static str, Box<dyn Action>, SmallVec<[Binding; 1]>)> {
364 let window_id = self.window_id;
365 let mut contexts = Vec::new();
366 let mut handler_depths_by_action_id = HashMap::<TypeId, usize>::default();
367 for (depth, view_id) in self.ancestors(view_id).enumerate() {
368 if let Some(view_metadata) = self.views_metadata.get(&(window_id, view_id)) {
369 contexts.push(view_metadata.keymap_context.clone());
370 if let Some(actions) = self.actions.get(&view_metadata.type_id) {
371 handler_depths_by_action_id
372 .extend(actions.keys().copied().map(|action_id| (action_id, depth)));
373 }
374 } else {
375 log::error!(
376 "view {} not found when computing available actions",
377 view_id
378 );
379 }
380 }
381
382 handler_depths_by_action_id.extend(
383 self.global_actions
384 .keys()
385 .copied()
386 .map(|action_id| (action_id, contexts.len())),
387 );
388
389 self.action_deserializers
390 .iter()
391 .filter_map(move |(name, (action_id, deserialize))| {
392 if let Some(action_depth) = handler_depths_by_action_id.get(action_id).copied() {
393 let action = deserialize(serde_json::Value::Object(Default::default())).ok()?;
394 let bindings = self
395 .keystroke_matcher
396 .bindings_for_action(*action_id)
397 .filter(|b| {
398 action.eq(b.action())
399 && (0..=action_depth)
400 .any(|depth| b.match_context(&contexts[depth..]))
401 })
402 .cloned()
403 .collect();
404 Some((*name, action, bindings))
405 } else {
406 None
407 }
408 })
409 .collect()
410 }
411
412 pub(crate) fn dispatch_keystroke(&mut self, keystroke: &Keystroke) -> bool {
413 let window_id = self.window_id;
414 if let Some(focused_view_id) = self.focused_view_id() {
415 let dispatch_path = self
416 .ancestors(focused_view_id)
417 .filter_map(|view_id| {
418 self.views_metadata
419 .get(&(window_id, view_id))
420 .map(|view| (view_id, view.keymap_context.clone()))
421 })
422 .collect();
423
424 let match_result = self
425 .keystroke_matcher
426 .push_keystroke(keystroke.clone(), dispatch_path);
427 let mut handled_by = None;
428
429 let keystroke_handled = match &match_result {
430 MatchResult::None => false,
431 MatchResult::Pending => true,
432 MatchResult::Matches(matches) => {
433 for (view_id, action) in matches {
434 if self.dispatch_action(Some(*view_id), action.as_ref()) {
435 self.keystroke_matcher.clear_pending();
436 handled_by = Some(action.boxed_clone());
437 break;
438 }
439 }
440 handled_by.is_some()
441 }
442 };
443
444 self.keystroke(
445 window_id,
446 keystroke.clone(),
447 handled_by,
448 match_result.clone(),
449 );
450 keystroke_handled
451 } else {
452 self.keystroke(window_id, keystroke.clone(), None, MatchResult::None);
453 false
454 }
455 }
456
457 pub(crate) fn dispatch_event(&mut self, event: Event, event_reused: bool) -> bool {
458 let mut mouse_events = SmallVec::<[_; 2]>::new();
459 let mut notified_views: HashSet<usize> = Default::default();
460 let window_id = self.window_id;
461
462 // 1. Handle platform event. Keyboard events get dispatched immediately, while mouse events
463 // get mapped into the mouse-specific MouseEvent type.
464 // -> These are usually small: [Mouse Down] or [Mouse up, Click] or [Mouse Moved, Mouse Dragged?]
465 // -> Also updates mouse-related state
466 match &event {
467 Event::KeyDown(e) => return self.dispatch_key_down(e),
468
469 Event::KeyUp(e) => return self.dispatch_key_up(e),
470
471 Event::ModifiersChanged(e) => return self.dispatch_modifiers_changed(e),
472
473 Event::MouseDown(e) => {
474 // Click events are weird because they can be fired after a drag event.
475 // MDN says that browsers handle this by starting from 'the most
476 // specific ancestor element that contained both [positions]'
477 // So we need to store the overlapping regions on mouse down.
478
479 // If there is already region being clicked, don't replace it.
480 if self.window.clicked_region.is_none() {
481 self.window.clicked_region_ids = self
482 .window
483 .mouse_regions
484 .iter()
485 .filter_map(|(region, _)| {
486 if region.bounds.contains_point(e.position) {
487 Some(region.id())
488 } else {
489 None
490 }
491 })
492 .collect();
493
494 let mut highest_z_index = 0;
495 let mut clicked_region_id = None;
496 for (region, z_index) in self.window.mouse_regions.iter() {
497 if region.bounds.contains_point(e.position) && *z_index >= highest_z_index {
498 highest_z_index = *z_index;
499 clicked_region_id = Some(region.id());
500 }
501 }
502
503 self.window.clicked_region =
504 clicked_region_id.map(|region_id| (region_id, e.button));
505 }
506
507 mouse_events.push(MouseEvent::Down(MouseDown {
508 region: Default::default(),
509 platform_event: e.clone(),
510 }));
511 mouse_events.push(MouseEvent::DownOut(MouseDownOut {
512 region: Default::default(),
513 platform_event: e.clone(),
514 }));
515 }
516
517 Event::MouseUp(e) => {
518 // NOTE: The order of event pushes is important! MouseUp events MUST be fired
519 // before click events, and so the MouseUp events need to be pushed before
520 // MouseClick events.
521 mouse_events.push(MouseEvent::Up(MouseUp {
522 region: Default::default(),
523 platform_event: e.clone(),
524 }));
525 mouse_events.push(MouseEvent::UpOut(MouseUpOut {
526 region: Default::default(),
527 platform_event: e.clone(),
528 }));
529 mouse_events.push(MouseEvent::Click(MouseClick {
530 region: Default::default(),
531 platform_event: e.clone(),
532 }));
533 mouse_events.push(MouseEvent::ClickOut(MouseClickOut {
534 region: Default::default(),
535 platform_event: e.clone(),
536 }));
537 }
538
539 Event::MouseMoved(
540 e @ MouseMovedEvent {
541 position,
542 pressed_button,
543 ..
544 },
545 ) => {
546 let mut style_to_assign = CursorStyle::Arrow;
547 for region in self.window.cursor_regions.iter().rev() {
548 if region.bounds.contains_point(*position) {
549 style_to_assign = region.style;
550 break;
551 }
552 }
553
554 if self
555 .window
556 .platform_window
557 .is_topmost_for_position(*position)
558 {
559 self.platform().set_cursor_style(style_to_assign);
560 }
561
562 if !event_reused {
563 if pressed_button.is_some() {
564 mouse_events.push(MouseEvent::Drag(MouseDrag {
565 region: Default::default(),
566 prev_mouse_position: self.window.mouse_position,
567 platform_event: e.clone(),
568 }));
569 } else if let Some((_, clicked_button)) = self.window.clicked_region {
570 // Mouse up event happened outside the current window. Simulate mouse up button event
571 let button_event = e.to_button_event(clicked_button);
572 mouse_events.push(MouseEvent::Up(MouseUp {
573 region: Default::default(),
574 platform_event: button_event.clone(),
575 }));
576 mouse_events.push(MouseEvent::UpOut(MouseUpOut {
577 region: Default::default(),
578 platform_event: button_event.clone(),
579 }));
580 mouse_events.push(MouseEvent::Click(MouseClick {
581 region: Default::default(),
582 platform_event: button_event.clone(),
583 }));
584 }
585
586 mouse_events.push(MouseEvent::Move(MouseMove {
587 region: Default::default(),
588 platform_event: e.clone(),
589 }));
590 }
591
592 mouse_events.push(MouseEvent::Hover(MouseHover {
593 region: Default::default(),
594 platform_event: e.clone(),
595 started: false,
596 }));
597 mouse_events.push(MouseEvent::MoveOut(MouseMoveOut {
598 region: Default::default(),
599 }));
600
601 self.window.last_mouse_moved_event = Some(event.clone());
602 }
603
604 Event::MouseExited(event) => {
605 // When the platform sends a MouseExited event, synthesize
606 // a MouseMoved event whose position is outside the window's
607 // bounds so that hover and cursor state can be updated.
608 return self.dispatch_event(
609 Event::MouseMoved(MouseMovedEvent {
610 position: event.position,
611 pressed_button: event.pressed_button,
612 modifiers: event.modifiers,
613 }),
614 event_reused,
615 );
616 }
617
618 Event::ScrollWheel(e) => mouse_events.push(MouseEvent::ScrollWheel(MouseScrollWheel {
619 region: Default::default(),
620 platform_event: e.clone(),
621 })),
622 }
623
624 if let Some(position) = event.position() {
625 self.window.mouse_position = position;
626 }
627
628 // 2. Dispatch mouse events on regions
629 let mut any_event_handled = false;
630 for mut mouse_event in mouse_events {
631 let mut valid_regions = Vec::new();
632
633 // GPUI elements are arranged by z_index but sibling elements can register overlapping
634 // mouse regions. As such, hover events are only fired on overlapping elements which
635 // are at the same z-index as the topmost element which overlaps with the mouse.
636 match &mouse_event {
637 MouseEvent::Hover(_) => {
638 let mut highest_z_index = None;
639 let mouse_position = self.window.mouse_position.clone();
640 let window = &mut *self.window;
641 for (region, z_index) in window.mouse_regions.iter().rev() {
642 // Allow mouse regions to appear transparent to hovers
643 if !region.hoverable {
644 continue;
645 }
646
647 let contains_mouse = region.bounds.contains_point(mouse_position);
648
649 if contains_mouse && highest_z_index.is_none() {
650 highest_z_index = Some(z_index);
651 }
652
653 // This unwrap relies on short circuiting boolean expressions
654 // The right side of the && is only executed when contains_mouse
655 // is true, and we know above that when contains_mouse is true
656 // highest_z_index is set.
657 if contains_mouse && z_index == highest_z_index.unwrap() {
658 //Ensure that hover entrance events aren't sent twice
659 if window.hovered_region_ids.insert(region.id()) {
660 valid_regions.push(region.clone());
661 if region.notify_on_hover {
662 notified_views.insert(region.id().view_id());
663 }
664 }
665 } else {
666 // Ensure that hover exit events aren't sent twice
667 if window.hovered_region_ids.remove(®ion.id()) {
668 valid_regions.push(region.clone());
669 if region.notify_on_hover {
670 notified_views.insert(region.id().view_id());
671 }
672 }
673 }
674 }
675 }
676
677 MouseEvent::Down(_) | MouseEvent::Up(_) => {
678 for (region, _) in self.window.mouse_regions.iter().rev() {
679 if region.bounds.contains_point(self.window.mouse_position) {
680 valid_regions.push(region.clone());
681 if region.notify_on_click {
682 notified_views.insert(region.id().view_id());
683 }
684 }
685 }
686 }
687
688 MouseEvent::Click(e) => {
689 // Only raise click events if the released button is the same as the one stored
690 if self
691 .window
692 .clicked_region
693 .map(|(_, clicked_button)| clicked_button == e.button)
694 .unwrap_or(false)
695 {
696 // Clear clicked regions and clicked button
697 let clicked_region_ids = std::mem::replace(
698 &mut self.window.clicked_region_ids,
699 Default::default(),
700 );
701 self.window.clicked_region = None;
702
703 // Find regions which still overlap with the mouse since the last MouseDown happened
704 for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
705 if clicked_region_ids.contains(&mouse_region.id()) {
706 if mouse_region
707 .bounds
708 .contains_point(self.window.mouse_position)
709 {
710 valid_regions.push(mouse_region.clone());
711 }
712 }
713 }
714 }
715 }
716
717 MouseEvent::Drag(_) => {
718 for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
719 if self.window.clicked_region_ids.contains(&mouse_region.id()) {
720 valid_regions.push(mouse_region.clone());
721 }
722 }
723 }
724
725 MouseEvent::MoveOut(_)
726 | MouseEvent::UpOut(_)
727 | MouseEvent::DownOut(_)
728 | MouseEvent::ClickOut(_) => {
729 for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
730 // NOT contains
731 if !mouse_region
732 .bounds
733 .contains_point(self.window.mouse_position)
734 {
735 valid_regions.push(mouse_region.clone());
736 }
737 }
738 }
739
740 _ => {
741 for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
742 // Contains
743 if mouse_region
744 .bounds
745 .contains_point(self.window.mouse_position)
746 {
747 valid_regions.push(mouse_region.clone());
748 }
749 }
750 }
751 }
752
753 //3. Fire region events
754 let hovered_region_ids = self.window.hovered_region_ids.clone();
755 for valid_region in valid_regions.into_iter() {
756 let mut handled = false;
757 mouse_event.set_region(valid_region.bounds);
758 if let MouseEvent::Hover(e) = &mut mouse_event {
759 e.started = hovered_region_ids.contains(&valid_region.id())
760 }
761 // Handle Down events if the MouseRegion has a Click or Drag handler. This makes the api more intuitive as you would
762 // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
763 // This behavior can be overridden by adding a Down handler
764 if let MouseEvent::Down(e) = &mouse_event {
765 let has_click = valid_region
766 .handlers
767 .contains(MouseEvent::click_disc(), Some(e.button));
768 let has_drag = valid_region
769 .handlers
770 .contains(MouseEvent::drag_disc(), Some(e.button));
771 let has_down = valid_region
772 .handlers
773 .contains(MouseEvent::down_disc(), Some(e.button));
774 if !has_down && (has_click || has_drag) {
775 handled = true;
776 }
777 }
778
779 // `event_consumed` should only be true if there are any handlers for this event.
780 let mut event_consumed = handled;
781 if let Some(callbacks) = valid_region.handlers.get(&mouse_event.handler_key()) {
782 for callback in callbacks {
783 handled = true;
784 let view_id = valid_region.id().view_id();
785 self.update_any_view(view_id, |view, cx| {
786 handled = callback(mouse_event.clone(), view.as_any_mut(), cx, view_id);
787 });
788 event_consumed |= handled;
789 any_event_handled |= handled;
790 }
791 }
792
793 any_event_handled |= handled;
794
795 // For bubbling events, if the event was handled, don't continue dispatching.
796 // This only makes sense for local events which return false from is_capturable.
797 if event_consumed && mouse_event.is_capturable() {
798 break;
799 }
800 }
801 }
802
803 for view_id in notified_views {
804 self.notify_view(window_id, view_id);
805 }
806
807 any_event_handled
808 }
809
810 pub(crate) fn dispatch_key_down(&mut self, event: &KeyDownEvent) -> bool {
811 let window_id = self.window_id;
812 if let Some(focused_view_id) = self.window.focused_view_id {
813 for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
814 if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
815 let handled = view.key_down(event, self, view_id);
816 self.views.insert((window_id, view_id), view);
817 if handled {
818 return true;
819 }
820 } else {
821 log::error!("view {} does not exist", view_id)
822 }
823 }
824 }
825
826 false
827 }
828
829 pub(crate) fn dispatch_key_up(&mut self, event: &KeyUpEvent) -> bool {
830 let window_id = self.window_id;
831 if let Some(focused_view_id) = self.window.focused_view_id {
832 for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
833 if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
834 let handled = view.key_up(event, self, view_id);
835 self.views.insert((window_id, view_id), view);
836 if handled {
837 return true;
838 }
839 } else {
840 log::error!("view {} does not exist", view_id)
841 }
842 }
843 }
844
845 false
846 }
847
848 pub(crate) fn dispatch_modifiers_changed(&mut self, event: &ModifiersChangedEvent) -> bool {
849 let window_id = self.window_id;
850 if let Some(focused_view_id) = self.window.focused_view_id {
851 for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
852 if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
853 let handled = view.modifiers_changed(event, self, view_id);
854 self.views.insert((window_id, view_id), view);
855 if handled {
856 return true;
857 }
858 } else {
859 log::error!("view {} does not exist", view_id)
860 }
861 }
862 }
863
864 false
865 }
866
867 pub fn invalidate(&mut self, mut invalidation: WindowInvalidation, appearance: Appearance) {
868 self.start_frame();
869 self.window.appearance = appearance;
870 for view_id in &invalidation.removed {
871 invalidation.updated.remove(view_id);
872 self.window.rendered_views.remove(view_id);
873 }
874 for view_id in &invalidation.updated {
875 let titlebar_height = self.window.titlebar_height;
876 let element = self
877 .render_view(RenderParams {
878 view_id: *view_id,
879 titlebar_height,
880 refreshing: false,
881 appearance,
882 })
883 .unwrap();
884 self.window.rendered_views.insert(*view_id, element);
885 }
886 }
887
888 pub fn render_view(&mut self, params: RenderParams) -> Result<Box<dyn AnyRootElement>> {
889 let window_id = self.window_id;
890 let view_id = params.view_id;
891 let mut view = self
892 .views
893 .remove(&(window_id, view_id))
894 .ok_or_else(|| anyhow!("view not found"))?;
895 let element = view.render(self, view_id);
896 self.views.insert((window_id, view_id), view);
897 Ok(element)
898 }
899
900 pub(crate) fn layout(&mut self, refreshing: bool) -> Result<HashMap<usize, usize>> {
901 let window_size = self.window.platform_window.content_size();
902 let root_view_id = self.window.root_view().id();
903 let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
904 let mut new_parents = HashMap::default();
905 let mut views_to_notify_if_ancestors_change = HashMap::default();
906 rendered_root.layout(
907 SizeConstraint::strict(window_size),
908 &mut new_parents,
909 &mut views_to_notify_if_ancestors_change,
910 refreshing,
911 self,
912 )?;
913
914 for (view_id, view_ids_to_notify) in views_to_notify_if_ancestors_change {
915 let mut current_view_id = view_id;
916 loop {
917 let old_parent_id = self.window.parents.get(¤t_view_id);
918 let new_parent_id = new_parents.get(¤t_view_id);
919 if old_parent_id.is_none() && new_parent_id.is_none() {
920 break;
921 } else if old_parent_id == new_parent_id {
922 current_view_id = *old_parent_id.unwrap();
923 } else {
924 let window_id = self.window_id;
925 for view_id_to_notify in view_ids_to_notify {
926 self.notify_view(window_id, view_id_to_notify);
927 }
928 break;
929 }
930 }
931 }
932
933 let old_parents = mem::replace(&mut self.window.parents, new_parents);
934 self.window
935 .rendered_views
936 .insert(root_view_id, rendered_root);
937 Ok(old_parents)
938 }
939
940 pub(crate) fn paint(&mut self) -> Result<Scene> {
941 let window_size = self.window.platform_window.content_size();
942 let scale_factor = self.window.platform_window.scale_factor();
943
944 let root_view_id = self.window.root_view().id();
945 let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
946
947 let mut scene_builder = SceneBuilder::new(scale_factor);
948 rendered_root.paint(
949 &mut scene_builder,
950 Vector2F::zero(),
951 RectF::from_points(Vector2F::zero(), window_size),
952 self,
953 )?;
954 self.window
955 .rendered_views
956 .insert(root_view_id, rendered_root);
957
958 self.window.text_layout_cache.finish_frame();
959 let scene = scene_builder.build();
960 self.window.cursor_regions = scene.cursor_regions();
961 self.window.mouse_regions = scene.mouse_regions();
962
963 if self.window_is_active() {
964 if let Some(event) = self.window.last_mouse_moved_event.clone() {
965 self.dispatch_event(event, true);
966 }
967 }
968
969 Ok(scene)
970 }
971
972 pub fn rect_for_text_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
973 let focused_view_id = self.window.focused_view_id?;
974 self.window
975 .rendered_views
976 .get(&focused_view_id)?
977 .rect_for_text_range(range_utf16, self)
978 .log_err()
979 .flatten()
980 }
981
982 pub fn set_window_title(&mut self, title: &str) {
983 self.window.platform_window.set_title(title);
984 }
985
986 pub fn set_window_edited(&mut self, edited: bool) {
987 self.window.platform_window.set_edited(edited);
988 }
989
990 pub fn is_topmost_window_for_position(&self, position: Vector2F) -> bool {
991 self.window
992 .platform_window
993 .is_topmost_for_position(position)
994 }
995
996 pub fn activate_window(&self) {
997 self.window.platform_window.activate();
998 }
999
1000 pub fn window_is_active(&self) -> bool {
1001 self.window.is_active
1002 }
1003
1004 pub fn window_is_fullscreen(&self) -> bool {
1005 self.window.is_fullscreen
1006 }
1007
1008 pub(crate) fn dispatch_action(&mut self, view_id: Option<usize>, action: &dyn Action) -> bool {
1009 if let Some(view_id) = view_id {
1010 self.halt_action_dispatch = false;
1011 self.visit_dispatch_path(view_id, |view_id, capture_phase, cx| {
1012 cx.update_any_view(view_id, |view, cx| {
1013 let type_id = view.as_any().type_id();
1014 if let Some((name, mut handlers)) = cx
1015 .actions_mut(capture_phase)
1016 .get_mut(&type_id)
1017 .and_then(|h| h.remove_entry(&action.id()))
1018 {
1019 for handler in handlers.iter_mut().rev() {
1020 cx.halt_action_dispatch = true;
1021 handler(view, action, cx, view_id);
1022 if cx.halt_action_dispatch {
1023 break;
1024 }
1025 }
1026 cx.actions_mut(capture_phase)
1027 .get_mut(&type_id)
1028 .unwrap()
1029 .insert(name, handlers);
1030 }
1031 });
1032
1033 !cx.halt_action_dispatch
1034 });
1035 }
1036
1037 if !self.halt_action_dispatch {
1038 self.halt_action_dispatch = self.dispatch_global_action_any(action);
1039 }
1040
1041 self.pending_effects
1042 .push_back(Effect::ActionDispatchNotification {
1043 action_id: action.id(),
1044 });
1045 self.halt_action_dispatch
1046 }
1047
1048 /// Returns an iterator over all of the view ids from the passed view up to the root of the window
1049 /// Includes the passed view itself
1050 pub(crate) fn ancestors(&self, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
1051 std::iter::once(view_id)
1052 .into_iter()
1053 .chain(std::iter::from_fn(move || {
1054 if let Some(parent_id) = self.window.parents.get(&view_id) {
1055 view_id = *parent_id;
1056 Some(view_id)
1057 } else {
1058 None
1059 }
1060 }))
1061 }
1062
1063 // Traverses the parent tree. Walks down the tree toward the passed
1064 // view calling visit with true. Then walks back up the tree calling visit with false.
1065 // If `visit` returns false this function will immediately return.
1066 fn visit_dispatch_path(
1067 &mut self,
1068 view_id: usize,
1069 mut visit: impl FnMut(usize, bool, &mut WindowContext) -> bool,
1070 ) {
1071 // List of view ids from the leaf to the root of the window
1072 let path = self.ancestors(view_id).collect::<Vec<_>>();
1073
1074 // Walk down from the root to the leaf calling visit with capture_phase = true
1075 for view_id in path.iter().rev() {
1076 if !visit(*view_id, true, self) {
1077 return;
1078 }
1079 }
1080
1081 // Walk up from the leaf to the root calling visit with capture_phase = false
1082 for view_id in path.iter() {
1083 if !visit(*view_id, false, self) {
1084 return;
1085 }
1086 }
1087 }
1088
1089 pub fn focused_view_id(&self) -> Option<usize> {
1090 self.window.focused_view_id
1091 }
1092
1093 pub fn focus(&mut self, view_id: Option<usize>) {
1094 self.app_context.focus(self.window_id, view_id);
1095 }
1096
1097 pub fn window_bounds(&self) -> WindowBounds {
1098 self.window.platform_window.bounds()
1099 }
1100
1101 pub fn window_appearance(&self) -> Appearance {
1102 self.window.appearance
1103 }
1104
1105 pub fn window_display_uuid(&self) -> Option<Uuid> {
1106 self.window.platform_window.screen().display_uuid()
1107 }
1108
1109 pub fn show_character_palette(&self) {
1110 self.window.platform_window.show_character_palette();
1111 }
1112
1113 pub fn minimize_window(&self) {
1114 self.window.platform_window.minimize();
1115 }
1116
1117 pub fn zoom_window(&self) {
1118 self.window.platform_window.zoom();
1119 }
1120
1121 pub fn toggle_full_screen(&self) {
1122 self.window.platform_window.toggle_full_screen();
1123 }
1124
1125 pub fn prompt(
1126 &self,
1127 level: PromptLevel,
1128 msg: &str,
1129 answers: &[&str],
1130 ) -> oneshot::Receiver<usize> {
1131 self.window.platform_window.prompt(level, msg, answers)
1132 }
1133
1134 pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
1135 where
1136 V: View,
1137 F: FnOnce(&mut ViewContext<V>) -> V,
1138 {
1139 let root_view = self.add_view(|cx| build_root_view(cx));
1140 self.window.root_view = Some(root_view.clone().into_any());
1141 self.window.focused_view_id = Some(root_view.id());
1142 root_view
1143 }
1144
1145 pub fn add_view<T, F>(&mut self, build_view: F) -> ViewHandle<T>
1146 where
1147 T: View,
1148 F: FnOnce(&mut ViewContext<T>) -> T,
1149 {
1150 self.add_option_view(|cx| Some(build_view(cx))).unwrap()
1151 }
1152
1153 pub fn add_option_view<T, F>(&mut self, build_view: F) -> Option<ViewHandle<T>>
1154 where
1155 T: View,
1156 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1157 {
1158 let window_id = self.window_id;
1159 let view_id = post_inc(&mut self.next_entity_id);
1160 let mut cx = ViewContext::mutable(self, view_id);
1161 let handle = if let Some(view) = build_view(&mut cx) {
1162 let mut keymap_context = KeymapContext::default();
1163 view.update_keymap_context(&mut keymap_context, cx.app_context());
1164 self.views_metadata.insert(
1165 (window_id, view_id),
1166 ViewMetadata {
1167 type_id: TypeId::of::<T>(),
1168 keymap_context,
1169 },
1170 );
1171 self.views.insert((window_id, view_id), Box::new(view));
1172 self.window
1173 .invalidation
1174 .get_or_insert_with(Default::default)
1175 .updated
1176 .insert(view_id);
1177 Some(ViewHandle::new(window_id, view_id, &self.ref_counts))
1178 } else {
1179 None
1180 };
1181 handle
1182 }
1183}
1184
1185pub struct RenderParams {
1186 pub view_id: usize,
1187 pub titlebar_height: f32,
1188 pub refreshing: bool,
1189 pub appearance: Appearance,
1190}
1191
1192#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1193pub enum Axis {
1194 #[default]
1195 Horizontal,
1196 Vertical,
1197}
1198
1199impl Axis {
1200 pub fn invert(self) -> Self {
1201 match self {
1202 Self::Horizontal => Self::Vertical,
1203 Self::Vertical => Self::Horizontal,
1204 }
1205 }
1206
1207 pub fn component(&self, point: Vector2F) -> f32 {
1208 match self {
1209 Self::Horizontal => point.x(),
1210 Self::Vertical => point.y(),
1211 }
1212 }
1213}
1214
1215impl ToJson for Axis {
1216 fn to_json(&self) -> serde_json::Value {
1217 match self {
1218 Axis::Horizontal => json!("horizontal"),
1219 Axis::Vertical => json!("vertical"),
1220 }
1221 }
1222}
1223
1224impl StaticColumnCount for Axis {}
1225impl Bind for Axis {
1226 fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
1227 match self {
1228 Axis::Horizontal => "Horizontal",
1229 Axis::Vertical => "Vertical",
1230 }
1231 .bind(statement, start_index)
1232 }
1233}
1234
1235impl Column for Axis {
1236 fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
1237 String::column(statement, start_index).and_then(|(axis_text, next_index)| {
1238 Ok((
1239 match axis_text.as_str() {
1240 "Horizontal" => Axis::Horizontal,
1241 "Vertical" => Axis::Vertical,
1242 _ => bail!("Stored serialized item kind is incorrect"),
1243 },
1244 next_index,
1245 ))
1246 })
1247 }
1248}
1249
1250pub trait Vector2FExt {
1251 fn along(self, axis: Axis) -> f32;
1252}
1253
1254impl Vector2FExt for Vector2F {
1255 fn along(self, axis: Axis) -> f32 {
1256 match axis {
1257 Axis::Horizontal => self.x(),
1258 Axis::Vertical => self.y(),
1259 }
1260 }
1261}
1262
1263#[derive(Copy, Clone, Debug)]
1264pub struct SizeConstraint {
1265 pub min: Vector2F,
1266 pub max: Vector2F,
1267}
1268
1269impl SizeConstraint {
1270 pub fn new(min: Vector2F, max: Vector2F) -> Self {
1271 Self { min, max }
1272 }
1273
1274 pub fn strict(size: Vector2F) -> Self {
1275 Self {
1276 min: size,
1277 max: size,
1278 }
1279 }
1280
1281 pub fn strict_along(axis: Axis, max: f32) -> Self {
1282 match axis {
1283 Axis::Horizontal => Self {
1284 min: vec2f(max, 0.0),
1285 max: vec2f(max, f32::INFINITY),
1286 },
1287 Axis::Vertical => Self {
1288 min: vec2f(0.0, max),
1289 max: vec2f(f32::INFINITY, max),
1290 },
1291 }
1292 }
1293
1294 pub fn max_along(&self, axis: Axis) -> f32 {
1295 match axis {
1296 Axis::Horizontal => self.max.x(),
1297 Axis::Vertical => self.max.y(),
1298 }
1299 }
1300
1301 pub fn min_along(&self, axis: Axis) -> f32 {
1302 match axis {
1303 Axis::Horizontal => self.min.x(),
1304 Axis::Vertical => self.min.y(),
1305 }
1306 }
1307
1308 pub fn constrain(&self, size: Vector2F) -> Vector2F {
1309 vec2f(
1310 size.x().min(self.max.x()).max(self.min.x()),
1311 size.y().min(self.max.y()).max(self.min.y()),
1312 )
1313 }
1314}
1315
1316impl Default for SizeConstraint {
1317 fn default() -> Self {
1318 SizeConstraint {
1319 min: Vector2F::zero(),
1320 max: Vector2F::splat(f32::INFINITY),
1321 }
1322 }
1323}
1324
1325impl ToJson for SizeConstraint {
1326 fn to_json(&self) -> serde_json::Value {
1327 json!({
1328 "min": self.min.to_json(),
1329 "max": self.max.to_json(),
1330 })
1331 }
1332}
1333
1334pub struct ChildView {
1335 view_id: usize,
1336 view_name: &'static str,
1337}
1338
1339impl ChildView {
1340 pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
1341 let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
1342 Self {
1343 view_id: view.id(),
1344 view_name,
1345 }
1346 }
1347}
1348
1349impl<V: View> Element<V> for ChildView {
1350 type LayoutState = ();
1351 type PaintState = ();
1352
1353 fn layout(
1354 &mut self,
1355 constraint: SizeConstraint,
1356 _: &mut V,
1357 cx: &mut LayoutContext<V>,
1358 ) -> (Vector2F, Self::LayoutState) {
1359 if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1360 cx.new_parents.insert(self.view_id, cx.view_id());
1361 let size = rendered_view
1362 .layout(
1363 constraint,
1364 cx.new_parents,
1365 cx.views_to_notify_if_ancestors_change,
1366 cx.refreshing,
1367 cx.view_context,
1368 )
1369 .log_err()
1370 .unwrap_or(Vector2F::zero());
1371 cx.window.rendered_views.insert(self.view_id, rendered_view);
1372 (size, ())
1373 } else {
1374 log::error!(
1375 "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1376 self.view_id,
1377 self.view_name
1378 );
1379 (Vector2F::zero(), ())
1380 }
1381 }
1382
1383 fn paint(
1384 &mut self,
1385 scene: &mut SceneBuilder,
1386 bounds: RectF,
1387 visible_bounds: RectF,
1388 _: &mut Self::LayoutState,
1389 _: &mut V,
1390 cx: &mut ViewContext<V>,
1391 ) {
1392 if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1393 rendered_view
1394 .paint(scene, bounds.origin(), visible_bounds, cx)
1395 .log_err();
1396 cx.window.rendered_views.insert(self.view_id, rendered_view);
1397 } else {
1398 log::error!(
1399 "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1400 self.view_id,
1401 self.view_name
1402 );
1403 }
1404 }
1405
1406 fn rect_for_text_range(
1407 &self,
1408 range_utf16: Range<usize>,
1409 _: RectF,
1410 _: RectF,
1411 _: &Self::LayoutState,
1412 _: &Self::PaintState,
1413 _: &V,
1414 cx: &ViewContext<V>,
1415 ) -> Option<RectF> {
1416 if let Some(rendered_view) = cx.window.rendered_views.get(&self.view_id) {
1417 rendered_view
1418 .rect_for_text_range(range_utf16, &cx.window_context)
1419 .log_err()
1420 .flatten()
1421 } else {
1422 log::error!(
1423 "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1424 self.view_id,
1425 self.view_name
1426 );
1427 None
1428 }
1429 }
1430
1431 fn debug(
1432 &self,
1433 bounds: RectF,
1434 _: &Self::LayoutState,
1435 _: &Self::PaintState,
1436 _: &V,
1437 cx: &ViewContext<V>,
1438 ) -> serde_json::Value {
1439 json!({
1440 "type": "ChildView",
1441 "bounds": bounds.to_json(),
1442 "child": if let Some(element) = cx.window.rendered_views.get(&self.view_id) {
1443 element.debug(&cx.window_context).log_err().unwrap_or_else(|| json!(null))
1444 } else {
1445 json!(null)
1446 }
1447 })
1448 }
1449}