Skip to main content

graphics/file_picker/
mod.rs

1//! A graphics-owned, parent-lifetime file chooser. All VFS calls use its captured caller.
2mod model;
3
4use crate::{Error, Result, lvgl};
5use alloc::{boxed::Box, ffi::CString, format, string::String};
6use core::{
7    ffi::CStr,
8    ptr::{self, NonNull},
9};
10use embedded_i18n::t;
11use model::{Browser, MAX_PATH, Model, PAGE_SIZE};
12use synchronization::once_lock::OnceLock;
13use task::TaskIdentifier;
14use virtual_file_system::VirtualFileSystem;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[repr(u32)]
18pub enum FilePickerMode {
19    OpenFile = 0,
20    SaveFile = 1,
21    Directory = 2,
22}
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24#[repr(u32)]
25pub enum FilePickerStatus {
26    Pending = 0,
27    Selected = 1,
28    Cancelled = 2,
29}
30
31const MAX_INPUTS: usize = 8;
32struct ModalFocus {
33    group: *mut lvgl::lv_group_t,
34    inputs: [(*mut lvgl::lv_indev_t, *mut lvgl::lv_group_t); MAX_INPUTS],
35    count: usize,
36}
37impl ModalFocus {
38    unsafe fn capture() -> Result<Self> {
39        unsafe {
40            let mut modal = Self {
41                group: ptr::null_mut(),
42                inputs: [(ptr::null_mut(), ptr::null_mut()); MAX_INPUTS],
43                count: 0,
44            };
45            let mut input = lvgl::lv_indev_get_next(ptr::null_mut());
46            while !input.is_null() {
47                if matches!(
48                    lvgl::lv_indev_get_type(input),
49                    lvgl::lv_indev_type_t_LV_INDEV_TYPE_KEYPAD
50                        | lvgl::lv_indev_type_t_LV_INDEV_TYPE_ENCODER
51                ) {
52                    if modal.count == MAX_INPUTS {
53                        return Err(Error::NotAvailable);
54                    }
55                    modal.inputs[modal.count] = (input, lvgl::lv_indev_get_group(input));
56                    modal.count += 1;
57                }
58                input = lvgl::lv_indev_get_next(input);
59            }
60            modal.group = lvgl::lv_group_create();
61            if modal.group.is_null() {
62                return Err(Error::OutOfMemory);
63            }
64            Ok(modal)
65        }
66    }
67    unsafe fn activate(&self) {
68        for (input, _) in &self.inputs[..self.count] {
69            unsafe {
70                lvgl::lv_indev_set_group(*input, self.group);
71            }
72        }
73    }
74}
75impl ModalFocus {
76    fn release(&mut self) {
77        unsafe {
78            if self.group.is_null() {
79                return;
80            }
81            for (saved_input, saved_group) in &self.inputs[..self.count] {
82                let mut input = lvgl::lv_indev_get_next(ptr::null_mut());
83                while !input.is_null() {
84                    if input == *saved_input && lvgl::lv_indev_get_group(input) == self.group {
85                        let mut group = if saved_group.is_null() {
86                            ptr::null_mut()
87                        } else {
88                            lvgl::lv_group_get_default()
89                        };
90                        for index in 0..lvgl::lv_group_get_count() {
91                            if lvgl::lv_group_by_index(index) == *saved_group {
92                                group = *saved_group;
93                                break;
94                            }
95                        }
96                        lvgl::lv_indev_set_group(input, group);
97                        break;
98                    }
99                    input = lvgl::lv_indev_get_next(input);
100                }
101            }
102            lvgl::lv_group_delete(self.group);
103            self.group = ptr::null_mut();
104        }
105    }
106}
107impl Drop for ModalFocus {
108    fn drop(&mut self) {
109        self.release();
110    }
111}
112struct State {
113    _modal: ModalFocus,
114    vfs: &'static VirtualFileSystem,
115    model: Model,
116    path: *mut lvgl::lv_obj_t,
117    error: *mut lvgl::lv_obj_t,
118    keyboard: *mut lvgl::lv_obj_t,
119    up: *mut lvgl::lv_obj_t,
120    previous: *mut lvgl::lv_obj_t,
121    next: *mut lvgl::lv_obj_t,
122    confirm: *mut lvgl::lv_obj_t,
123    cancel: *mut lvgl::lv_obj_t,
124    rows: [*mut lvgl::lv_obj_t; PAGE_SIZE],
125}
126
127#[repr(C)]
128pub struct FilePicker {
129    object: lvgl::lv_obj_t,
130    state: Option<Box<State>>,
131}
132struct Class(lvgl::lv_obj_class_t);
133unsafe impl Send for Class {}
134unsafe impl Sync for Class {}
135static CLASS: OnceLock<Class> = OnceLock::new();
136pub fn get_file_picker_class() -> &'static lvgl::lv_obj_class_t {
137    &CLASS
138        .get_or_init(|| {
139            let mut class = lvgl::lv_obj_class_t {
140                base_class: unsafe { &lvgl::lv_obj_class },
141                constructor_cb: Some(construct),
142                destructor_cb: Some(destruct),
143                width_def: unsafe { lvgl::lv_pct(100) },
144                height_def: unsafe { lvgl::lv_pct(100) },
145                name: c"file_picker".as_ptr(),
146                ..Default::default()
147            };
148            class.set_instance_size(size_of::<FilePicker>() as _);
149            Class(class)
150        })
151        .0
152}
153unsafe extern "C" fn construct(_: *const lvgl::lv_obj_class_t, object: *mut lvgl::lv_obj_t) {
154    unsafe {
155        ptr::write(&mut (*(object as *mut FilePicker)).state, None);
156    }
157}
158unsafe extern "C" fn destruct(_: *const lvgl::lv_obj_class_t, object: *mut lvgl::lv_obj_t) {
159    unsafe {
160        let state = (*(object as *mut FilePicker)).state.take();
161        drop(state);
162    }
163}
164unsafe fn text(object: *mut lvgl::lv_obj_t, value: &str) {
165    if let Ok(value) = CString::new(value) {
166        unsafe {
167            lvgl::lv_label_set_text(object, value.as_ptr());
168        }
169    }
170}
171unsafe fn button(
172    parent: *mut lvgl::lv_obj_t,
173    value: &str,
174    picker: *mut FilePicker,
175) -> *mut lvgl::lv_obj_t {
176    unsafe {
177        let object = lvgl::lv_button_create(parent);
178        let label = lvgl::lv_label_create(object);
179        text(label, value);
180        lvgl::lv_obj_add_event_cb(
181            object,
182            Some(callback),
183            lvgl::lv_event_code_t_LV_EVENT_CLICKED,
184            picker.cast(),
185        );
186        lvgl::lv_obj_add_event_cb(
187            object,
188            Some(callback),
189            lvgl::lv_event_code_t_LV_EVENT_KEY,
190            picker.cast(),
191        );
192        object
193    }
194}
195unsafe fn hide_private_keyboard(keyboard: *mut lvgl::lv_obj_t) {
196    if !keyboard.is_null() {
197        unsafe {
198            lvgl::lv_keyboard_set_textarea(keyboard, ptr::null_mut());
199            lvgl::lv_obj_add_flag(keyboard, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN);
200        }
201    }
202}
203
204impl FilePicker {
205    /// Create a picker under `parent`; deleting its LVGL parent also drops all Rust state.
206    ///
207    /// # Safety
208    /// `parent` must be a live LVGL object and the graphics lock must be held.
209    pub unsafe fn new(
210        parent: *mut lvgl::lv_obj_t,
211        vfs: &'static VirtualFileSystem,
212        caller: TaskIdentifier,
213        mode: FilePickerMode,
214        initial: &str,
215    ) -> Result<NonNull<Self>> {
216        let initial = model::normalize(initial).map_err(|_| Error::InvalidParameter)?;
217        unsafe {
218            let modal = ModalFocus::capture()?;
219            let object = lvgl::lv_obj_class_create_obj(get_file_picker_class(), parent);
220            let mut picker =
221                NonNull::new(object.cast::<Self>()).ok_or(Error::FailedToCreateObject)?;
222            lvgl::lv_obj_class_init_obj(object);
223            lvgl::lv_obj_add_flag(object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_IGNORE_LAYOUT);
224            lvgl::lv_obj_remove_flag(object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_EVENT_BUBBLE);
225            lvgl::lv_obj_set_size(object, lvgl::lv_pct(100), lvgl::lv_pct(100));
226            lvgl::lv_obj_center(object);
227            lvgl::lv_obj_move_foreground(object);
228            crate::theme::set_surface(object, crate::theme::Surface::Background);
229            lvgl::lv_obj_set_style_bg_opa(object, lvgl::LV_OPA_COVER as _, 0);
230            lvgl::lv_obj_set_flex_flow(object, lvgl::lv_flex_flow_t_LV_FLEX_FLOW_COLUMN);
231            let path = lvgl::lv_textarea_create(object);
232            lvgl::lv_textarea_set_one_line(path, true);
233            lvgl::lv_textarea_set_max_length(path, MAX_PATH as _);
234            lvgl::lv_obj_set_width(path, lvgl::lv_pct(100));
235            lvgl::lv_obj_add_event_cb(
236                path,
237                Some(callback),
238                lvgl::lv_event_code_t_LV_EVENT_ALL,
239                picker.as_ptr().cast(),
240            );
241            let toolbar = lvgl::lv_obj_create(object);
242            lvgl::lv_obj_set_size(toolbar, lvgl::lv_pct(100), lvgl::LV_SIZE_CONTENT as _);
243            lvgl::lv_obj_set_flex_flow(toolbar, lvgl::lv_flex_flow_t_LV_FLEX_FLOW_ROW_WRAP);
244            let up = button(toolbar, t!("file_picker.parent"), picker.as_ptr());
245            let previous = button(toolbar, t!("file_picker.previous"), picker.as_ptr());
246            let next = button(toolbar, t!("file_picker.next"), picker.as_ptr());
247            let confirm = button(
248                toolbar,
249                match mode {
250                    FilePickerMode::OpenFile => t!("file_picker.open"),
251                    FilePickerMode::SaveFile => t!("file_picker.save"),
252                    FilePickerMode::Directory => t!("file_picker.select_directory"),
253                },
254                picker.as_ptr(),
255            );
256            let cancel = button(toolbar, t!("file_picker.cancel"), picker.as_ptr());
257            let error = lvgl::lv_label_create(object);
258            lvgl::lv_obj_set_width(error, lvgl::lv_pct(100));
259            let list = lvgl::lv_obj_create(object);
260            lvgl::lv_obj_set_width(list, lvgl::lv_pct(100));
261            lvgl::lv_obj_set_flex_grow(list, 1);
262            lvgl::lv_obj_set_flex_flow(list, lvgl::lv_flex_flow_t_LV_FLEX_FLOW_COLUMN);
263            let mut rows = [ptr::null_mut(); PAGE_SIZE];
264            for row in &mut rows {
265                *row = button(list, "", picker.as_ptr());
266                lvgl::lv_obj_set_width(*row, lvgl::lv_pct(100));
267            }
268            let keyboard = if crate::on_screen_keyboard::enabled_for(object) {
269                ptr::null_mut()
270            } else {
271                let keyboard = lvgl::lv_keyboard_create(object);
272                lvgl::lv_obj_set_size(keyboard, lvgl::lv_pct(100), 160);
273                lvgl::lv_obj_add_flag(keyboard, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN);
274                lvgl::lv_obj_add_event_cb(
275                    keyboard,
276                    Some(callback),
277                    lvgl::lv_event_code_t_LV_EVENT_ALL,
278                    picker.as_ptr().cast(),
279                );
280                keyboard
281            };
282            lvgl::lv_obj_add_event_cb(
283                object,
284                Some(callback),
285                lvgl::lv_event_code_t_LV_EVENT_KEY,
286                picker.as_ptr().cast(),
287            );
288            for control in [path, up, previous, next, confirm, cancel, keyboard]
289                .into_iter()
290                .chain(rows.iter().copied())
291                .filter(|control| !control.is_null())
292            {
293                lvgl::lv_group_add_obj(modal.group, control);
294            }
295            modal.activate();
296            let state = Box::new(State {
297                _modal: modal,
298                vfs,
299                model: Model::new(caller, mode),
300                path,
301                error,
302                keyboard,
303                up,
304                previous,
305                next,
306                confirm,
307                cancel,
308                rows,
309            });
310            picker.as_mut().state = Some(state);
311            picker.as_mut().reset(mode, &initial)?;
312            Ok(picker)
313        }
314    }
315    /// Reuse this picker and its guest handle for another selection session.
316    /// Clears the previous result while preserving the original VFS and caller.
317    ///
318    /// # Safety
319    /// The graphics lock must be held and this must be a live LVGL picker.
320    pub unsafe fn reset(&mut self, mode: FilePickerMode, initial: &str) -> Result<()> {
321        let initial = model::normalize(initial).map_err(|_| Error::InvalidParameter)?;
322        unsafe {
323            let state = self.state.as_mut().ok_or(Error::InvalidReference)?;
324            if state._modal.group.is_null() {
325                let modal = ModalFocus::capture()?;
326                for control in [
327                    state.path,
328                    state.up,
329                    state.previous,
330                    state.next,
331                    state.confirm,
332                    state.cancel,
333                    state.keyboard,
334                ]
335                .into_iter()
336                .chain(state.rows.iter().copied())
337                .filter(|control| !control.is_null())
338                {
339                    lvgl::lv_group_add_obj(modal.group, control);
340                }
341                state._modal = modal;
342            }
343            state.model = Model::new(state.model.caller, mode);
344            let directory = match state.vfs.kind(state.model.caller, &initial) {
345                Ok(file_system::Kind::Directory) => initial.as_str(),
346                _ => model::parent(&initial),
347            };
348            let result = state.model.navigate(state.vfs, directory, 0);
349            text(
350                lvgl::lv_obj_get_child(state.confirm, 0),
351                match mode {
352                    FilePickerMode::OpenFile => t!("file_picker.open"),
353                    FilePickerMode::SaveFile => t!("file_picker.save"),
354                    FilePickerMode::Directory => t!("file_picker.select_directory"),
355                },
356            );
357            state._modal.activate();
358            let path = state.path;
359            hide_private_keyboard(state.keyboard);
360            self.refresh();
361            lvgl::lv_textarea_set_text(path, CString::new(initial).unwrap().as_ptr());
362            self.show_result(result);
363            lvgl::lv_obj_remove_flag(&mut self.object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN);
364            lvgl::lv_obj_move_foreground(&mut self.object);
365            Ok(())
366        }
367    }
368    pub fn status(&self) -> FilePickerStatus {
369        self.state
370            .as_ref()
371            .map_or(FilePickerStatus::Pending, |s| s.model.status)
372    }
373    pub fn selected_path(&self) -> Option<&str> {
374        self.state.as_ref()?.model.selected.as_deref()
375    }
376    pub fn as_object_mutable(&mut self) -> &mut lvgl::lv_obj_t {
377        &mut self.object
378    }
379    unsafe fn finish(&mut self) {
380        unsafe {
381            if let Some(state) = &mut self.state {
382                state._modal.release();
383                hide_private_keyboard(state.keyboard);
384            }
385            lvgl::lv_obj_add_flag(&mut self.object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN);
386        }
387    }
388    unsafe fn show_result(&mut self, result: virtual_file_system::Result<()>) {
389        if let Some(state) = &self.state {
390            let message = result
391                .err()
392                .map(|error| format!("{}: {}", t!("file_picker.error"), error))
393                .unwrap_or_default();
394            unsafe {
395                text(state.error, &message);
396            }
397        }
398    }
399    unsafe fn refresh(&mut self) {
400        let Some(state) = &mut self.state else {
401            return;
402        };
403        unsafe {
404            lvgl::lv_textarea_set_text(
405                state.path,
406                CString::new(state.model.directory.as_str())
407                    .unwrap()
408                    .as_ptr(),
409            );
410            for (index, row) in state.rows.iter().enumerate() {
411                if let Some(entry) = state.model.page.entries.get(index) {
412                    lvgl::lv_obj_remove_flag(*row, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN);
413                    text(
414                        lvgl::lv_obj_get_child(*row, 0),
415                        &format!(
416                            "{}{}",
417                            entry.name,
418                            if entry.kind == file_system::Kind::Directory {
419                                "/"
420                            } else {
421                                ""
422                            }
423                        ),
424                    );
425                } else {
426                    lvgl::lv_obj_add_flag(*row, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN);
427                }
428            }
429            for (button, enabled) in [
430                (state.previous, state.model.offset > 0),
431                (state.next, state.model.page.more),
432            ] {
433                if enabled {
434                    lvgl::lv_obj_remove_state(button, lvgl::lv_state_t_LV_STATE_DISABLED as _);
435                } else {
436                    lvgl::lv_obj_add_state(button, lvgl::lv_state_t_LV_STATE_DISABLED as _);
437                }
438            }
439        }
440    }
441}
442unsafe extern "C" fn callback(event: *mut lvgl::lv_event_t) {
443    unsafe {
444        let code = lvgl::lv_event_get_code(event);
445        if !matches!(
446            code,
447            lvgl::lv_event_code_t_LV_EVENT_CLICKED
448                | lvgl::lv_event_code_t_LV_EVENT_FOCUSED
449                | lvgl::lv_event_code_t_LV_EVENT_READY
450                | lvgl::lv_event_code_t_LV_EVENT_CANCEL
451                | lvgl::lv_event_code_t_LV_EVENT_KEY
452        ) {
453            return;
454        }
455        let picker = lvgl::lv_event_get_user_data(event).cast::<FilePicker>();
456        if picker.is_null() {
457            return;
458        }
459        let picker = &mut *picker;
460        let Some(state) = &mut picker.state else {
461            return;
462        };
463        if state.model.status != FilePickerStatus::Pending {
464            return;
465        }
466        let target = lvgl::lv_event_get_target_obj(event);
467        let code = lvgl::lv_event_get_code(event);
468        if code == lvgl::lv_event_code_t_LV_EVENT_KEY
469            && lvgl::lv_event_get_key(event) == lvgl::lv_key_t_LV_KEY_ESC
470        {
471            state.model.cancel();
472            picker.finish();
473            return;
474        }
475        if !state.keyboard.is_null()
476            && target == state.path
477            && code == lvgl::lv_event_code_t_LV_EVENT_FOCUSED
478        {
479            lvgl::lv_keyboard_set_textarea(state.keyboard, state.path);
480            lvgl::lv_obj_remove_flag(state.keyboard, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN);
481            return;
482        }
483        if target == state.keyboard
484            && (code == lvgl::lv_event_code_t_LV_EVENT_READY
485                || code == lvgl::lv_event_code_t_LV_EVENT_CANCEL)
486        {
487            lvgl::lv_keyboard_set_textarea(state.keyboard, ptr::null_mut());
488            lvgl::lv_obj_add_flag(state.keyboard, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_HIDDEN);
489            if code == lvgl::lv_event_code_t_LV_EVENT_CANCEL {
490                return;
491            }
492        } else if target == state.keyboard
493            || (code != lvgl::lv_event_code_t_LV_EVENT_CLICKED
494                && !(target == state.path && code == lvgl::lv_event_code_t_LV_EVENT_READY))
495        {
496            return;
497        }
498        if target == state.path && code != lvgl::lv_event_code_t_LV_EVENT_READY {
499            return;
500        }
501        let path = CStr::from_ptr(lvgl::lv_textarea_get_text(state.path))
502            .to_str()
503            .map(String::from);
504        let mut navigated = false;
505        let result = if target == state.cancel {
506            state.model.cancel();
507            Ok(())
508        } else if target == state.confirm
509            || ((target == state.path || target == state.keyboard)
510                && code == lvgl::lv_event_code_t_LV_EVENT_READY)
511        {
512            path.map_err(|_| virtual_file_system::IoErrorKind::InvalidPath)
513                .and_then(|path| state.model.activate(state.vfs, &path))
514                .map(|did_navigate| {
515                    navigated = did_navigate;
516                })
517        } else {
518            let (destination, offset) = if target == state.up {
519                (String::from(model::parent(&state.model.directory)), 0)
520            } else if target == state.previous {
521                (
522                    state.model.directory.clone(),
523                    state.model.offset.saturating_sub(PAGE_SIZE),
524                )
525            } else if target == state.next {
526                (
527                    state.model.directory.clone(),
528                    state.model.offset.saturating_add(PAGE_SIZE),
529                )
530            } else if let Some(index) = state.rows.iter().position(|row| *row == target) {
531                let Some(entry) = state.model.page.entries.get(index) else {
532                    return;
533                };
534                let destination = format!(
535                    "{}/{}",
536                    state.model.directory.trim_end_matches('/'),
537                    entry.name
538                );
539                let destination = match model::normalize(&destination) {
540                    Ok(destination) => destination,
541                    Err(error) => {
542                        picker.show_result(Err(error));
543                        return;
544                    }
545                };
546                match state.vfs.kind(state.model.caller, &destination) {
547                    Ok(file_system::Kind::Directory) => {}
548                    Ok(_) => {
549                        if let Ok(value) = CString::new(destination) {
550                            lvgl::lv_textarea_set_text(state.path, value.as_ptr());
551                        }
552                        return;
553                    }
554                    Err(error) => {
555                        picker.show_result(Err(error));
556                        return;
557                    }
558                }
559                (destination, 0)
560            } else {
561                match path {
562                    Ok(path) => (path, 0),
563                    Err(_) => {
564                        picker.show_result(Err(virtual_file_system::IoErrorKind::InvalidPath));
565                        return;
566                    }
567                }
568            };
569            let result = state.model.navigate(state.vfs, &destination, offset);
570            navigated = result.is_ok();
571            result
572        };
573        if navigated {
574            picker.refresh();
575        }
576        picker.show_result(result);
577        if picker.status() != FilePickerStatus::Pending {
578            picker.finish();
579        }
580    }
581}