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