inkanim_types/ink/widget/
implementation.rs

1use std::fmt::Debug;
2
3use enum_dispatch::enum_dispatch;
4
5use crate::{Name, ink::InkWrapper};
6
7use super::{
8    SiblingOrNested, Widget, WidgetSummary, inkBorderWidget, inkCacheWidget, inkCanvasWidget,
9    inkCircleWidget, inkFlexWidget, inkHorizontalPanelWidget, inkImageWidget, inkMaskWidget,
10    inkMultiChildren, inkRectangleWidget, inkScrollAreaWidget, inkShapeWidget, inkTextWidget,
11    inkUniformGridWidget, inkVectorGraphicWidget, inkVerticalPanelWidget, inkVideoWidget,
12    inkVirtualCompoundWidget, inkWidgetLibraryItem, inkWidgetLibraryItemInstance,
13    inkWidgetLibraryResource,
14};
15
16impl SiblingOrNested for Vec<usize> {
17    fn sibling_or_nested(&self, searched: &[usize]) -> bool {
18        let count_own = self.len();
19        let count_searched = searched.len();
20        if count_searched == 0 {
21            return true;
22        }
23        let last_searched = count_searched - 1;
24        for (i, path_index) in self.iter().enumerate() {
25            if *path_index != searched[i] {
26                return false;
27            }
28            if i == last_searched && count_own >= count_searched {
29                return true;
30            }
31        }
32        false
33    }
34}
35
36macro_rules! impl_ink_children {
37    ($ty:ident) => {
38        impl InkChildren for $ty {
39            fn orphans(&self) -> Vec<Widget> {
40                self.children.data.orphans()
41            }
42
43            fn children(&self) -> Vec<InkWrapper<Widget>> {
44                self.children.data.children()
45            }
46        }
47    };
48}
49
50macro_rules! impl_ink_widget {
51    ($ty:ident) => {
52        impl InkWidget for $ty {
53            fn name(&self) -> &str {
54                self.name.as_str()
55            }
56        }
57    };
58}
59
60macro_rules! impl_leaf_widget {
61    ($ty:ident) => {
62        impl InkLeafWidget for $ty {}
63    };
64}
65
66macro_rules! impl_classname {
67    ($ty:ident) => {
68        impl Classname for $ty {
69            fn classname(&self) -> String {
70                stringify!($ty).to_string()
71            }
72        }
73    };
74}
75
76#[enum_dispatch]
77pub trait Classname {
78    fn classname(&self) -> String;
79}
80
81pub trait InkWidget: Debug {
82    fn name(&self) -> &str;
83}
84
85/// containers which can contain multiple widgets.
86pub trait InkChildren {
87    /// equivalent to `.children()`
88    /// but stripped of their [wrapper](InkWrapper), effectively making them orphans
89    /// (meaning their relative position in the graph cannot be determined anymore).
90    fn orphans(&self) -> Vec<Widget>;
91    /// children [wrappers](InkWrapper),
92    /// which conserve their relative index in the graph.
93    fn children(&self) -> Vec<InkWrapper<Widget>>;
94}
95
96pub trait InkLeafWidget: InkWidget + Debug {}
97
98pub trait InkCompoundWidget: InkWidget + InkChildren + Debug {}
99
100impl<T> InkCompoundWidget for T where T: InkWidget + InkChildren + Debug {}
101
102impl InkChildren for inkMultiChildren {
103    fn orphans(&self) -> Vec<Widget> {
104        self.children.iter().map(|x| x.data.clone()).collect()
105    }
106
107    fn children(&self) -> Vec<InkWrapper<Widget>> {
108        self.children.to_vec()
109    }
110}
111
112impl_ink_children!(inkCanvasWidget);
113impl_ink_children!(inkHorizontalPanelWidget);
114impl_ink_children!(inkVerticalPanelWidget);
115impl_ink_children!(inkScrollAreaWidget);
116impl_ink_children!(inkUniformGridWidget);
117impl_ink_children!(inkVirtualCompoundWidget);
118impl_ink_children!(inkFlexWidget);
119impl_ink_children!(inkCacheWidget);
120
121impl_ink_widget!(inkCanvasWidget);
122impl_ink_widget!(inkHorizontalPanelWidget);
123impl_ink_widget!(inkVerticalPanelWidget);
124impl_ink_widget!(inkScrollAreaWidget);
125impl_ink_widget!(inkUniformGridWidget);
126impl_ink_widget!(inkVirtualCompoundWidget);
127impl_ink_widget!(inkFlexWidget);
128impl_ink_widget!(inkCacheWidget);
129
130impl_ink_widget!(inkTextWidget);
131impl_ink_widget!(inkImageWidget);
132impl_ink_widget!(inkVideoWidget);
133impl_ink_widget!(inkMaskWidget);
134impl_ink_widget!(inkBorderWidget);
135impl_ink_widget!(inkShapeWidget);
136impl_ink_widget!(inkCircleWidget);
137impl_ink_widget!(inkRectangleWidget);
138impl_ink_widget!(inkVectorGraphicWidget);
139
140impl_leaf_widget!(inkTextWidget);
141impl_leaf_widget!(inkImageWidget);
142impl_leaf_widget!(inkVideoWidget);
143impl_leaf_widget!(inkMaskWidget);
144impl_leaf_widget!(inkBorderWidget);
145impl_leaf_widget!(inkShapeWidget);
146impl_leaf_widget!(inkCircleWidget);
147impl_leaf_widget!(inkRectangleWidget);
148impl_leaf_widget!(inkVectorGraphicWidget);
149
150impl_classname!(inkMultiChildren);
151
152impl_classname!(inkCanvasWidget);
153impl_classname!(inkHorizontalPanelWidget);
154impl_classname!(inkVerticalPanelWidget);
155impl_classname!(inkScrollAreaWidget);
156impl_classname!(inkUniformGridWidget);
157impl_classname!(inkVirtualCompoundWidget);
158impl_classname!(inkFlexWidget);
159impl_classname!(inkCacheWidget);
160
161impl_classname!(inkTextWidget);
162impl_classname!(inkImageWidget);
163impl_classname!(inkVideoWidget);
164impl_classname!(inkMaskWidget);
165impl_classname!(inkBorderWidget);
166impl_classname!(inkShapeWidget);
167impl_classname!(inkCircleWidget);
168impl_classname!(inkRectangleWidget);
169impl_classname!(inkVectorGraphicWidget);
170impl Widget {
171    pub fn name(&self) -> Option<&str> {
172        match self {
173            Self::inkMultiChildren(_) => None,
174            Self::inkCanvasWidget(node) => Some(node.name()),
175            Self::inkHorizontalPanelWidget(node) => Some(node.name()),
176            Self::inkVerticalPanelWidget(node) => Some(node.name()),
177            Self::inkScrollAreaWidget(node) => Some(node.name()),
178            Self::inkUniformGridWidget(node) => Some(node.name()),
179            Self::inkVirtualCompoundWidget(node) => Some(node.name()),
180            Self::inkFlexWidget(node) => Some(node.name()),
181            Self::inkCacheWidget(node) => Some(node.name()),
182            Self::inkTextWidget(node) => Some(node.name()),
183            Self::inkImageWidget(node) => Some(node.name()),
184            Self::inkVideoWidget(node) => Some(node.name()),
185            Self::inkMaskWidget(node) => Some(node.name()),
186            Self::inkBorderWidget(node) => Some(node.name()),
187            Self::inkShapeWidget(node) => Some(node.name()),
188            Self::inkCircleWidget(node) => Some(node.name()),
189            Self::inkRectangleWidget(node) => Some(node.name()),
190            Self::inkVectorGraphicWidget(node) => Some(node.name()),
191        }
192    }
193    pub fn as_compound(&self) -> Option<&dyn InkCompoundWidget> {
194        match self {
195            Self::inkCanvasWidget(node) => Some(node),
196            Self::inkHorizontalPanelWidget(node) => Some(node),
197            Self::inkVerticalPanelWidget(node) => Some(node),
198            Self::inkScrollAreaWidget(node) => Some(node),
199            Self::inkUniformGridWidget(node) => Some(node),
200            Self::inkVirtualCompoundWidget(node) => Some(node),
201            Self::inkFlexWidget(node) => Some(node),
202            Self::inkCacheWidget(node) => Some(node),
203            _ => None,
204        }
205    }
206    pub fn as_widget(&self) -> Option<&dyn InkWidget> {
207        match self {
208            Self::inkMultiChildren(_) => None,
209            Self::inkCanvasWidget(widget) => Some(widget),
210            Self::inkHorizontalPanelWidget(widget) => Some(widget),
211            Self::inkVerticalPanelWidget(widget) => Some(widget),
212            Self::inkScrollAreaWidget(widget) => Some(widget),
213            Self::inkUniformGridWidget(widget) => Some(widget),
214            Self::inkVirtualCompoundWidget(widget) => Some(widget),
215            Self::inkFlexWidget(widget) => Some(widget),
216            Self::inkCacheWidget(widget) => Some(widget),
217            Self::inkTextWidget(widget) => Some(widget),
218            Self::inkImageWidget(widget) => Some(widget),
219            Self::inkVideoWidget(widget) => Some(widget),
220            Self::inkMaskWidget(widget) => Some(widget),
221            Self::inkBorderWidget(widget) => Some(widget),
222            Self::inkShapeWidget(widget) => Some(widget),
223            Self::inkCircleWidget(widget) => Some(widget),
224            Self::inkRectangleWidget(widget) => Some(widget),
225            Self::inkVectorGraphicWidget(widget) => Some(widget),
226        }
227    }
228    pub fn as_leaf(&self) -> Option<&dyn InkLeafWidget> {
229        match self {
230            Self::inkTextWidget(widget) => Some(widget),
231            Self::inkImageWidget(widget) => Some(widget),
232            Self::inkVideoWidget(widget) => Some(widget),
233            Self::inkMaskWidget(widget) => Some(widget),
234            Self::inkBorderWidget(widget) => Some(widget),
235            Self::inkShapeWidget(widget) => Some(widget),
236            Self::inkCircleWidget(widget) => Some(widget),
237            Self::inkRectangleWidget(widget) => Some(widget),
238            Self::inkVectorGraphicWidget(widget) => Some(widget),
239            _ => None,
240        }
241    }
242    pub fn is_leaf(&self) -> bool {
243        self.as_leaf().is_some()
244    }
245    pub fn is_compound(&self) -> bool {
246        self.as_compound().is_some()
247    }
248}
249
250pub trait WidgetTree {
251    /// return the widget type
252    fn get_widget_classname(&self, path: &[usize]) -> Option<String>;
253    /// return the full path names to the widget
254    fn get_path_names(&self, path: &[usize]) -> Option<Vec<String>>;
255    /// return the full path indexes to the widget
256    fn get_path_indexes(&self, path: &[&str]) -> Option<Vec<usize>>;
257}
258
259pub trait ByIndex {
260    /// find a widget by index
261    fn by_index(&self, idx: usize) -> Option<Widget>;
262}
263
264pub trait ByName {
265    /// find a widget by name
266    fn by_name(&self, name: &str) -> Option<(usize, Widget)>;
267}
268
269pub trait Leaves {
270    /// get widget summary for elements
271    fn leaves(&self) -> Vec<WidgetSummary>;
272}
273
274impl<T> InkChildren for InkWrapper<T>
275where
276    T: InkChildren,
277{
278    fn orphans(&self) -> Vec<Widget> {
279        self.data.orphans()
280    }
281
282    fn children(&self) -> Vec<InkWrapper<Widget>> {
283        self.data.children()
284    }
285}
286
287impl InkChildren for inkWidgetLibraryItem {
288    fn orphans(&self) -> Vec<Widget> {
289        self.package.data.file.root_chunk.root_widget.orphans()
290    }
291
292    fn children(&self) -> Vec<InkWrapper<Widget>> {
293        self.package.data.file.root_chunk.root_widget.children()
294    }
295}
296
297impl<T> ByIndex for T
298where
299    T: InkChildren,
300{
301    fn by_index(&self, idx: usize) -> Option<Widget> {
302        self.orphans().get(idx).cloned()
303    }
304}
305
306impl<T> ByName for T
307where
308    T: InkChildren,
309{
310    fn by_name(&self, name: &str) -> Option<(usize, Widget)> {
311        for (idx, child) in self.orphans().iter().enumerate() {
312            if let Widget::inkMultiChildren(_) = &child {
313                panic!("unexpected inkMultiChildren with name {name}");
314            }
315            if let Some(compound) = child.as_compound()
316                && compound.name() == name
317            {
318                return Some((idx, child.clone()));
319            }
320            continue;
321        }
322        None
323    }
324}
325
326impl<T> Leaves for T
327where
328    T: InkCompoundWidget,
329{
330    fn leaves(&self) -> Vec<WidgetSummary> {
331        let mut out = vec![];
332        for child in self.children().iter() {
333            if let Some(name) = child.data.name() {
334                out.push(WidgetSummary {
335                    HandleId: child.handle_id,
336                    Name: Name {
337                        r#type: String::from("CName"),
338                        storage: String::from("string"),
339                        value: name.to_string(),
340                    },
341                });
342            }
343        }
344        out
345    }
346}
347
348impl ByName for Vec<InkWrapper<Widget>> {
349    fn by_name(&self, name: &str) -> Option<(usize, Widget)> {
350        for (idx, widget) in self.iter().enumerate() {
351            if let Some(compound) = widget.data.as_compound()
352                && compound.name() == name
353            {
354                return Some((idx, widget.data.clone()));
355            }
356            if let Some(leaf) = widget.data.as_leaf()
357                && leaf.name() == name
358            {
359                return Some((idx, widget.data.clone()));
360            }
361        }
362        None
363    }
364}
365
366impl ByIndex for Vec<InkWrapper<Widget>> {
367    fn by_index(&self, idx: usize) -> Option<Widget> {
368        self.get(idx).map(|x| x.data.clone())
369    }
370}
371
372impl ByName for &dyn InkCompoundWidget {
373    fn by_name(&self, name: &str) -> Option<(usize, Widget)> {
374        self.children().by_name(name)
375    }
376}
377
378impl ByIndex for &dyn InkCompoundWidget {
379    fn by_index(&self, idx: usize) -> Option<Widget> {
380        self.children().by_index(idx)
381    }
382}
383
384impl ByIndex for Widget {
385    fn by_index(&self, idx: usize) -> Option<Widget> {
386        if let Widget::inkMultiChildren(node) = self {
387            return node.by_index(idx);
388        }
389        if let Some(compound) = self.as_compound() {
390            return compound.children().by_index(idx);
391        }
392        Some(self.clone())
393    }
394}
395
396impl WidgetTree for inkWidgetLibraryItemInstance {
397    fn get_widget_classname(&self, path: &[usize]) -> Option<String> {
398        let mut parent: Option<Widget> = Some(Widget::inkMultiChildren(
399            self.root_widget.data.children.data.clone(),
400        ));
401        let last = path.len() - 1;
402        for (i, idx) in path.iter().enumerate() {
403            if parent.is_none() {
404                break;
405            }
406            if let Some(ref child) = parent.as_ref().unwrap().by_index(*idx) {
407                if let Widget::inkMultiChildren(_) = child {
408                    panic!("encountered unexpected inkMultiChildren at index {idx}");
409                }
410                if child.as_compound().is_some() {
411                    if i == last {
412                        return Some(child.classname());
413                    }
414                    parent = Some(child.clone());
415                    continue;
416                }
417                if child.as_leaf().is_some() {
418                    return Some(child.classname());
419                }
420            }
421        }
422        None
423    }
424
425    fn get_path_names(&self, path: &[usize]) -> Option<Vec<String>> {
426        let mut names: Vec<String> = vec![];
427        let mut parent: Option<Widget> = Some(Widget::inkMultiChildren(
428            self.root_widget.data.children.data.clone(),
429        ));
430
431        let depth = path.len() - 1;
432        for (i, idx) in path.iter().enumerate() {
433            if parent.is_none() {
434                break;
435            }
436            if let Some(ref child) = parent.unwrap().by_index(*idx) {
437                if let Some(name) = child.name() {
438                    if child.as_compound().is_some() {
439                        names.push(name.to_string());
440                        parent = Some(child.clone());
441                        continue;
442                    }
443                    if child.as_leaf().is_some() {
444                        names.push(name.to_string());
445                        if i < depth {
446                            return None;
447                        }
448                        break;
449                    }
450                } else {
451                    panic!("encountered unexpected inkMultiChildren at index {idx}");
452                }
453            }
454            return None;
455        }
456        Some(names)
457    }
458
459    fn get_path_indexes(&self, path: &[&str]) -> Option<Vec<usize>> {
460        let mut indexes: Vec<usize> = vec![];
461        let depth = path.len() - 1;
462        let mut parent: Option<Widget> =
463            Some(Widget::inkCanvasWidget(self.root_widget.data.clone()));
464        for (i, name) in path.iter().enumerate() {
465            if parent.is_none() {
466                break;
467            }
468
469            if parent.as_ref().unwrap().is_leaf() {
470                if i < depth {
471                    return None;
472                }
473                break;
474            }
475
476            if let Some(compound) = parent.as_ref().unwrap().as_compound()
477                && let Some((idx, widget)) = compound.by_name(name)
478            {
479                indexes.push(idx);
480                parent = Some(widget);
481                continue;
482            }
483            return None;
484        }
485        Some(indexes)
486    }
487}
488
489impl inkWidgetLibraryResource {
490    pub fn root(&self) -> &inkWidgetLibraryItem {
491        self.library_items.first().expect("Root")
492    }
493    pub fn root_chunk(&self) -> &inkWidgetLibraryItemInstance {
494        &self.root().package.data.file.root_chunk
495    }
496}
497
498impl WidgetTree for inkWidgetLibraryResource {
499    fn get_widget_classname(&self, indexes: &[usize]) -> Option<String> {
500        self.root_chunk().get_widget_classname(indexes)
501    }
502
503    fn get_path_names(&self, indexes: &[usize]) -> Option<Vec<String>> {
504        self.root_chunk().get_path_names(indexes)
505    }
506
507    fn get_path_indexes(&self, names: &[&str]) -> Option<Vec<usize>> {
508        self.root_chunk().get_path_indexes(names)
509    }
510}