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.build_layout_context(cx)
128 .layout(root_view_id, SizeConstraint::strict(size));
129 }
130 }
131
132 pub fn build_layout_context<'a>(
133 &'a mut self,
134 cx: &'a mut MutableAppContext,
135 ) -> LayoutContext<'a> {
136 LayoutContext {
137 rendered_views: &mut self.rendered_views,
138 parents: &mut self.parents,
139 font_cache: &self.font_cache,
140 font_system: cx.platform().fonts(),
141 text_layout_cache: &self.text_layout_cache,
142 asset_cache: &self.asset_cache,
143 view_stack: Vec::new(),
144 app: cx,
145 }
146 }
147
148 pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) {
149 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
150 match event {
151 Event::MouseMoved { .. } => {
152 self.last_mouse_moved_event = Some(event.clone());
153 }
154 Event::LeftMouseDragged { position } => {
155 self.last_mouse_moved_event = Some(Event::MouseMoved {
156 position,
157 left_mouse_down: true,
158 });
159 }
160 _ => {}
161 }
162
163 let mut event_cx = EventContext {
164 rendered_views: &mut self.rendered_views,
165 dispatched_actions: Default::default(),
166 font_cache: &self.font_cache,
167 text_layout_cache: &self.text_layout_cache,
168 view_stack: Default::default(),
169 invalidated_views: Default::default(),
170 app: cx,
171 };
172 event_cx.dispatch_event(root_view_id, &event);
173
174 let invalidated_views = event_cx.invalidated_views;
175 let dispatch_directives = event_cx.dispatched_actions;
176
177 for view_id in invalidated_views {
178 cx.notify_view(self.window_id, view_id);
179 }
180 for directive in dispatch_directives {
181 cx.dispatch_action_any(self.window_id, &directive.path, directive.action.as_ref());
182 }
183 }
184 }
185
186 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
187 cx.root_view_id(self.window_id)
188 .and_then(|root_view_id| self.rendered_views.get(&root_view_id))
189 .map(|root_element| {
190 root_element.debug(&DebugContext {
191 rendered_views: &self.rendered_views,
192 font_cache: &self.font_cache,
193 app: cx,
194 })
195 })
196 }
197}
198
199pub struct DispatchDirective {
200 pub path: Vec<usize>,
201 pub action: Box<dyn AnyAction>,
202}
203
204pub struct LayoutContext<'a> {
205 rendered_views: &'a mut HashMap<usize, ElementBox>,
206 parents: &'a mut HashMap<usize, usize>,
207 view_stack: Vec<usize>,
208 pub font_cache: &'a Arc<FontCache>,
209 pub font_system: Arc<dyn FontSystem>,
210 pub text_layout_cache: &'a TextLayoutCache,
211 pub asset_cache: &'a AssetCache,
212 pub app: &'a mut MutableAppContext,
213}
214
215impl<'a> LayoutContext<'a> {
216 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
217 if let Some(parent_id) = self.view_stack.last() {
218 self.parents.insert(view_id, *parent_id);
219 }
220 self.view_stack.push(view_id);
221 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
222 let size = rendered_view.layout(constraint, self);
223 self.rendered_views.insert(view_id, rendered_view);
224 self.view_stack.pop();
225 size
226 }
227}
228
229pub struct PaintContext<'a> {
230 rendered_views: &'a mut HashMap<usize, ElementBox>,
231 pub scene: &'a mut Scene,
232 pub font_cache: &'a FontCache,
233 pub text_layout_cache: &'a TextLayoutCache,
234 pub app: &'a AppContext,
235}
236
237impl<'a> PaintContext<'a> {
238 fn paint(&mut self, view_id: usize, origin: Vector2F) {
239 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
240 tree.paint(origin, self);
241 self.rendered_views.insert(view_id, tree);
242 }
243 }
244}
245
246pub struct EventContext<'a> {
247 rendered_views: &'a mut HashMap<usize, ElementBox>,
248 dispatched_actions: Vec<DispatchDirective>,
249 pub font_cache: &'a FontCache,
250 pub text_layout_cache: &'a TextLayoutCache,
251 pub app: &'a mut MutableAppContext,
252 view_stack: Vec<usize>,
253 invalidated_views: HashSet<usize>,
254}
255
256impl<'a> EventContext<'a> {
257 fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
258 if let Some(mut element) = self.rendered_views.remove(&view_id) {
259 self.view_stack.push(view_id);
260 let result = element.dispatch_event(event, self);
261 self.view_stack.pop();
262 self.rendered_views.insert(view_id, element);
263 result
264 } else {
265 false
266 }
267 }
268
269 pub fn dispatch_action<A: Action>(&mut self, action: A) {
270 self.dispatched_actions.push(DispatchDirective {
271 path: self.view_stack.clone(),
272 action: Box::new(action),
273 });
274 }
275
276 pub fn notify(&mut self) {
277 self.invalidated_views
278 .insert(*self.view_stack.last().unwrap());
279 }
280}
281
282impl<'a> Deref for EventContext<'a> {
283 type Target = MutableAppContext;
284
285 fn deref(&self) -> &Self::Target {
286 self.app
287 }
288}
289
290impl<'a> DerefMut for EventContext<'a> {
291 fn deref_mut(&mut self) -> &mut Self::Target {
292 self.app
293 }
294}
295
296pub struct DebugContext<'a> {
297 rendered_views: &'a HashMap<usize, ElementBox>,
298 pub font_cache: &'a FontCache,
299 pub app: &'a AppContext,
300}
301
302#[derive(Clone, Copy, Debug, Eq, PartialEq)]
303pub enum Axis {
304 Horizontal,
305 Vertical,
306}
307
308impl Axis {
309 pub fn invert(self) -> Self {
310 match self {
311 Self::Horizontal => Self::Vertical,
312 Self::Vertical => Self::Horizontal,
313 }
314 }
315}
316
317impl ToJson for Axis {
318 fn to_json(&self) -> serde_json::Value {
319 match self {
320 Axis::Horizontal => json!("horizontal"),
321 Axis::Vertical => json!("vertical"),
322 }
323 }
324}
325
326pub trait Vector2FExt {
327 fn along(self, axis: Axis) -> f32;
328}
329
330impl Vector2FExt for Vector2F {
331 fn along(self, axis: Axis) -> f32 {
332 match axis {
333 Axis::Horizontal => self.x(),
334 Axis::Vertical => self.y(),
335 }
336 }
337}
338
339#[derive(Copy, Clone, Debug)]
340pub struct SizeConstraint {
341 pub min: Vector2F,
342 pub max: Vector2F,
343}
344
345impl SizeConstraint {
346 pub fn new(min: Vector2F, max: Vector2F) -> Self {
347 Self { min, max }
348 }
349
350 pub fn strict(size: Vector2F) -> Self {
351 Self {
352 min: size,
353 max: size,
354 }
355 }
356
357 pub fn strict_along(axis: Axis, max: f32) -> Self {
358 match axis {
359 Axis::Horizontal => Self {
360 min: vec2f(max, 0.0),
361 max: vec2f(max, f32::INFINITY),
362 },
363 Axis::Vertical => Self {
364 min: vec2f(0.0, max),
365 max: vec2f(f32::INFINITY, max),
366 },
367 }
368 }
369
370 pub fn max_along(&self, axis: Axis) -> f32 {
371 match axis {
372 Axis::Horizontal => self.max.x(),
373 Axis::Vertical => self.max.y(),
374 }
375 }
376
377 pub fn min_along(&self, axis: Axis) -> f32 {
378 match axis {
379 Axis::Horizontal => self.min.x(),
380 Axis::Vertical => self.min.y(),
381 }
382 }
383}
384
385impl ToJson for SizeConstraint {
386 fn to_json(&self) -> serde_json::Value {
387 json!({
388 "min": self.min.to_json(),
389 "max": self.max.to_json(),
390 })
391 }
392}
393
394pub struct ChildView {
395 view_id: usize,
396}
397
398impl ChildView {
399 pub fn new(view_id: usize) -> Self {
400 Self { view_id }
401 }
402}
403
404impl Element for ChildView {
405 type LayoutState = ();
406 type PaintState = ();
407
408 fn layout(
409 &mut self,
410 constraint: SizeConstraint,
411 cx: &mut LayoutContext,
412 ) -> (Vector2F, Self::LayoutState) {
413 let size = cx.layout(self.view_id, constraint);
414 (size, ())
415 }
416
417 fn paint(
418 &mut self,
419 bounds: pathfinder_geometry::rect::RectF,
420 _: &mut Self::LayoutState,
421 cx: &mut PaintContext,
422 ) -> Self::PaintState {
423 cx.paint(self.view_id, bounds.origin());
424 }
425
426 fn dispatch_event(
427 &mut self,
428 event: &Event,
429 _: pathfinder_geometry::rect::RectF,
430 _: &mut Self::LayoutState,
431 _: &mut Self::PaintState,
432 cx: &mut EventContext,
433 ) -> bool {
434 cx.dispatch_event(self.view_id, event)
435 }
436
437 fn debug(
438 &self,
439 bounds: pathfinder_geometry::rect::RectF,
440 _: &Self::LayoutState,
441 _: &Self::PaintState,
442 cx: &DebugContext,
443 ) -> serde_json::Value {
444 json!({
445 "type": "ChildView",
446 "view_id": self.view_id,
447 "bounds": bounds.to_json(),
448 "child": if let Some(view) = cx.rendered_views.get(&self.view_id) {
449 view.debug(cx)
450 } else {
451 json!(null)
452 }
453 })
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 // #[test]
460 // fn test_responder_chain() {
461 // let settings = settings_rx(None);
462 // let mut app = App::new().unwrap();
463 // let workspace = app.add_model(|cx| Workspace::new(Vec::new(), cx));
464 // let (window_id, workspace_view) =
465 // app.add_window(|cx| WorkspaceView::new(workspace.clone(), settings, cx));
466
467 // let invalidations = Rc::new(RefCell::new(Vec::new()));
468 // let invalidations_ = invalidations.clone();
469 // app.on_window_invalidated(window_id, move |invalidation, _| {
470 // invalidations_.borrow_mut().push(invalidation)
471 // });
472
473 // let active_pane_id = workspace_view.update(&mut app, |view, cx| {
474 // cx.focus(view.active_pane());
475 // view.active_pane().id()
476 // });
477
478 // app.update(|app| {
479 // let mut presenter = Presenter::new(
480 // window_id,
481 // Rc::new(FontCache::new()),
482 // Rc::new(AssetCache::new()),
483 // app,
484 // );
485 // for invalidation in invalidations.borrow().iter().cloned() {
486 // presenter.update(vec2f(1024.0, 768.0), 2.0, Some(invalidation), app);
487 // }
488
489 // assert_eq!(
490 // presenter.responder_chain(app.cx()).unwrap(),
491 // vec![workspace_view.id(), active_pane_id]
492 // );
493 // });
494 // }
495}