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