1use crate::{
2 elements::AnyRootElement,
3 geometry::rect::RectF,
4 json::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 set_window_title(&mut self, title: &str) {
979 self.window.platform_window.set_title(title);
980 }
981
982 pub fn set_window_edited(&mut self, edited: bool) {
983 self.window.platform_window.set_edited(edited);
984 }
985
986 pub fn is_topmost_window_for_position(&self, position: Vector2F) -> bool {
987 self.window
988 .platform_window
989 .is_topmost_for_position(position)
990 }
991
992 pub fn activate_window(&self) {
993 self.window.platform_window.activate();
994 }
995
996 pub fn window_is_active(&self) -> bool {
997 self.window.is_active
998 }
999
1000 pub fn window_is_fullscreen(&self) -> bool {
1001 self.window.is_fullscreen
1002 }
1003
1004 pub(crate) fn handle_dispatch_action_from_effect(
1005 &mut self,
1006 view_id: Option<usize>,
1007 action: &dyn Action,
1008 ) -> bool {
1009 if let Some(view_id) = view_id {
1010 self.halt_action_dispatch = false;
1011 self.visit_dispatch_path(view_id, |view_id, capture_phase, cx| {
1012 cx.update_any_view(view_id, |view, cx| {
1013 let type_id = view.as_any().type_id();
1014 if let Some((name, mut handlers)) = cx
1015 .actions_mut(capture_phase)
1016 .get_mut(&type_id)
1017 .and_then(|h| h.remove_entry(&action.id()))
1018 {
1019 for handler in handlers.iter_mut().rev() {
1020 cx.halt_action_dispatch = true;
1021 handler(view, action, cx, view_id);
1022 if cx.halt_action_dispatch {
1023 break;
1024 }
1025 }
1026 cx.actions_mut(capture_phase)
1027 .get_mut(&type_id)
1028 .unwrap()
1029 .insert(name, handlers);
1030 }
1031 });
1032
1033 !cx.halt_action_dispatch
1034 });
1035 }
1036
1037 if !self.halt_action_dispatch {
1038 self.halt_action_dispatch = self.dispatch_global_action_any(action);
1039 }
1040
1041 self.pending_effects
1042 .push_back(Effect::ActionDispatchNotification {
1043 action_id: action.id(),
1044 });
1045 self.halt_action_dispatch
1046 }
1047
1048 /// Returns an iterator over all of the view ids from the passed view up to the root of the window
1049 /// Includes the passed view itself
1050 pub(crate) fn ancestors(&self, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
1051 std::iter::once(view_id)
1052 .into_iter()
1053 .chain(std::iter::from_fn(move || {
1054 if let Some(ParentId::View(parent_id)) =
1055 self.parents.get(&(self.window_id, view_id))
1056 {
1057 view_id = *parent_id;
1058 Some(view_id)
1059 } else {
1060 None
1061 }
1062 }))
1063 }
1064
1065 /// Returns the id of the parent of the given view, or none if the given
1066 /// view is the root.
1067 pub(crate) fn parent(&self, view_id: usize) -> Option<usize> {
1068 if let Some(ParentId::View(view_id)) = self.parents.get(&(self.window_id, view_id)) {
1069 Some(*view_id)
1070 } else {
1071 None
1072 }
1073 }
1074
1075 // Traverses the parent tree. Walks down the tree toward the passed
1076 // view calling visit with true. Then walks back up the tree calling visit with false.
1077 // If `visit` returns false this function will immediately return.
1078 fn visit_dispatch_path(
1079 &mut self,
1080 view_id: usize,
1081 mut visit: impl FnMut(usize, bool, &mut WindowContext) -> bool,
1082 ) {
1083 // List of view ids from the leaf to the root of the window
1084 let path = self.ancestors(view_id).collect::<Vec<_>>();
1085
1086 // Walk down from the root to the leaf calling visit with capture_phase = true
1087 for view_id in path.iter().rev() {
1088 if !visit(*view_id, true, self) {
1089 return;
1090 }
1091 }
1092
1093 // Walk up from the leaf to the root calling visit with capture_phase = false
1094 for view_id in path.iter() {
1095 if !visit(*view_id, false, self) {
1096 return;
1097 }
1098 }
1099 }
1100
1101 pub fn focused_view_id(&self) -> Option<usize> {
1102 self.window.focused_view_id
1103 }
1104
1105 pub fn is_child_focused(&self, view: &AnyViewHandle) -> bool {
1106 if let Some(focused_view_id) = self.focused_view_id() {
1107 self.ancestors(focused_view_id)
1108 .skip(1) // Skip self id
1109 .any(|parent| parent == view.view_id)
1110 } else {
1111 false
1112 }
1113 }
1114
1115 pub fn window_bounds(&self) -> WindowBounds {
1116 self.window.platform_window.bounds()
1117 }
1118
1119 pub fn window_appearance(&self) -> Appearance {
1120 self.window.appearance
1121 }
1122
1123 pub fn window_display_uuid(&self) -> Option<Uuid> {
1124 self.window.platform_window.screen().display_uuid()
1125 }
1126
1127 pub fn show_character_palette(&self) {
1128 self.window.platform_window.show_character_palette();
1129 }
1130
1131 pub fn minimize_window(&self) {
1132 self.window.platform_window.minimize();
1133 }
1134
1135 pub fn zoom_window(&self) {
1136 self.window.platform_window.zoom();
1137 }
1138
1139 pub fn toggle_full_screen(&self) {
1140 self.window.platform_window.toggle_full_screen();
1141 }
1142
1143 pub fn prompt(
1144 &self,
1145 level: PromptLevel,
1146 msg: &str,
1147 answers: &[&str],
1148 ) -> oneshot::Receiver<usize> {
1149 self.window.platform_window.prompt(level, msg, answers)
1150 }
1151
1152 pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
1153 where
1154 V: View,
1155 F: FnOnce(&mut ViewContext<V>) -> V,
1156 {
1157 let root_view = self
1158 .build_and_insert_view(ParentId::Root, |cx| Some(build_root_view(cx)))
1159 .unwrap();
1160 self.window.root_view = Some(root_view.clone().into_any());
1161 self.window.focused_view_id = Some(root_view.id());
1162 root_view
1163 }
1164
1165 pub(crate) fn build_and_insert_view<T, F>(
1166 &mut self,
1167 parent_id: ParentId,
1168 build_view: F,
1169 ) -> Option<ViewHandle<T>>
1170 where
1171 T: View,
1172 F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1173 {
1174 let window_id = self.window_id;
1175 let view_id = post_inc(&mut self.next_entity_id);
1176 // Make sure we can tell child views about their parentu
1177 self.parents.insert((window_id, view_id), parent_id);
1178 let mut cx = ViewContext::mutable(self, view_id);
1179 let handle = if let Some(view) = build_view(&mut cx) {
1180 self.views.insert((window_id, view_id), Box::new(view));
1181 self.window
1182 .invalidation
1183 .get_or_insert_with(Default::default)
1184 .updated
1185 .insert(view_id);
1186 Some(ViewHandle::new(window_id, view_id, &self.ref_counts))
1187 } else {
1188 self.parents.remove(&(window_id, view_id));
1189 None
1190 };
1191 handle
1192 }
1193}
1194
1195pub struct RenderParams {
1196 pub view_id: usize,
1197 pub titlebar_height: f32,
1198 pub hovered_region_ids: HashSet<MouseRegionId>,
1199 pub clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
1200 pub refreshing: bool,
1201 pub appearance: Appearance,
1202}
1203
1204#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1205pub enum Axis {
1206 #[default]
1207 Horizontal,
1208 Vertical,
1209}
1210
1211impl Axis {
1212 pub fn invert(self) -> Self {
1213 match self {
1214 Self::Horizontal => Self::Vertical,
1215 Self::Vertical => Self::Horizontal,
1216 }
1217 }
1218
1219 pub fn component(&self, point: Vector2F) -> f32 {
1220 match self {
1221 Self::Horizontal => point.x(),
1222 Self::Vertical => point.y(),
1223 }
1224 }
1225}
1226
1227impl ToJson for Axis {
1228 fn to_json(&self) -> serde_json::Value {
1229 match self {
1230 Axis::Horizontal => json!("horizontal"),
1231 Axis::Vertical => json!("vertical"),
1232 }
1233 }
1234}
1235
1236impl StaticColumnCount for Axis {}
1237impl Bind for Axis {
1238 fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
1239 match self {
1240 Axis::Horizontal => "Horizontal",
1241 Axis::Vertical => "Vertical",
1242 }
1243 .bind(statement, start_index)
1244 }
1245}
1246
1247impl Column for Axis {
1248 fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
1249 String::column(statement, start_index).and_then(|(axis_text, next_index)| {
1250 Ok((
1251 match axis_text.as_str() {
1252 "Horizontal" => Axis::Horizontal,
1253 "Vertical" => Axis::Vertical,
1254 _ => bail!("Stored serialized item kind is incorrect"),
1255 },
1256 next_index,
1257 ))
1258 })
1259 }
1260}
1261
1262pub trait Vector2FExt {
1263 fn along(self, axis: Axis) -> f32;
1264}
1265
1266impl Vector2FExt for Vector2F {
1267 fn along(self, axis: Axis) -> f32 {
1268 match axis {
1269 Axis::Horizontal => self.x(),
1270 Axis::Vertical => self.y(),
1271 }
1272 }
1273}
1274
1275#[derive(Copy, Clone, Debug)]
1276pub struct SizeConstraint {
1277 pub min: Vector2F,
1278 pub max: Vector2F,
1279}
1280
1281impl SizeConstraint {
1282 pub fn new(min: Vector2F, max: Vector2F) -> Self {
1283 Self { min, max }
1284 }
1285
1286 pub fn strict(size: Vector2F) -> Self {
1287 Self {
1288 min: size,
1289 max: size,
1290 }
1291 }
1292
1293 pub fn strict_along(axis: Axis, max: f32) -> Self {
1294 match axis {
1295 Axis::Horizontal => Self {
1296 min: vec2f(max, 0.0),
1297 max: vec2f(max, f32::INFINITY),
1298 },
1299 Axis::Vertical => Self {
1300 min: vec2f(0.0, max),
1301 max: vec2f(f32::INFINITY, max),
1302 },
1303 }
1304 }
1305
1306 pub fn max_along(&self, axis: Axis) -> f32 {
1307 match axis {
1308 Axis::Horizontal => self.max.x(),
1309 Axis::Vertical => self.max.y(),
1310 }
1311 }
1312
1313 pub fn min_along(&self, axis: Axis) -> f32 {
1314 match axis {
1315 Axis::Horizontal => self.min.x(),
1316 Axis::Vertical => self.min.y(),
1317 }
1318 }
1319
1320 pub fn constrain(&self, size: Vector2F) -> Vector2F {
1321 vec2f(
1322 size.x().min(self.max.x()).max(self.min.x()),
1323 size.y().min(self.max.y()).max(self.min.y()),
1324 )
1325 }
1326}
1327
1328impl Default for SizeConstraint {
1329 fn default() -> Self {
1330 SizeConstraint {
1331 min: Vector2F::zero(),
1332 max: Vector2F::splat(f32::INFINITY),
1333 }
1334 }
1335}
1336
1337impl ToJson for SizeConstraint {
1338 fn to_json(&self) -> serde_json::Value {
1339 json!({
1340 "min": self.min.to_json(),
1341 "max": self.max.to_json(),
1342 })
1343 }
1344}
1345
1346pub struct ChildView {
1347 view_id: usize,
1348 view_name: &'static str,
1349}
1350
1351impl ChildView {
1352 pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
1353 let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
1354 Self {
1355 view_id: view.id(),
1356 view_name,
1357 }
1358 }
1359}
1360
1361impl<V: View> Element<V> for ChildView {
1362 type LayoutState = ();
1363 type PaintState = ();
1364
1365 fn layout(
1366 &mut self,
1367 constraint: SizeConstraint,
1368 _: &mut V,
1369 cx: &mut ViewContext<V>,
1370 ) -> (Vector2F, Self::LayoutState) {
1371 if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1372 let size = rendered_view
1373 .layout(constraint, cx)
1374 .log_err()
1375 .unwrap_or(Vector2F::zero());
1376 cx.window.rendered_views.insert(self.view_id, rendered_view);
1377 (size, ())
1378 } else {
1379 log::error!(
1380 "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1381 self.view_id,
1382 self.view_name
1383 );
1384 (Vector2F::zero(), ())
1385 }
1386 }
1387
1388 fn paint(
1389 &mut self,
1390 scene: &mut SceneBuilder,
1391 bounds: RectF,
1392 visible_bounds: RectF,
1393 _: &mut Self::LayoutState,
1394 _: &mut V,
1395 cx: &mut ViewContext<V>,
1396 ) {
1397 if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1398 rendered_view
1399 .paint(scene, bounds.origin(), visible_bounds, cx)
1400 .log_err();
1401 cx.window.rendered_views.insert(self.view_id, rendered_view);
1402 } else {
1403 log::error!(
1404 "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1405 self.view_id,
1406 self.view_name
1407 );
1408 }
1409 }
1410
1411 fn rect_for_text_range(
1412 &self,
1413 range_utf16: Range<usize>,
1414 _: RectF,
1415 _: RectF,
1416 _: &Self::LayoutState,
1417 _: &Self::PaintState,
1418 _: &V,
1419 cx: &ViewContext<V>,
1420 ) -> Option<RectF> {
1421 if let Some(rendered_view) = cx.window.rendered_views.get(&self.view_id) {
1422 rendered_view
1423 .rect_for_text_range(range_utf16, &cx.window_context)
1424 .log_err()
1425 .flatten()
1426 } else {
1427 log::error!(
1428 "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1429 self.view_id,
1430 self.view_name
1431 );
1432 None
1433 }
1434 }
1435
1436 fn debug(
1437 &self,
1438 bounds: RectF,
1439 _: &Self::LayoutState,
1440 _: &Self::PaintState,
1441 _: &V,
1442 cx: &ViewContext<V>,
1443 ) -> serde_json::Value {
1444 json!({
1445 "type": "ChildView",
1446 "bounds": bounds.to_json(),
1447 "child": if let Some(element) = cx.window.rendered_views.get(&self.view_id) {
1448 element.debug(&cx.window_context).log_err().unwrap_or_else(|| json!(null))
1449 } else {
1450 json!(null)
1451 }
1452 })
1453 }
1454}