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