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