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