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