1use crate::{
2 app::{AppContext, MutableAppContext, WindowInvalidation},
3 elements::Element,
4 font_cache::FontCache,
5 geometry::rect::RectF,
6 json::{self, ToJson},
7 platform::Event,
8 text_layout::TextLayoutCache,
9 Action, AnyAction, AssetCache, ElementBox, Entity, FontSystem, ModelHandle, ReadModel,
10 ReadView, Scene, View, ViewHandle,
11};
12use pathfinder_geometry::vector::{vec2f, Vector2F};
13use serde_json::json;
14use std::{
15 collections::{HashMap, HashSet},
16 ops::{Deref, DerefMut},
17 sync::Arc,
18};
19
20pub struct Presenter {
21 window_id: usize,
22 rendered_views: HashMap<usize, ElementBox>,
23 parents: HashMap<usize, usize>,
24 font_cache: Arc<FontCache>,
25 text_layout_cache: TextLayoutCache,
26 asset_cache: Arc<AssetCache>,
27 last_mouse_moved_event: Option<Event>,
28 titlebar_height: f32,
29}
30
31impl Presenter {
32 pub fn new(
33 window_id: usize,
34 titlebar_height: f32,
35 font_cache: Arc<FontCache>,
36 text_layout_cache: TextLayoutCache,
37 asset_cache: Arc<AssetCache>,
38 cx: &mut MutableAppContext,
39 ) -> Self {
40 Self {
41 window_id,
42 rendered_views: cx.render_views(window_id, titlebar_height),
43 parents: HashMap::new(),
44 font_cache,
45 text_layout_cache,
46 asset_cache,
47 last_mouse_moved_event: None,
48 titlebar_height,
49 }
50 }
51
52 pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
53 let mut view_id = app.focused_view_id(self.window_id).unwrap();
54 let mut path = vec![view_id];
55 while let Some(parent_id) = self.parents.get(&view_id).copied() {
56 path.push(parent_id);
57 view_id = parent_id;
58 }
59 path.reverse();
60 path
61 }
62
63 pub fn invalidate(&mut self, mut invalidation: WindowInvalidation, cx: &mut MutableAppContext) {
64 for view_id in invalidation.removed {
65 invalidation.updated.remove(&view_id);
66 self.rendered_views.remove(&view_id);
67 self.parents.remove(&view_id);
68 }
69 for view_id in invalidation.updated {
70 self.rendered_views.insert(
71 view_id,
72 cx.render_view(self.window_id, view_id, self.titlebar_height, false)
73 .unwrap(),
74 );
75 }
76 }
77
78 pub fn refresh(
79 &mut self,
80 invalidation: Option<WindowInvalidation>,
81 cx: &mut MutableAppContext,
82 ) {
83 if let Some(invalidation) = invalidation {
84 for view_id in invalidation.removed {
85 self.rendered_views.remove(&view_id);
86 self.parents.remove(&view_id);
87 }
88 }
89
90 for (view_id, view) in &mut self.rendered_views {
91 *view = cx
92 .render_view(self.window_id, *view_id, self.titlebar_height, true)
93 .unwrap();
94 }
95 }
96
97 pub fn build_scene(
98 &mut self,
99 window_size: Vector2F,
100 scale_factor: f32,
101 refreshing: bool,
102 cx: &mut MutableAppContext,
103 ) -> Scene {
104 let mut scene = Scene::new(scale_factor);
105
106 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
107 self.layout(window_size, refreshing, cx);
108 let mut paint_cx = PaintContext {
109 scene: &mut scene,
110 font_cache: &self.font_cache,
111 text_layout_cache: &self.text_layout_cache,
112 rendered_views: &mut self.rendered_views,
113 app: cx.as_ref(),
114 };
115 paint_cx.paint(
116 root_view_id,
117 Vector2F::zero(),
118 RectF::new(Vector2F::zero(), window_size),
119 );
120 self.text_layout_cache.finish_frame();
121
122 if let Some(event) = self.last_mouse_moved_event.clone() {
123 self.dispatch_event(event, cx)
124 }
125 } else {
126 log::error!("could not find root_view_id for window {}", self.window_id);
127 }
128
129 scene
130 }
131
132 fn layout(&mut self, size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
133 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
134 self.build_layout_context(refreshing, cx)
135 .layout(root_view_id, SizeConstraint::strict(size));
136 }
137 }
138
139 pub fn build_layout_context<'a>(
140 &'a mut self,
141 refreshing: bool,
142 cx: &'a mut MutableAppContext,
143 ) -> LayoutContext<'a> {
144 LayoutContext {
145 rendered_views: &mut self.rendered_views,
146 parents: &mut self.parents,
147 refreshing,
148 font_cache: &self.font_cache,
149 font_system: cx.platform().fonts(),
150 text_layout_cache: &self.text_layout_cache,
151 asset_cache: &self.asset_cache,
152 view_stack: Vec::new(),
153 app: cx,
154 }
155 }
156
157 pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) {
158 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
159 match event {
160 Event::MouseMoved { .. } => {
161 self.last_mouse_moved_event = Some(event.clone());
162 }
163 Event::LeftMouseDragged { position } => {
164 self.last_mouse_moved_event = Some(Event::MouseMoved {
165 position,
166 left_mouse_down: true,
167 });
168 }
169 _ => {}
170 }
171
172 let mut event_cx = self.build_event_context(cx);
173 event_cx.dispatch_event(root_view_id, &event);
174
175 let invalidated_views = event_cx.invalidated_views;
176 let dispatch_directives = event_cx.dispatched_actions;
177
178 for view_id in invalidated_views {
179 cx.notify_view(self.window_id, view_id);
180 }
181 for directive in dispatch_directives {
182 cx.dispatch_action_any(self.window_id, &directive.path, directive.action.as_ref());
183 }
184 }
185 }
186
187 pub fn build_event_context<'a>(
188 &'a mut self,
189 cx: &'a mut MutableAppContext,
190 ) -> EventContext<'a> {
191 EventContext {
192 rendered_views: &mut self.rendered_views,
193 dispatched_actions: Default::default(),
194 font_cache: &self.font_cache,
195 text_layout_cache: &self.text_layout_cache,
196 view_stack: Default::default(),
197 invalidated_views: Default::default(),
198 app: cx,
199 }
200 }
201
202 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
203 cx.root_view_id(self.window_id)
204 .and_then(|root_view_id| self.rendered_views.get(&root_view_id))
205 .map(|root_element| {
206 root_element.debug(&DebugContext {
207 rendered_views: &self.rendered_views,
208 font_cache: &self.font_cache,
209 app: cx,
210 })
211 })
212 }
213}
214
215pub struct DispatchDirective {
216 pub path: Vec<usize>,
217 pub action: Box<dyn AnyAction>,
218}
219
220pub struct LayoutContext<'a> {
221 rendered_views: &'a mut HashMap<usize, ElementBox>,
222 parents: &'a mut HashMap<usize, usize>,
223 view_stack: Vec<usize>,
224 pub refreshing: bool,
225 pub font_cache: &'a Arc<FontCache>,
226 pub font_system: Arc<dyn FontSystem>,
227 pub text_layout_cache: &'a TextLayoutCache,
228 pub asset_cache: &'a AssetCache,
229 pub app: &'a mut MutableAppContext,
230}
231
232impl<'a> LayoutContext<'a> {
233 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
234 if let Some(parent_id) = self.view_stack.last() {
235 self.parents.insert(view_id, *parent_id);
236 }
237 self.view_stack.push(view_id);
238 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
239 let size = rendered_view.layout(constraint, self);
240 self.rendered_views.insert(view_id, rendered_view);
241 self.view_stack.pop();
242 size
243 }
244}
245
246impl<'a> Deref for LayoutContext<'a> {
247 type Target = MutableAppContext;
248
249 fn deref(&self) -> &Self::Target {
250 self.app
251 }
252}
253
254impl<'a> DerefMut for LayoutContext<'a> {
255 fn deref_mut(&mut self) -> &mut Self::Target {
256 self.app
257 }
258}
259
260impl<'a> ReadView for LayoutContext<'a> {
261 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
262 self.app.read_view(handle)
263 }
264}
265
266impl<'a> ReadModel for LayoutContext<'a> {
267 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
268 self.app.read_model(handle)
269 }
270}
271
272pub struct PaintContext<'a> {
273 rendered_views: &'a mut HashMap<usize, ElementBox>,
274 pub scene: &'a mut Scene,
275 pub font_cache: &'a FontCache,
276 pub text_layout_cache: &'a TextLayoutCache,
277 pub app: &'a AppContext,
278}
279
280impl<'a> PaintContext<'a> {
281 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
282 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
283 tree.paint(origin, visible_bounds, self);
284 self.rendered_views.insert(view_id, tree);
285 }
286 }
287}
288
289pub struct EventContext<'a> {
290 rendered_views: &'a mut HashMap<usize, ElementBox>,
291 dispatched_actions: Vec<DispatchDirective>,
292 pub font_cache: &'a FontCache,
293 pub text_layout_cache: &'a TextLayoutCache,
294 pub app: &'a mut MutableAppContext,
295 view_stack: Vec<usize>,
296 invalidated_views: HashSet<usize>,
297}
298
299impl<'a> EventContext<'a> {
300 fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
301 if let Some(mut element) = self.rendered_views.remove(&view_id) {
302 self.view_stack.push(view_id);
303 let result = element.dispatch_event(event, self);
304 self.view_stack.pop();
305 self.rendered_views.insert(view_id, element);
306 result
307 } else {
308 false
309 }
310 }
311
312 pub fn dispatch_action<A: Action>(&mut self, action: A) {
313 self.dispatched_actions.push(DispatchDirective {
314 path: self.view_stack.clone(),
315 action: Box::new(action),
316 });
317 }
318
319 pub fn notify(&mut self) {
320 if let Some(view_id) = self.view_stack.last() {
321 self.invalidated_views.insert(*view_id);
322 }
323 }
324}
325
326impl<'a> Deref for EventContext<'a> {
327 type Target = MutableAppContext;
328
329 fn deref(&self) -> &Self::Target {
330 self.app
331 }
332}
333
334impl<'a> DerefMut for EventContext<'a> {
335 fn deref_mut(&mut self) -> &mut Self::Target {
336 self.app
337 }
338}
339
340pub struct DebugContext<'a> {
341 rendered_views: &'a HashMap<usize, ElementBox>,
342 pub font_cache: &'a FontCache,
343 pub app: &'a AppContext,
344}
345
346#[derive(Clone, Copy, Debug, Eq, PartialEq)]
347pub enum Axis {
348 Horizontal,
349 Vertical,
350}
351
352impl Axis {
353 pub fn invert(self) -> Self {
354 match self {
355 Self::Horizontal => Self::Vertical,
356 Self::Vertical => Self::Horizontal,
357 }
358 }
359}
360
361impl ToJson for Axis {
362 fn to_json(&self) -> serde_json::Value {
363 match self {
364 Axis::Horizontal => json!("horizontal"),
365 Axis::Vertical => json!("vertical"),
366 }
367 }
368}
369
370pub trait Vector2FExt {
371 fn along(self, axis: Axis) -> f32;
372}
373
374impl Vector2FExt for Vector2F {
375 fn along(self, axis: Axis) -> f32 {
376 match axis {
377 Axis::Horizontal => self.x(),
378 Axis::Vertical => self.y(),
379 }
380 }
381}
382
383#[derive(Copy, Clone, Debug)]
384pub struct SizeConstraint {
385 pub min: Vector2F,
386 pub max: Vector2F,
387}
388
389impl SizeConstraint {
390 pub fn new(min: Vector2F, max: Vector2F) -> Self {
391 Self { min, max }
392 }
393
394 pub fn strict(size: Vector2F) -> Self {
395 Self {
396 min: size,
397 max: size,
398 }
399 }
400
401 pub fn strict_along(axis: Axis, max: f32) -> Self {
402 match axis {
403 Axis::Horizontal => Self {
404 min: vec2f(max, 0.0),
405 max: vec2f(max, f32::INFINITY),
406 },
407 Axis::Vertical => Self {
408 min: vec2f(0.0, max),
409 max: vec2f(f32::INFINITY, max),
410 },
411 }
412 }
413
414 pub fn max_along(&self, axis: Axis) -> f32 {
415 match axis {
416 Axis::Horizontal => self.max.x(),
417 Axis::Vertical => self.max.y(),
418 }
419 }
420
421 pub fn min_along(&self, axis: Axis) -> f32 {
422 match axis {
423 Axis::Horizontal => self.min.x(),
424 Axis::Vertical => self.min.y(),
425 }
426 }
427}
428
429impl ToJson for SizeConstraint {
430 fn to_json(&self) -> serde_json::Value {
431 json!({
432 "min": self.min.to_json(),
433 "max": self.max.to_json(),
434 })
435 }
436}
437
438pub struct ChildView {
439 view_id: usize,
440}
441
442impl ChildView {
443 pub fn new(view_id: usize) -> Self {
444 Self { view_id }
445 }
446}
447
448impl Element for ChildView {
449 type LayoutState = ();
450 type PaintState = ();
451
452 fn layout(
453 &mut self,
454 constraint: SizeConstraint,
455 cx: &mut LayoutContext,
456 ) -> (Vector2F, Self::LayoutState) {
457 let size = cx.layout(self.view_id, constraint);
458 (size, ())
459 }
460
461 fn paint(
462 &mut self,
463 bounds: RectF,
464 visible_bounds: RectF,
465 _: &mut Self::LayoutState,
466 cx: &mut PaintContext,
467 ) -> Self::PaintState {
468 cx.paint(self.view_id, bounds.origin(), visible_bounds);
469 }
470
471 fn dispatch_event(
472 &mut self,
473 event: &Event,
474 _: RectF,
475 _: &mut Self::LayoutState,
476 _: &mut Self::PaintState,
477 cx: &mut EventContext,
478 ) -> bool {
479 cx.dispatch_event(self.view_id, event)
480 }
481
482 fn debug(
483 &self,
484 bounds: RectF,
485 _: &Self::LayoutState,
486 _: &Self::PaintState,
487 cx: &DebugContext,
488 ) -> serde_json::Value {
489 json!({
490 "type": "ChildView",
491 "view_id": self.view_id,
492 "bounds": bounds.to_json(),
493 "child": if let Some(view) = cx.rendered_views.get(&self.view_id) {
494 view.debug(cx)
495 } else {
496 json!(null)
497 }
498 })
499 }
500}
501
502#[cfg(test)]
503mod tests {
504 // #[test]
505 // fn test_responder_chain() {
506 // let settings = settings_rx(None);
507 // let mut app = App::new().unwrap();
508 // let workspace = app.add_model(|cx| Workspace::new(Vec::new(), cx));
509 // let (window_id, workspace_view) =
510 // app.add_window(|cx| WorkspaceView::new(workspace.clone(), settings, cx));
511
512 // let invalidations = Rc::new(RefCell::new(Vec::new()));
513 // let invalidations_ = invalidations.clone();
514 // app.on_window_invalidated(window_id, move |invalidation, _| {
515 // invalidations_.borrow_mut().push(invalidation)
516 // });
517
518 // let active_pane_id = workspace_view.update(&mut app, |view, cx| {
519 // cx.focus(view.active_pane());
520 // view.active_pane().id()
521 // });
522
523 // app.update(|app| {
524 // let mut presenter = Presenter::new(
525 // window_id,
526 // Rc::new(FontCache::new()),
527 // Rc::new(AssetCache::new()),
528 // app,
529 // );
530 // for invalidation in invalidations.borrow().iter().cloned() {
531 // presenter.update(vec2f(1024.0, 768.0), 2.0, Some(invalidation), app);
532 // }
533
534 // assert_eq!(
535 // presenter.responder_chain(app.cx()).unwrap(),
536 // vec![workspace_view.id(), active_pane_id]
537 // );
538 // });
539 // }
540}