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