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