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