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