1mod align;
2mod canvas;
3mod constrained_box;
4mod container;
5mod empty;
6mod event_handler;
7mod expanded;
8mod flex;
9mod hook;
10mod image;
11mod keystroke_label;
12mod label;
13mod list;
14mod mouse_event_handler;
15mod overlay;
16mod stack;
17mod svg;
18mod text;
19mod tooltip;
20mod uniform_list;
21
22use self::expanded::Expanded;
23pub use self::{
24 align::*, canvas::*, constrained_box::*, container::*, empty::*, event_handler::*, flex::*,
25 hook::*, image::*, keystroke_label::*, label::*, list::*, mouse_event_handler::*, overlay::*,
26 stack::*, svg::*, text::*, tooltip::*, uniform_list::*,
27};
28pub use crate::presenter::ChildView;
29use crate::{
30 geometry::{
31 rect::RectF,
32 vector::{vec2f, Vector2F},
33 },
34 json,
35 presenter::MeasurementContext,
36 Action, DebugContext, Event, EventContext, LayoutContext, PaintContext, RenderContext,
37 SizeConstraint, View,
38};
39use core::panic;
40use json::ToJson;
41use std::{
42 any::Any,
43 borrow::Cow,
44 cell::RefCell,
45 mem,
46 ops::{Deref, DerefMut, Range},
47 rc::Rc,
48};
49
50trait AnyElement {
51 fn layout(&mut self, constraint: SizeConstraint, cx: &mut LayoutContext) -> Vector2F;
52 fn paint(&mut self, origin: Vector2F, visible_bounds: RectF, cx: &mut PaintContext);
53 fn dispatch_event(&mut self, event: &Event, cx: &mut EventContext) -> bool;
54 fn rect_for_text_range(
55 &self,
56 range_utf16: Range<usize>,
57 cx: &MeasurementContext,
58 ) -> Option<RectF>;
59 fn debug(&self, cx: &DebugContext) -> serde_json::Value;
60
61 fn size(&self) -> Vector2F;
62 fn metadata(&self) -> Option<&dyn Any>;
63}
64
65pub trait Element {
66 type LayoutState;
67 type PaintState;
68
69 fn layout(
70 &mut self,
71 constraint: SizeConstraint,
72 cx: &mut LayoutContext,
73 ) -> (Vector2F, Self::LayoutState);
74
75 fn paint(
76 &mut self,
77 bounds: RectF,
78 visible_bounds: RectF,
79 layout: &mut Self::LayoutState,
80 cx: &mut PaintContext,
81 ) -> Self::PaintState;
82
83 fn dispatch_event(
84 &mut self,
85 event: &Event,
86 bounds: RectF,
87 visible_bounds: RectF,
88 layout: &mut Self::LayoutState,
89 paint: &mut Self::PaintState,
90 cx: &mut EventContext,
91 ) -> bool;
92
93 fn rect_for_text_range(
94 &self,
95 range_utf16: Range<usize>,
96 bounds: RectF,
97 visible_bounds: RectF,
98 layout: &Self::LayoutState,
99 paint: &Self::PaintState,
100 cx: &MeasurementContext,
101 ) -> Option<RectF>;
102
103 fn metadata(&self) -> Option<&dyn Any> {
104 None
105 }
106
107 fn debug(
108 &self,
109 bounds: RectF,
110 layout: &Self::LayoutState,
111 paint: &Self::PaintState,
112 cx: &DebugContext,
113 ) -> serde_json::Value;
114
115 fn boxed(self) -> ElementBox
116 where
117 Self: 'static + Sized,
118 {
119 ElementBox(ElementRc {
120 name: None,
121 element: Rc::new(RefCell::new(Lifecycle::Init { element: self })),
122 })
123 }
124
125 fn named(self, name: impl Into<Cow<'static, str>>) -> ElementBox
126 where
127 Self: 'static + Sized,
128 {
129 ElementBox(ElementRc {
130 name: Some(name.into()),
131 element: Rc::new(RefCell::new(Lifecycle::Init { element: self })),
132 })
133 }
134
135 fn constrained(self) -> ConstrainedBox
136 where
137 Self: 'static + Sized,
138 {
139 ConstrainedBox::new(self.boxed())
140 }
141
142 fn aligned(self) -> Align
143 where
144 Self: 'static + Sized,
145 {
146 Align::new(self.boxed())
147 }
148
149 fn contained(self) -> Container
150 where
151 Self: 'static + Sized,
152 {
153 Container::new(self.boxed())
154 }
155
156 fn expanded(self) -> Expanded
157 where
158 Self: 'static + Sized,
159 {
160 Expanded::new(self.boxed())
161 }
162
163 fn flex(self, flex: f32, expanded: bool) -> FlexItem
164 where
165 Self: 'static + Sized,
166 {
167 FlexItem::new(self.boxed()).flex(flex, expanded)
168 }
169
170 fn flex_float(self) -> FlexItem
171 where
172 Self: 'static + Sized,
173 {
174 FlexItem::new(self.boxed()).float()
175 }
176
177 fn with_tooltip<Tag: 'static, T: View>(
178 self,
179 id: usize,
180 text: String,
181 action: Option<Box<dyn Action>>,
182 style: TooltipStyle,
183 cx: &mut RenderContext<T>,
184 ) -> Tooltip
185 where
186 Self: 'static + Sized,
187 {
188 Tooltip::new::<Tag, T>(id, text, action, style, self.boxed(), cx)
189 }
190}
191
192pub enum Lifecycle<T: Element> {
193 Empty,
194 Init {
195 element: T,
196 },
197 PostLayout {
198 element: T,
199 constraint: SizeConstraint,
200 size: Vector2F,
201 layout: T::LayoutState,
202 },
203 PostPaint {
204 element: T,
205 constraint: SizeConstraint,
206 bounds: RectF,
207 visible_bounds: RectF,
208 layout: T::LayoutState,
209 paint: T::PaintState,
210 },
211}
212pub struct ElementBox(ElementRc);
213
214#[derive(Clone)]
215pub struct ElementRc {
216 name: Option<Cow<'static, str>>,
217 element: Rc<RefCell<dyn AnyElement>>,
218}
219
220impl<T: Element> AnyElement for Lifecycle<T> {
221 fn layout(&mut self, constraint: SizeConstraint, cx: &mut LayoutContext) -> Vector2F {
222 let result;
223 *self = match mem::take(self) {
224 Lifecycle::Empty => unreachable!(),
225 Lifecycle::Init { mut element }
226 | Lifecycle::PostLayout { mut element, .. }
227 | Lifecycle::PostPaint { mut element, .. } => {
228 let (size, layout) = element.layout(constraint, cx);
229 debug_assert!(size.x().is_finite());
230 debug_assert!(size.y().is_finite());
231
232 result = size;
233 Lifecycle::PostLayout {
234 element,
235 constraint,
236 size,
237 layout,
238 }
239 }
240 };
241 result
242 }
243
244 fn paint(&mut self, origin: Vector2F, visible_bounds: RectF, cx: &mut PaintContext) {
245 *self = match mem::take(self) {
246 Lifecycle::PostLayout {
247 mut element,
248 constraint,
249 size,
250 mut layout,
251 } => {
252 let bounds = RectF::new(origin, size);
253 let visible_bounds = visible_bounds
254 .intersection(bounds)
255 .unwrap_or_else(|| RectF::new(bounds.origin(), Vector2F::default()));
256 let paint = element.paint(bounds, visible_bounds, &mut layout, cx);
257 Lifecycle::PostPaint {
258 element,
259 constraint,
260 bounds,
261 visible_bounds,
262 layout,
263 paint,
264 }
265 }
266 Lifecycle::PostPaint {
267 mut element,
268 constraint,
269 bounds,
270 mut layout,
271 ..
272 } => {
273 let bounds = RectF::new(origin, bounds.size());
274 let visible_bounds = visible_bounds
275 .intersection(bounds)
276 .unwrap_or_else(|| RectF::new(bounds.origin(), Vector2F::default()));
277 let paint = element.paint(bounds, visible_bounds, &mut layout, cx);
278 Lifecycle::PostPaint {
279 element,
280 constraint,
281 bounds,
282 visible_bounds,
283 layout,
284 paint,
285 }
286 }
287 _ => panic!("invalid element lifecycle state"),
288 }
289 }
290
291 fn dispatch_event(&mut self, event: &Event, cx: &mut EventContext) -> bool {
292 if let Lifecycle::PostPaint {
293 element,
294 bounds,
295 visible_bounds,
296 layout,
297 paint,
298 ..
299 } = self
300 {
301 element.dispatch_event(event, *bounds, *visible_bounds, layout, paint, cx)
302 } else {
303 panic!("invalid element lifecycle state");
304 }
305 }
306
307 fn rect_for_text_range(
308 &self,
309 range_utf16: Range<usize>,
310 cx: &MeasurementContext,
311 ) -> Option<RectF> {
312 if let Lifecycle::PostPaint {
313 element,
314 bounds,
315 visible_bounds,
316 layout,
317 paint,
318 ..
319 } = self
320 {
321 element.rect_for_text_range(range_utf16, *bounds, *visible_bounds, layout, paint, cx)
322 } else {
323 None
324 }
325 }
326
327 fn size(&self) -> Vector2F {
328 match self {
329 Lifecycle::Empty | Lifecycle::Init { .. } => panic!("invalid element lifecycle state"),
330 Lifecycle::PostLayout { size, .. } => *size,
331 Lifecycle::PostPaint { bounds, .. } => bounds.size(),
332 }
333 }
334
335 fn metadata(&self) -> Option<&dyn Any> {
336 match self {
337 Lifecycle::Empty => unreachable!(),
338 Lifecycle::Init { element }
339 | Lifecycle::PostLayout { element, .. }
340 | Lifecycle::PostPaint { element, .. } => element.metadata(),
341 }
342 }
343
344 fn debug(&self, cx: &DebugContext) -> serde_json::Value {
345 match self {
346 Lifecycle::PostPaint {
347 element,
348 constraint,
349 bounds,
350 visible_bounds,
351 layout,
352 paint,
353 } => {
354 let mut value = element.debug(*bounds, layout, paint, cx);
355 if let json::Value::Object(map) = &mut value {
356 let mut new_map: crate::json::Map<String, serde_json::Value> =
357 Default::default();
358 if let Some(typ) = map.remove("type") {
359 new_map.insert("type".into(), typ);
360 }
361 new_map.insert("constraint".into(), constraint.to_json());
362 new_map.insert("bounds".into(), bounds.to_json());
363 new_map.insert("visible_bounds".into(), visible_bounds.to_json());
364 new_map.append(map);
365 json::Value::Object(new_map)
366 } else {
367 value
368 }
369 }
370 _ => panic!("invalid element lifecycle state"),
371 }
372 }
373}
374
375impl<T: Element> Default for Lifecycle<T> {
376 fn default() -> Self {
377 Self::Empty
378 }
379}
380
381impl ElementBox {
382 pub fn name(&self) -> Option<&str> {
383 self.0.name.as_deref()
384 }
385
386 pub fn metadata<T: 'static>(&self) -> Option<&T> {
387 let element = unsafe { &*self.0.element.as_ptr() };
388 element.metadata().and_then(|m| m.downcast_ref())
389 }
390}
391
392impl Into<ElementRc> for ElementBox {
393 fn into(self) -> ElementRc {
394 self.0
395 }
396}
397
398impl Deref for ElementBox {
399 type Target = ElementRc;
400
401 fn deref(&self) -> &Self::Target {
402 &self.0
403 }
404}
405
406impl DerefMut for ElementBox {
407 fn deref_mut(&mut self) -> &mut Self::Target {
408 &mut self.0
409 }
410}
411
412impl ElementRc {
413 pub fn layout(&mut self, constraint: SizeConstraint, cx: &mut LayoutContext) -> Vector2F {
414 self.element.borrow_mut().layout(constraint, cx)
415 }
416
417 pub fn paint(&mut self, origin: Vector2F, visible_bounds: RectF, cx: &mut PaintContext) {
418 self.element.borrow_mut().paint(origin, visible_bounds, cx);
419 }
420
421 pub fn dispatch_event(&mut self, event: &Event, cx: &mut EventContext) -> bool {
422 self.element.borrow_mut().dispatch_event(event, cx)
423 }
424
425 pub fn rect_for_text_range(
426 &self,
427 range_utf16: Range<usize>,
428 cx: &MeasurementContext,
429 ) -> Option<RectF> {
430 self.element.borrow().rect_for_text_range(range_utf16, cx)
431 }
432
433 pub fn size(&self) -> Vector2F {
434 self.element.borrow().size()
435 }
436
437 pub fn debug(&self, cx: &DebugContext) -> json::Value {
438 let mut value = self.element.borrow().debug(cx);
439
440 if let Some(name) = &self.name {
441 if let json::Value::Object(map) = &mut value {
442 let mut new_map: crate::json::Map<String, serde_json::Value> = Default::default();
443 new_map.insert("name".into(), json::Value::String(name.to_string()));
444 new_map.append(map);
445 return json::Value::Object(new_map);
446 }
447 }
448
449 value
450 }
451
452 pub fn with_metadata<T, F, R>(&self, f: F) -> R
453 where
454 T: 'static,
455 F: FnOnce(Option<&T>) -> R,
456 {
457 let element = self.element.borrow();
458 f(element.metadata().and_then(|m| m.downcast_ref()))
459 }
460}
461
462pub trait ParentElement<'a>: Extend<ElementBox> + Sized {
463 fn add_children(&mut self, children: impl IntoIterator<Item = ElementBox>) {
464 self.extend(children);
465 }
466
467 fn add_child(&mut self, child: ElementBox) {
468 self.add_children(Some(child));
469 }
470
471 fn with_children(mut self, children: impl IntoIterator<Item = ElementBox>) -> Self {
472 self.add_children(children);
473 self
474 }
475
476 fn with_child(self, child: ElementBox) -> Self {
477 self.with_children(Some(child))
478 }
479}
480
481impl<'a, T> ParentElement<'a> for T where T: Extend<ElementBox> {}
482
483fn constrain_size_preserving_aspect_ratio(max_size: Vector2F, size: Vector2F) -> Vector2F {
484 if max_size.x().is_infinite() && max_size.y().is_infinite() {
485 size
486 } else if max_size.x().is_infinite() || max_size.x() / max_size.y() > size.x() / size.y() {
487 vec2f(size.x() * max_size.y() / size.y(), max_size.y())
488 } else {
489 vec2f(max_size.x(), size.y() * max_size.x() / size.x())
490 }
491}