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