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