1use crate::{Descriptor, Error, FocusMode, Props, TextKind, TextProps};
4use std::{
5 collections::HashSet,
6 hash::{Hash, Hasher},
7 rc::{Rc, Weak},
8};
9
10pub const MAX_PLAN_NODES: usize = 256;
11
12#[derive(Clone, Debug, PartialEq)]
13pub struct PlanNode {
14 pub parent: Option<usize>,
15 pub descriptor: Descriptor,
16}
17
18#[derive(Clone, Debug)]
19pub struct Plan(Rc<Declaration>);
20#[derive(Clone, Debug)]
21pub struct WeakPlan(Weak<Declaration>);
22
23#[derive(Debug)]
26struct Declaration {
27 nodes: Box<[PlanNode]>,
28 facts: Box<[Facts]>,
29 layers: usize,
30 focus_scopes: usize,
31 semantic_nodes: Box<[usize]>,
32 document_roots: Box<[usize]>,
33 choice_roots: Box<[usize]>,
34 external_options: bool,
35 submission: bool,
36}
37#[derive(Debug)]
38pub(crate) struct Facts {
39 pub layer: bool,
40 pub live_names: bool,
41 pub focus_nodes: u16,
43}
44impl Declaration {
45 fn new(nodes: Vec<PlanNode>) -> Self {
46 let mut facts = Vec::with_capacity(nodes.len());
47 let mut semantic_nodes = Vec::new();
48 let mut document_roots = Vec::new();
49 let mut choice_roots = Vec::new();
50 let mut document_contexts = Vec::with_capacity(nodes.len());
51 let mut choice_contexts = Vec::with_capacity(nodes.len());
52 let mut layers = 0;
53 let mut focus_scopes = 0;
54 let mut external_options = false;
55 let mut submission = true;
56 for (index, node) in nodes.iter().enumerate() {
57 let d = node.descriptor.view();
58 submission &= d.semantics.is_none()
59 && matches!(
60 d.props,
61 Props::View | Props::Text(_) | Props::Button(_) | Props::Link(_)
62 );
63 let layer = d.semantics.as_ref().is_some_and(|s| s.layer.is_some());
64 let focus = crate::focus_scope::declared(d);
65 let live_names = d.semantics.is_some();
66 layers += usize::from(layer);
67 focus_scopes += usize::from(focus);
68 facts.push(Facts {
69 layer,
70 live_names,
71 focus_nodes: u16::from(focus),
72 });
73 if live_names {
74 semantic_nodes.push(index);
75 }
76 let exposed = node.parent.is_none_or(|parent| {
77 document_contexts[parent] && matches!(nodes[parent].descriptor.props, Props::Group)
78 });
79 document_contexts.push(exposed);
80 if exposed {
81 document_roots.push(index);
82 }
83 let owned = node.parent.is_some_and(|parent| choice_contexts[parent]);
84 let option = d.semantics.as_ref().is_some_and(|s| s.option.is_some());
85 if !owned {
86 external_options |= option;
87 if option || d.props.interactive() || d.role == Some(crate::Role::Listbox) {
88 choice_roots.push(index);
89 }
90 }
91 choice_contexts.push(owned || d.role == Some(crate::Role::Listbox));
92 }
93 if focus_scopes > 0 {
94 let mut sizes = vec![1u16; nodes.len()];
95 for (index, node) in nodes.iter().enumerate().rev() {
96 if let Some(parent) = node.parent {
97 sizes[parent] += sizes[index];
98 }
99 if facts[index].focus_nodes != 0 {
100 facts[index].focus_nodes = sizes[index];
101 }
102 }
103 }
104 Self {
105 nodes: nodes.into_boxed_slice(),
106 facts: facts.into_boxed_slice(),
107 layers,
108 focus_scopes,
109 semantic_nodes: semantic_nodes.into_boxed_slice(),
110 document_roots: document_roots.into_boxed_slice(),
111 choice_roots: choice_roots.into_boxed_slice(),
112 external_options,
113 submission,
114 }
115 }
116}
117impl Plan {
118 pub fn new(mut nodes: Vec<PlanNode>) -> Result<Self, Error> {
122 if nodes.is_empty() || nodes.len() > MAX_PLAN_NODES {
123 return Err(Error::InvalidProps("plan requires 1..=256 nodes"));
124 }
125 let mut names = HashSet::new();
126 let mut contexts = Vec::with_capacity(nodes.len());
127 for index in 0..nodes.len() {
128 let parent = nodes[index].parent;
129 if parent.is_none_or(|parent| parent < index) {
130 let mut boxed_parent = parent;
131 while let Some(index) = boxed_parent {
132 if !matches!(nodes[index].descriptor.view().props, Props::Group) {
133 break;
134 }
135 boxed_parent = nodes[index].parent;
136 }
137 crate::document::validate_child(
138 nodes[index].descriptor.view(),
139 boxed_parent.map(|parent| nodes[parent].descriptor.view()),
140 boxed_parent.is_none(),
141 )?;
142 }
143 let (interactive, button, form, tooltip) = match parent {
144 None if index == 0 => (false, false, false, false),
145 Some(parent) if parent < index => {
146 if nodes[parent].descriptor.view().role == Some(crate::Role::Separator) {
147 return Err(Error::InvalidProps(
148 "passive separators cannot contain children",
149 ));
150 }
151 if nodes[index].descriptor.view().field_part() == Some(crate::FieldPart::Legend)
152 && nodes[parent].descriptor.view().field_part()
153 != Some(crate::FieldPart::Fieldset)
154 {
155 return Err(Error::InvalidPlacement(
156 "legend requires a direct fieldset parent",
157 ));
158 }
159 if !nodes[parent].descriptor.view().props.accepts_children() {
160 return Err(Error::InvalidProps("leaf widget cannot contain children"));
161 }
162 contexts[parent]
163 }
164 _ => {
165 return Err(Error::InvalidPlacement(
166 "plan parent must precede its child",
167 ));
168 }
169 };
170 let descriptor = &mut nodes[index].descriptor;
171 descriptor.normalize_input()?;
172 descriptor.validate()?;
173 if form && descriptor.field_part() == Some(crate::FieldPart::Form) {
174 return Err(Error::InvalidPlacement("forms cannot be nested"));
175 }
176 validate_context(descriptor.view(), interactive, button, tooltip)?;
177 if let Some(name) = descriptor.semantic_id()
178 && !names.insert(name.clone())
179 {
180 return Err(Error::InvalidProps("duplicate semantic id"));
181 }
182 contexts.push((
183 interactive
184 || descriptor.props.interactive()
185 || matches!(
186 descriptor.field_part(),
187 Some(crate::FieldPart::Label | crate::FieldPart::Legend)
188 ),
189 button || matches!(descriptor.props, Props::Button(_) | Props::File(_)),
190 form || descriptor.field_part() == Some(crate::FieldPart::Form),
191 tooltip
192 || matches!(
193 descriptor.role,
194 Some(crate::Role::Tooltip | crate::Role::ProgressBar | crate::Role::Slider)
195 ),
196 ));
197 }
198 let plan = Self(Rc::new(Declaration::new(nodes)));
199 crate::choice::validate_plan_owners(&plan, None, true)?;
200 Ok(plan)
201 }
202 pub fn nodes(&self) -> &[PlanNode] {
203 &self.0.nodes
204 }
205 pub(crate) fn supports_submission(&self) -> bool {
206 self.0.submission
207 }
208 pub(crate) fn facts(&self, index: usize) -> &Facts {
209 &self.0.facts[index]
210 }
211 pub(crate) fn layers(&self) -> usize {
212 self.0.layers
213 }
214 pub(crate) fn focus_scopes(&self) -> usize {
215 self.0.focus_scopes
216 }
217 pub fn semantic_nodes(&self) -> &[usize] {
221 &self.0.semantic_nodes
222 }
223 pub(crate) fn document_roots(&self) -> &[usize] {
224 &self.0.document_roots
225 }
226 pub(crate) fn choice_roots(&self) -> &[usize] {
227 &self.0.choice_roots
228 }
229 pub(crate) fn external_options(&self) -> bool {
230 self.0.external_options
231 }
232 pub fn same(&self, other: &Self) -> bool {
233 Rc::ptr_eq(&self.0, &other.0)
234 }
235 pub fn downgrade(&self) -> WeakPlan {
236 WeakPlan(Rc::downgrade(&self.0))
237 }
238 pub fn identity(&self) -> usize {
239 Rc::as_ptr(&self.0) as usize
240 }
241}
242impl WeakPlan {
243 pub fn upgrade(&self) -> Option<Plan> {
244 self.0.upgrade().map(Plan)
245 }
246}
247impl PartialEq for Plan {
248 fn eq(&self, other: &Self) -> bool {
249 self.same(other)
250 }
251}
252impl Eq for Plan {}
253impl Hash for Plan {
254 fn hash<H: Hasher>(&self, state: &mut H) {
255 self.identity().hash(state);
256 }
257}
258
259pub(crate) fn validate_context<'a>(
260 descriptor: impl Into<crate::DescriptorView<'a>>,
261 interactive: bool,
262 button: bool,
263 tooltip: bool,
264) -> Result<(), Error> {
265 let descriptor = descriptor.into();
266 if tooltip
267 && (descriptor.props.interactive()
268 || descriptor.focus != FocusMode::Auto
269 || matches!(
270 descriptor.role,
271 Some(
272 crate::Role::Dialog
273 | crate::Role::AlertDialog
274 | crate::Role::Menu
275 | crate::Role::Toolbar
276 | crate::Role::TabList
277 | crate::Role::RadioGroup
278 )
279 )
280 || descriptor.semantics.as_ref().is_some_and(|s| {
281 s.layer.is_some()
282 || s.navigation.is_some()
283 || s.tab
284 || s.pressed.is_some()
285 || s.popup.is_some()
286 || s.expanded.is_some()
287 || s.menu_item.is_some()
288 || s.menu_search.is_some()
289 || s.form_action.is_some()
290 || s.swipe_capture.is_some()
291 }))
292 {
293 return Err(Error::InvalidProps(
294 "tooltip/progress content must remain passive",
295 ));
296 }
297 if interactive
298 && (descriptor.props.interactive()
299 || descriptor.focus != FocusMode::Auto
300 || descriptor
301 .semantics
302 .as_ref()
303 .is_some_and(|s| s.swipe_capture.is_some()))
304 {
305 return Err(Error::InvalidProps("interactive controls cannot be nested"));
306 }
307 if button
308 && !matches!(
309 descriptor.props,
310 Props::Group
311 | Props::Text(TextProps {
312 kind: TextKind::Inline | TextKind::Code | TextKind::Kbd | TextKind::Mark,
313 ..
314 })
315 | Props::Image(_)
316 | Props::Graphic(_)
317 )
318 {
319 return Err(Error::InvalidProps(
320 "button children must be inline text, images or groups",
321 ));
322 }
323 Ok(())
324}