1use crate::lvgl;
2use alloc::{string::String, vec::Vec};
3use core::str;
4const UI_ELEMENT_MAX_TEXT_BYTES: usize = 512;
5const UI_ELEMENT_MAX_NAME_BYTES: usize = 128;
6const UI_NAME_MAX_CHILDREN: u32 = 16;
7#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct UiElement {
10 pub id: u32,
12 pub parent_id: Option<u32>,
13 pub role: String,
15 pub semantic_role: Option<&'static str>,
17 pub name: Option<String>,
19 pub text: Option<String>,
21 pub hidden: bool,
23 pub disabled: bool,
25 pub focused: bool,
26 pub clickable: bool,
28 pub checked: Option<bool>,
29 pub bounds: (i32, i32, i32, i32),
31 pub visible: bool,
33 pub clipped_bounds: Option<(i32, i32, i32, i32)>,
34 pub layer: &'static str,
35 pub redacted: bool,
36 pub text_truncated: bool,
37 pub name_truncated: bool,
38 pub state: u32,
39 pub scroll: (i32, i32),
40 pub value: Option<i32>,
41 pub range: Option<(i32, i32)>,
42 pub selected: Option<u32>,
43 pub selected_text: Option<String>,
44 pub selected_text_truncated: bool,
45 pub style: UiStyle,
46 pub buttons: Vec<UiButton>,
47 pub buttons_truncated: bool,
48}
49
50#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct UiTreeSnapshot {
53 pub elements: Vec<UiElement>,
54 pub truncated: bool,
55}
56
57pub(crate) fn semantic_role(class: &str) -> Option<&'static str> {
58 match class {
59 "lv_button" | "lv_list_button" => Some("button"),
60 "lv_textarea" => Some("textbox"),
61 "lv_checkbox" => Some("checkbox"),
62 "lv_switch" => Some("switch"),
63 "lv_slider" => Some("slider"),
64 "lv_dropdown" => Some("combobox"),
65 "lv_label" | "lv_list_text" => Some("text"),
66 "lv_list" => Some("list"),
67 "lv_buttonmatrix" | "lv_keyboard" => Some("buttonmatrix"),
68 "lv_bar" => Some("progressbar"),
69 "lv_arc" => Some("dial"),
70 "lv_roller" => Some("listbox"),
71 "lv_spinbox" => Some("spinbutton"),
72 "lv_tabview" => Some("tablist"),
73 "lv_tileview" => Some("tileview"),
74 "lv_calendar" => Some("calendar"),
75 "lv_chart" => Some("chart"),
76 "lv_canvas" => Some("canvas"),
77 "lv_table" => Some("table"),
78 "lv_image" => Some("image"),
79 "lv_menu" => Some("menu"),
80 "lv_msgbox" => Some("dialog"),
81 _ => None,
82 }
83}
84
85unsafe fn is_hidden_by_ancestor(mut object: *mut lvgl::lv_obj_t) -> bool {
88 while !object.is_null() {
89 if unsafe { lvgl::lv_obj_has_flag(object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN) } {
90 return true;
91 }
92 object = unsafe { lvgl::lv_obj_get_parent(object) };
93 }
94 false
95}
96
97unsafe fn widget_name(object: *mut lvgl::lv_obj_t, semantic_role: Option<&str>) -> Option<String> {
100 unsafe {
101 match semantic_role {
102 Some("textbox") if lvgl::lv_obj_has_class(object, &lvgl::lv_textarea_class) => {
103 bounded_c_string_with_limit(
104 lvgl::lv_textarea_get_placeholder_text(object),
105 UI_ELEMENT_MAX_NAME_BYTES,
106 )
107 }
108 Some("checkbox") if lvgl::lv_obj_has_class(object, &lvgl::lv_checkbox_class) => {
109 bounded_c_string_with_limit(
110 lvgl::lv_checkbox_get_text(object),
111 UI_ELEMENT_MAX_NAME_BYTES,
112 )
113 }
114 Some("button") if lvgl::lv_obj_has_class(object, &lvgl::lv_button_class) => {
115 for index in 0..lvgl::lv_obj_get_child_count(object).min(UI_NAME_MAX_CHILDREN) {
116 let child = lvgl::lv_obj_get_child(object, index as i32);
117 if lvgl::lv_obj_has_class(child, &lvgl::lv_label_class) {
118 return bounded_c_string_with_limit(
119 lvgl::lv_label_get_text(child),
120 UI_ELEMENT_MAX_NAME_BYTES,
121 );
122 }
123 }
124 None
125 }
126 _ => None,
127 }
128 }
129}
130
131pub(crate) unsafe fn inspect_children(
132 object: *mut lvgl::lv_obj_t,
133 parent_id: Option<u32>,
134 depth: usize,
135 limits: (usize, usize),
136 elements: &mut Vec<UiElement>,
137 truncated: &mut bool,
138 layer: &'static str,
139) {
140 let (max_depth, max_elements) = limits;
141 if object.is_null() {
142 return;
143 }
144 if depth >= max_depth || elements.len() >= max_elements {
145 *truncated = true;
146 return;
147 }
148
149 let id = elements.len() as u32;
150 let class = unsafe { lvgl::lv_obj_get_class(object) };
151 let role = if class.is_null() {
152 String::from("unknown")
153 } else {
154 unsafe { bounded_c_string((*class).name) }.unwrap_or_else(|| String::from("unknown"))
155 };
156
157 let mut area = lvgl::lv_area_t::default();
158 unsafe { lvgl::lv_obj_get_coords(object, &mut area) };
159
160 let redacted = unsafe { password_ancestor(object) };
161 let text = if redacted {
162 None
163 } else {
164 unsafe {
165 if lvgl::lv_obj_has_class(object, &lvgl::lv_label_class) {
166 bounded_c_string(lvgl::lv_label_get_text(object))
167 } else if lvgl::lv_obj_has_class(object, &lvgl::lv_textarea_class) {
168 bounded_c_string(lvgl::lv_textarea_get_text(object))
169 } else {
170 None
171 }
172 }
173 };
174
175 let semantic_role = semantic_role(&role);
176 let (name, hidden, disabled, focused, clickable, checked) = unsafe {
177 (
178 if redacted && !lvgl::lv_obj_has_class(object, &lvgl::lv_textarea_class) {
179 None
180 } else {
181 widget_name(object, semantic_role)
182 },
183 is_hidden_by_ancestor(object),
184 lvgl::lv_obj_has_state(object, lvgl::lv_state_t_LV_STATE_DISABLED),
185 lvgl::lv_obj_has_state(object, lvgl::lv_state_t_LV_STATE_FOCUSED),
186 lvgl::lv_obj_has_flag(object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_CLICKABLE),
187 if matches!(semantic_role, Some("checkbox" | "switch")) {
188 Some(lvgl::lv_obj_has_state(
189 object,
190 lvgl::lv_state_t_LV_STATE_CHECKED,
191 ))
192 } else {
193 None
194 },
195 )
196 };
197
198 let clipped_bounds = unsafe { clipped_bounds(object) };
199 let visible = !hidden
200 && clipped_bounds.is_some()
201 && unsafe { lvgl::lv_obj_get_style_opa_recursive(object, 0) } != 0;
202 let WidgetValue {
203 value,
204 range,
205 selected,
206 selected_text,
207 selected_text_truncated,
208 } = if redacted {
209 WidgetValue::default()
210 } else {
211 unsafe { widget_value(object, &role) }
212 };
213 let (buttons, buttons_truncated) = if redacted {
214 (Vec::new(), false)
215 } else {
216 unsafe {
217 matrix_buttons(
218 object,
219 &role,
220 128usize.saturating_sub(elements.iter().map(|e| e.buttons.len()).sum::<usize>()),
221 )
222 }
223 };
224 let text_truncated = !redacted
225 && unsafe {
226 if lvgl::lv_obj_has_class(object, &lvgl::lv_label_class) {
227 was_capped(lvgl::lv_label_get_text(object), UI_ELEMENT_MAX_TEXT_BYTES)
228 } else if lvgl::lv_obj_has_class(object, &lvgl::lv_textarea_class) {
229 was_capped(
230 lvgl::lv_textarea_get_text(object),
231 UI_ELEMENT_MAX_TEXT_BYTES,
232 )
233 } else {
234 false
235 }
236 };
237 let name_truncated = name.is_some()
238 && unsafe {
239 match semantic_role {
240 Some("textbox") => was_capped(
241 lvgl::lv_textarea_get_placeholder_text(object),
242 UI_ELEMENT_MAX_NAME_BYTES,
243 ),
244 Some("checkbox") => was_capped(
245 lvgl::lv_checkbox_get_text(object),
246 UI_ELEMENT_MAX_NAME_BYTES,
247 ),
248 Some("button") => (0..lvgl::lv_obj_get_child_count(object)
249 .min(UI_NAME_MAX_CHILDREN))
250 .find_map(|i| {
251 let child = lvgl::lv_obj_get_child(object, i as i32);
252 lvgl::lv_obj_has_class(child, &lvgl::lv_label_class).then(|| {
253 was_capped(lvgl::lv_label_get_text(child), UI_ELEMENT_MAX_NAME_BYTES)
254 })
255 })
256 .unwrap_or(false),
257 _ => false,
258 }
259 };
260 elements.push(UiElement {
261 id,
262 parent_id,
263 role,
264 semantic_role,
265 name,
266 text,
267 hidden,
268 disabled,
269 focused,
270 clickable,
271 checked,
272 bounds: (area.x1, area.y1, area.x2, area.y2),
273 visible,
274 clipped_bounds,
275 layer,
276 redacted,
277 text_truncated,
278 name_truncated,
279 state: unsafe { lvgl::lv_obj_get_state(object) },
280 scroll: unsafe {
281 (
282 lvgl::lv_obj_get_scroll_x(object),
283 lvgl::lv_obj_get_scroll_y(object),
284 )
285 },
286 value,
287 range,
288 selected,
289 selected_text,
290 selected_text_truncated,
291 style: unsafe { style(object) },
292 buttons,
293 buttons_truncated,
294 });
295
296 let child_count = unsafe { lvgl::lv_obj_get_child_count(object) };
297 if child_count == 0 {
298 return;
299 }
300 if depth + 1 >= max_depth || elements.len() >= max_elements {
301 *truncated = true;
302 return;
303 }
304 for index in 0..child_count {
305 if elements.len() >= max_elements {
306 *truncated = true;
307 break;
308 }
309 let child = unsafe { lvgl::lv_obj_get_child(object, index as i32) };
310 unsafe {
311 inspect_children(
312 child,
313 Some(id),
314 depth + 1,
315 limits,
316 elements,
317 truncated,
318 layer,
319 );
320 }
321 }
322}
323
324unsafe fn bounded_c_string(pointer: *const core::ffi::c_char) -> Option<String> {
326 unsafe { bounded_c_string_with_limit(pointer, UI_ELEMENT_MAX_TEXT_BYTES) }
327}
328
329unsafe fn bounded_c_string_with_limit(
330 pointer: *const core::ffi::c_char,
331 limit: usize,
332) -> Option<String> {
333 if pointer.is_null() {
334 return None;
335 }
336
337 let bytes = pointer.cast::<u8>();
338 let mut length = 0;
339 while length < limit && unsafe { *bytes.add(length) } != 0 {
340 length += 1;
341 }
342
343 let slice = unsafe { core::slice::from_raw_parts(bytes, length) };
344 Some(match str::from_utf8(slice) {
345 Ok(text) => text.into(),
346 Err(error) => String::from_utf8_lossy(&slice[..error.valid_up_to()]).into_owned(),
347 })
348}
349
350#[derive(Clone, Debug, PartialEq, Eq)]
351pub struct UiStyle {
352 pub background: u32,
353 pub text_color: u32,
354 pub border_color: u32,
355 pub opacity: u8,
356 pub background_opacity: u8,
357 pub border_width: i32,
358 pub radius: i32,
359 pub padding: (i32, i32, i32, i32),
360 pub gap: (i32, i32),
361 pub layout: u16,
362 pub font_line_height: i32,
363}
364
365#[derive(Clone, Debug, PartialEq, Eq)]
366pub struct UiButton {
367 pub index: u32,
368 pub text: Option<String>,
369 pub text_truncated: bool,
370 pub bounds: (i32, i32, i32, i32),
371 pub hidden: bool,
372 pub disabled: bool,
373 pub checked: bool,
374}
375
376unsafe fn password_ancestor(mut obj: *mut lvgl::lv_obj_t) -> bool {
377 while !obj.is_null() {
378 if unsafe {
379 lvgl::lv_obj_has_class(obj, &lvgl::lv_textarea_class)
380 && lvgl::lv_textarea_get_password_mode(obj)
381 } {
382 return true;
383 }
384 obj = unsafe { lvgl::lv_obj_get_parent(obj) };
385 }
386 false
387}
388
389unsafe fn clipped_bounds(obj: *mut lvgl::lv_obj_t) -> Option<(i32, i32, i32, i32)> {
392 unsafe {
393 let mut area = lvgl::lv_area_t::default();
394 lvgl::lv_obj_get_coords(obj, &mut area);
395 let display = lvgl::lv_obj_get_display(obj);
396 area.x1 = area.x1.max(0);
397 area.y1 = area.y1.max(0);
398 area.x2 = area
399 .x2
400 .min(lvgl::lv_display_get_horizontal_resolution(display) - 1);
401 area.y2 = area
402 .y2
403 .min(lvgl::lv_display_get_vertical_resolution(display) - 1);
404 let mut parent = lvgl::lv_obj_get_parent(obj);
405 while !parent.is_null() {
406 if !lvgl::lv_obj_has_flag(parent, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_OVERFLOW_VISIBLE) {
407 let mut p = lvgl::lv_area_t::default();
408 lvgl::lv_obj_get_coords(parent, &mut p);
409 area.x1 = area.x1.max(p.x1);
410 area.y1 = area.y1.max(p.y1);
411 area.x2 = area.x2.min(p.x2);
412 area.y2 = area.y2.min(p.y2);
413 }
414 parent = lvgl::lv_obj_get_parent(parent);
415 }
416 (area.x1 <= area.x2 && area.y1 <= area.y2).then_some((area.x1, area.y1, area.x2, area.y2))
417 }
418}
419
420unsafe fn style(obj: *mut lvgl::lv_obj_t) -> UiStyle {
421 unsafe {
422 UiStyle {
423 background: lvgl::lv_color_to_u32(lvgl::lv_obj_get_style_bg_color(obj, 0)),
424 text_color: lvgl::lv_color_to_u32(lvgl::lv_obj_get_style_text_color(obj, 0)),
425 border_color: lvgl::lv_color_to_u32(lvgl::lv_obj_get_style_border_color(obj, 0)),
426 opacity: lvgl::lv_obj_get_style_opa_recursive(obj, 0),
427 background_opacity: lvgl::lv_obj_get_style_bg_opa(obj, 0),
428 border_width: lvgl::lv_obj_get_style_border_width(obj, 0),
429 radius: lvgl::lv_obj_get_style_radius(obj, 0),
430 padding: (
431 lvgl::lv_obj_get_style_pad_top(obj, 0),
432 lvgl::lv_obj_get_style_pad_right(obj, 0),
433 lvgl::lv_obj_get_style_pad_bottom(obj, 0),
434 lvgl::lv_obj_get_style_pad_left(obj, 0),
435 ),
436 gap: (
437 lvgl::lv_obj_get_style_pad_row(obj, 0),
438 lvgl::lv_obj_get_style_pad_column(obj, 0),
439 ),
440 layout: lvgl::lv_obj_get_style_layout(obj, 0),
441 font_line_height: lvgl::lv_font_get_line_height(lvgl::lv_obj_get_style_text_font(
442 obj, 0,
443 )),
444 }
445 }
446}
447
448#[derive(Default)]
449struct WidgetValue {
450 value: Option<i32>,
451 range: Option<(i32, i32)>,
452 selected: Option<u32>,
453 selected_text: Option<String>,
454 selected_text_truncated: bool,
455}
456unsafe fn widget_value(obj: *mut lvgl::lv_obj_t, role: &str) -> WidgetValue {
457 unsafe {
458 let mut data = WidgetValue::default();
459 match role {
460 "lv_slider" => {
461 data.value = Some(lvgl::lv_slider_get_value(obj));
462 data.range = Some((
463 lvgl::lv_slider_get_min_value(obj),
464 lvgl::lv_slider_get_max_value(obj),
465 ));
466 }
467 "lv_bar" => {
468 data.value = Some(lvgl::lv_bar_get_value(obj));
469 data.range = Some((
470 lvgl::lv_bar_get_min_value(obj),
471 lvgl::lv_bar_get_max_value(obj),
472 ));
473 }
474 "lv_arc" => {
475 data.value = Some(lvgl::lv_arc_get_value(obj));
476 data.range = Some((
477 lvgl::lv_arc_get_min_value(obj),
478 lvgl::lv_arc_get_max_value(obj),
479 ));
480 }
481 "lv_spinbox" => data.value = Some(lvgl::lv_spinbox_get_value(obj)),
482 "lv_dropdown" | "lv_roller" => {
483 let mut buffer = [0 as core::ffi::c_char; UI_ELEMENT_MAX_TEXT_BYTES + 4];
484 data.selected = Some(if role == "lv_dropdown" {
485 lvgl::lv_dropdown_get_selected_str(
486 obj,
487 buffer.as_mut_ptr(),
488 buffer.len() as u32,
489 );
490 lvgl::lv_dropdown_get_selected(obj)
491 } else {
492 lvgl::lv_roller_get_selected_str(obj, buffer.as_mut_ptr(), buffer.len() as u32);
493 lvgl::lv_roller_get_selected(obj)
494 });
495 data.selected_text = bounded_c_string(buffer.as_ptr());
496 data.selected_text_truncated =
497 was_capped(buffer.as_ptr(), UI_ELEMENT_MAX_TEXT_BYTES);
498 }
499 "lv_tabview" => data.selected = Some(lvgl::lv_tabview_get_tab_active(obj)),
500 "lv_buttonmatrix" | "lv_keyboard" => {
501 let selected = lvgl::lv_buttonmatrix_get_selected_button(obj);
502 data.selected = (selected != lvgl::LV_BUTTONMATRIX_BUTTON_NONE).then_some(selected);
503 }
504 _ => {}
505 }
506 data
507 }
508}
509
510unsafe fn matrix_buttons(
511 obj: *mut lvgl::lv_obj_t,
512 role: &str,
513 remaining: usize,
514) -> (Vec<UiButton>, bool) {
515 if !matches!(role, "lv_buttonmatrix" | "lv_keyboard") {
516 return (Vec::new(), false);
517 }
518 unsafe {
520 let matrix = &*obj.cast::<lvgl::lv_buttonmatrix_t>();
521 let count = matrix.btn_cnt.min(64).min(remaining as u32);
522 if count == 0 {
523 return (Vec::new(), matrix.btn_cnt > 0);
524 }
525 if matrix.map_p.is_null() || matrix.button_areas.is_null() || matrix.ctrl_bits.is_null() {
526 return (Vec::new(), true);
527 }
528
529 let mut buttons = Vec::with_capacity(count as usize);
530 let mut area = lvgl::lv_area_t::default();
531 lvgl::lv_obj_get_coords(obj, &mut area);
532 for index in 0..count {
533 let text =
534 bounded_c_string_with_limit(lvgl::lv_buttonmatrix_get_button_text(obj, index), 128);
535 let b = *matrix.button_areas.add(index as usize);
536 let flags = *matrix.ctrl_bits.add(index as usize);
537 buttons.push(UiButton {
538 index,
539 text_truncated: was_capped(lvgl::lv_buttonmatrix_get_button_text(obj, index), 128),
540 text,
541 bounds: (
542 area.x1 + b.x1,
543 area.y1 + b.y1,
544 area.x1 + b.x2,
545 area.y1 + b.y2,
546 ),
547 hidden: flags & lvgl::lv_buttonmatrix_ctrl_t_LV_BUTTONMATRIX_CTRL_HIDDEN != 0,
548 disabled: flags & lvgl::lv_buttonmatrix_ctrl_t_LV_BUTTONMATRIX_CTRL_DISABLED != 0,
549 checked: flags & lvgl::lv_buttonmatrix_ctrl_t_LV_BUTTONMATRIX_CTRL_CHECKED != 0,
550 });
551 }
552 (buttons, matrix.btn_cnt > count)
553 }
554}
555
556pub(crate) unsafe fn object_at(
559 root: *mut lvgl::lv_obj_t,
560 index: &mut u32,
561 depth: usize,
562) -> Option<*mut lvgl::lv_obj_t> {
563 if depth >= crate::UI_TREE_MAX_DEPTH {
564 return None;
565 }
566 if *index == 0 {
567 return Some(root);
568 }
569 *index -= 1;
570 unsafe {
571 for child in 0..lvgl::lv_obj_get_child_count(root) {
572 if let Some(obj) =
573 object_at(lvgl::lv_obj_get_child(root, child as i32), index, depth + 1)
574 {
575 return Some(obj);
576 }
577 }
578 }
579 None
580}
581
582unsafe fn was_capped(pointer: *const core::ffi::c_char, limit: usize) -> bool {
583 if pointer.is_null() {
584 return false;
585 }
586 for index in 0..limit {
587 if unsafe { *pointer.add(index) } == 0 {
588 return false;
589 }
590 }
591 true
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598 #[test]
599 fn matrix_with_unallocated_arrays_is_incomplete_not_dereferenced() {
600 let mut matrix = lvgl::lv_buttonmatrix_t {
601 btn_cnt: 1,
602 ..Default::default()
603 };
604 let (buttons, truncated) = unsafe {
605 matrix_buttons(
606 (&mut matrix as *mut lvgl::lv_buttonmatrix_t).cast(),
607 "lv_buttonmatrix",
608 64,
609 )
610 };
611 assert!(buttons.is_empty());
612 assert!(truncated);
613 }
614}