Merge branch 'nickez-agent/zeroizing-labels-textarea'
What changed, and why it matters
This commit replaces several LVGL UI widgets (label, textarea, keyboard) with custom Rust reimplementations whose main goal is to automatically erase sensitive text from memory when it is no longer needed. It also disables unused LVGL widgets and switches many UI call sites to the new widgets. The change is defensive: it reduces the chance that passwords, recovery words, or PINs remain in RAM after use. Because it is a large rewrite of UI code, it also carries the usual risks of new logic bugs, but the diff itself does not show an exploitable vulnerability.
Treat this as a security-hardening change rather than a vulnerability fix. Reviewers should focus on correctness of the new Rust widget implementations, especially memory/lifetime safety of Rc user-data, weak-handle invalidation after deletion, event-callback re-entrancy, and whether any remaining LVGL text buffers still hold secrets. Run UI tests and simulator tests, and verify that all secret-entry screens use the new zeroizing widgets.
Security signals we found
Introduction of zeroize-backed text storage for UI labels/textareas/keyboards
Replacement of LVGL label/textarea/keyboard widgets with Rust reimplementations
Disabling of unused LVGL widgets in lv_conf.h to reduce attack surface
Removal of in-place LVGL buffer reads for secret text in favor of zeroizing snapshots
Large refactor of UI code with new event handling, draw callbacks and weak-handle lifetime management
Evidence from the diff
The merge introduces ZeroizingText/Zeroizing wrappers around label, textarea and keyboard text buffers, backed by the zeroize crate, and reimplements BitboxLabel, BitboxTextarea and BitboxKeyboard in Rust on top of lower-level LVGL primitives. LVGL’s own label/textarea/keyboard implementations are disabled in lv_conf.h. The Rust code owns the text state in Rc
Changed components
src/rust/bitbox-lvgl/src/widgets/label.rssrc/rust/bitbox-lvgl/src/widgets/textarea.rssrc/rust/bitbox-lvgl/src/widgets/keyboard.rssrc/rust/bitbox-lvgl/src/text.rssrc/rust/bitbox-lvgl/src/widgets/util.rssrc/rust/bitbox-lvgl-sys/widgets.csrc/rust/bitbox-lvgl-sys/lv_conf.hsrc/rust/bitbox03/src/ui/*.rsInspect captured patch +1831 / −703
### src/rust/Cargo.lock
@@ -225,6 +225,7 @@ dependencies = [
"grounded",
"tracing",
"util",
+ "zeroize",
]
[[package]]
### src/rust/bitbox-lvgl-sys/build.rs
@@ -255,6 +255,9 @@ fn main() -> Result<(), &'static str> {
let out_path = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")).join("bindings.rs");
let mut lvgl_build = cc::Build::new();
+ let widgets = manifest_dir.join("widgets.c");
+ println!("cargo::rerun-if-changed={}", widgets.display());
+ lvgl_build.file(widgets);
for source in LVGL_C_FILES {
lvgl_build.file(lvgl_dir.join(source));
}
### src/rust/bitbox-lvgl-sys/lv_conf.h
@@ -723,7 +723,7 @@
#define LV_USE_BUTTONMATRIX 1
-#define LV_USE_CALENDAR 1
+#define LV_USE_CALENDAR 0
#if LV_USE_CALENDAR
#define LV_CALENDAR_WEEK_STARTS_MONDAY 0
#define LV_USE_CALENDAR_HEADER_ARROW 1
@@ -737,15 +737,15 @@
#define LV_USE_CHECKBOX 1
-#define LV_USE_DROPDOWN 1 /**< Requires: lv_label */
+#define LV_USE_DROPDOWN 0 /**< Requires: lv_label */
#define LV_USE_IMAGE 1
#define LV_USE_IMAGEBUTTON 1
-#define LV_USE_KEYBOARD 1
+#define LV_USE_KEYBOARD 0
-#define LV_USE_LABEL 1
+#define LV_USE_LABEL 0
#if LV_USE_LABEL
#define LV_LABEL_TEXT_SELECTION 1 /**< Enable selecting text of the label */
#define LV_LABEL_LONG_TXT_HINT 1 /**< Store some extra info in labels to speed up drawing of very long text */
@@ -756,15 +756,15 @@
#define LV_USE_LINE 1
-#define LV_USE_LIST 1
+#define LV_USE_LIST 0
#define LV_USE_LOTTIE 0 /**< Requires: lv_canvas, thorvg */
-#define LV_USE_MENU 1
+#define LV_USE_MENU 0
-#define LV_USE_MSGBOX 1
+#define LV_USE_MSGBOX 0
-#define LV_USE_ROLLER 1 /**< Requires: lv_label */
+#define LV_USE_ROLLER 0 /**< Requires: lv_label */
#define LV_USE_SCALE 1
@@ -776,24 +776,24 @@
#define LV_SPAN_SNIPPET_STACK_SIZE 64
#endif
-#define LV_USE_SPINBOX 1
+#define LV_USE_SPINBOX 0
#define LV_USE_SPINNER 1
#define LV_USE_SWITCH 1
-#define LV_USE_TABLE 1
+#define LV_USE_TABLE 0
-#define LV_USE_TABVIEW 1
+#define LV_USE_TABVIEW 0
-#define LV_USE_TEXTAREA 1 /**< Requires: lv_label */
+#define LV_USE_TEXTAREA 0 /**< Requires: lv_label */
#if LV_USE_TEXTAREA != 0
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /**< [ms] */
#endif
#define LV_USE_TILEVIEW 1
-#define LV_USE_WIN 1
+#define LV_USE_WIN 0
#define LV_USE_3DTEXTURE 0
### src/rust/bitbox-lvgl-sys/widgets.c
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: Apache-2.0
+
+#include <lvgl.h>
+#include <src/core/lv_obj_class_private.h>
+
+extern void bitbox_lv_widget_destructor(const lv_obj_class_t* class_p, lv_obj_t* obj);
+
+const lv_obj_class_t bitbox_lv_label_class = {
+ .base_class = &lv_obj_class,
+ .destructor_cb = bitbox_lv_widget_destructor,
+ .width_def = LV_SIZE_CONTENT,
+ .height_def = LV_SIZE_CONTENT,
+ .name = "bitbox_label",
+};
+
+const lv_obj_class_t bitbox_lv_textarea_class = {
+ .base_class = &lv_obj_class,
+ .destructor_cb = bitbox_lv_widget_destructor,
+ .theme_inheritable = LV_OBJ_CLASS_THEME_INHERITABLE_TRUE,
+ .name = "bitbox_textarea",
+};
+
+const lv_obj_class_t bitbox_lv_keyboard_class = {
+ .base_class = &lv_buttonmatrix_class,
+ .destructor_cb = bitbox_lv_widget_destructor,
+ .theme_inheritable = LV_OBJ_CLASS_THEME_INHERITABLE_TRUE,
+ .name = "bitbox_keyboard",
+};
### src/rust/bitbox-lvgl-sys/wrapper.h
@@ -1,6 +1,11 @@
// SPDX-License-Identifier: Apache-2.0
#include <lvgl.h>
+#include <src/misc/lv_text_private.h>
+
+extern const lv_obj_class_t bitbox_lv_label_class;
+extern const lv_obj_class_t bitbox_lv_textarea_class;
+extern const lv_obj_class_t bitbox_lv_keyboard_class;
extern const lv_font_t inter_regular_24;
extern const lv_font_t inter_regular_32;
### src/rust/bitbox-lvgl/Cargo.toml
@@ -7,4 +7,5 @@ edition = "2024"
bitbox-lvgl-sys = { path = "../bitbox-lvgl-sys" }
grounded = {version = "0.2.1"}
util = { path = "../util" }
+zeroize = { workspace = true }
tracing = {version = "0.1.41", features = ["log"], default-features = false}
### src/rust/bitbox-lvgl/src/lib.rs
@@ -34,8 +34,6 @@ pub use ffi::lv_image_align_t as LvImageAlign;
pub use ffi::lv_image_dsc_t as LvImageDsc;
pub use ffi::lv_indev_state_t as LvIndevState;
pub use ffi::lv_indev_type_t as LvIndevType;
-pub use ffi::lv_keyboard_mode_t as LvKeyboardMode;
-pub use ffi::lv_label_long_mode_t as LvLabelLongMode;
pub use ffi::lv_layout_t as LvLayout;
pub use ffi::lv_log_level_t as LvLogLevel;
pub use ffi::lv_obj_flag_t as LvObjFlag;
@@ -60,6 +58,8 @@ pub mod indev;
pub mod log;
pub mod style;
pub mod system;
+mod text;
+pub use text::ZeroizingText;
#[cfg(test)]
mod test_util;
pub mod tick;
@@ -80,14 +80,16 @@ pub use widgets::canvas::CanvasExt;
pub use widgets::canvas::{LvCanvas, LvCanvasCreateError};
pub use widgets::class;
pub use widgets::image::ImageExt;
-pub use widgets::keyboard::{KeyboardExt, LvKeyboard, LvKeyboardMapEntry, keyboard_def_event_cb};
-pub use widgets::label::{LabelExt, LvLabel, LvLabelTextError};
+pub use widgets::keyboard::{
+ BitboxKeyboard, BitboxKeyboardMapEntry, BitboxKeyboardMode, KeyboardExt,
+};
+pub use widgets::label::{BitboxLabel, BitboxLabelLongMode, BitboxLabelTextError, LabelExt};
pub use widgets::line::LvLine;
pub use widgets::obj;
pub use widgets::obj::LvObj;
pub use widgets::obj::{LvHandle, LvTypeError, ObjExt};
pub use widgets::slider::{LvSlider, SliderExt};
pub use widgets::span::{LvSpan, LvSpanTextError, LvSpangroup, SpangroupExt};
pub use widgets::spinner::{LvSpinner, SpinnerExt};
-pub use widgets::textarea::{LvTextarea, LvTextareaTextError, TextareaExt};
+pub use widgets::textarea::{BitboxTextarea, BitboxTextareaTextError, TextareaExt};
pub use widgets::{LvEventRegistrationError, LvMapError, LvTextError};
### src/rust/bitbox-lvgl/src/text.rs
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+
+use alloc::{boxed::Box, vec};
+use core::ffi::CStr;
+use core::ops::Deref;
+use zeroize::Zeroizing;
+
+use crate::LvTextError;
+
+/// An owned text snapshot that wipes its allocation when dropped.
+///
+/// Temporary strings and snapshots crossing the LVGL boundary use this type so their
+/// Rust-owned storage is wiped automatically. Labels also retain this storage for display.
+pub struct ZeroizingText(Zeroizing<Box<[u8]>>);
+
+impl ZeroizingText {
+ pub(crate) fn new(text: &str) -> Result<Self, LvTextError> {
+ // Validate before copying, including on the error path.
+ if text.as_bytes().contains(&0) {
+ return Err(LvTextError::ContainsNul);
+ }
+ // Finish allocating the final buffer before copying sensitive text.
+ let mut bytes = Zeroizing::new(vec![0; text.len() + 1].into_boxed_slice());
+ bytes[..text.len()].copy_from_slice(text.as_bytes());
+ Ok(Self(bytes))
+ }
+
+ pub(crate) fn from_cstr(text: &CStr) -> Self {
+ Self(Zeroizing::new(Box::from(text.to_bytes_with_nul())))
+ }
+}
+
+impl Deref for ZeroizingText {
+ type Target = CStr;
+
+ fn deref(&self) -> &CStr {
+ // Both constructors store exactly one trailing NUL, with no interior NULs.
+ unsafe { CStr::from_bytes_with_nul_unchecked(self.0.as_ref()) }
+ }
+}
+
+impl AsRef<CStr> for ZeroizingText {
+ fn as_ref(&self) -> &CStr {
+ self
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_new() {
+ for value in ["", "recovery words", "öäü"] {
+ let text = ZeroizingText::new(value).unwrap();
+ assert_eq!(text.to_str().unwrap(), value);
+ assert_eq!(text.to_bytes_with_nul().len(), value.len() + 1);
+ }
+ assert!(matches!(
+ ZeroizingText::new("secret\0suffix"),
+ Err(LvTextError::ContainsNul)
+ ));
+ }
+}
### src/rust/bitbox-lvgl/src/widgets/buttonmatrix.rs
@@ -1,12 +1,10 @@
// SPDX-License-Identifier: Apache-2.0
-use alloc::borrow::ToOwned;
-use alloc::ffi::CString;
use alloc::vec::Vec;
use core::ffi::{CStr, c_char};
use core::ptr::NonNull;
-use crate::{LvButtonmatrixCtrl, LvHandle, LvObj, ObjExt, class, ffi};
+use crate::{LvButtonmatrixCtrl, LvHandle, LvObj, ObjExt, ZeroizingText, class, ffi};
use util::strings::{cstr_array_from_ptr, optional_cstr_from_ptr};
pub type LvButtonmatrix = LvHandle<class::ButtonmatrixTag>;
@@ -20,7 +18,7 @@ impl LvButtonmatrixMapEntry {
Self(value.as_ptr())
}
- fn as_cstr(self) -> &'static CStr {
+ pub fn as_cstr(self) -> &'static CStr {
unsafe { CStr::from_ptr(self.0) }
}
@@ -103,11 +101,11 @@ pub trait ButtonmatrixExt: ObjExt {
unsafe { ffi::lv_buttonmatrix_set_one_checked(self.as_ptr(), enable) }
}
- fn get_map(&self) -> Vec<CString> {
+ fn get_map(&self) -> Vec<ZeroizingText> {
unsafe {
cstr_array_from_ptr(ffi::lv_buttonmatrix_get_map(self.as_ptr()))
.into_iter()
- .map(|entry| entry.to_owned())
+ .map(ZeroizingText::from_cstr)
.collect()
}
}
@@ -116,13 +114,13 @@ pub trait ButtonmatrixExt: ObjExt {
unsafe { ffi::lv_buttonmatrix_get_selected_button(self.as_ptr()) }
}
- fn get_button_text(&self, button_id: u32) -> Option<CString> {
+ fn get_button_text(&self, button_id: u32) -> Option<ZeroizingText> {
unsafe {
optional_cstr_from_ptr(ffi::lv_buttonmatrix_get_button_text(
self.as_ptr(),
button_id,
))
- .map(|text| text.to_owned())
+ .map(ZeroizingText::from_cstr)
}
}
### src/rust/bitbox-lvgl/src/widgets/class.rs
@@ -60,7 +60,7 @@ macro_rules! impl_lv_class {
}
impl_lv_class!(ObjTag, lv_obj_class);
-impl_lv_class!(LabelTag, lv_label_class);
+impl_lv_class!(LabelTag, bitbox_lv_label_class);
impl_lv_class!(ImageTag, lv_image_class);
impl_lv_class!(CanvasTag, lv_canvas_class);
impl_lv_class!(ArcTag, lv_arc_class);
@@ -69,9 +69,9 @@ impl_lv_class!(ButtonTag, lv_button_class);
impl_lv_class!(BarTag, lv_bar_class);
impl_lv_class!(SliderTag, lv_slider_class);
impl_lv_class!(SpangroupTag, lv_spangroup_class);
-impl_lv_class!(TextareaTag, lv_textarea_class);
+impl_lv_class!(TextareaTag, bitbox_lv_textarea_class);
impl_lv_class!(ButtonmatrixTag, lv_buttonmatrix_class);
-impl_lv_class!(KeyboardTag, lv_keyboard_class);
+impl_lv_class!(KeyboardTag, bitbox_lv_keyboard_class);
impl_lv_class!(LineTag, lv_line_class);
#[cfg(test)]
### src/rust/bitbox-lvgl/src/widgets/keyboard.rs
@@ -1,46 +1,114 @@
// SPDX-License-Identifier: Apache-2.0
-use alloc::borrow::ToOwned;
-use alloc::ffi::CString;
-use alloc::vec::Vec;
-use core::ptr::NonNull;
+//! A Rust reimplementation of LVGL's keyboard widget using `lv_buttonmatrix`.
+//!
+//! Edits [`BitboxTextarea`] through Rust event handlers.
+
+use alloc::{rc::Rc, vec::Vec};
+use core::{cell::RefCell, ptr::NonNull};
use super::buttonmatrix::{ButtonmatrixExt, LvButtonmatrix, LvButtonmatrixMapEntry, validate_map};
-use super::textarea::LvTextarea;
-use crate::{LvButtonmatrixCtrl, LvHandle, LvKeyboardMode, LvObj, class, ffi};
-use util::strings::{cstr_array_from_ptr, optional_cstr_from_ptr};
+use super::textarea::{BitboxTextarea, TextareaExt};
+use crate::{LvButtonmatrixCtrl, LvHandle, LvObj, ObjExt, ZeroizingText, class, ffi};
-pub type LvKeyboard = LvHandle<class::KeyboardTag>;
-pub type LvKeyboardMapEntry = LvButtonmatrixMapEntry;
+pub type BitboxKeyboard = LvHandle<class::KeyboardTag>;
+pub type BitboxKeyboardMapEntry = LvButtonmatrixMapEntry;
-pub trait KeyboardExt: ButtonmatrixExt {
- /// # Safety
- ///
- /// LVGL stores the textarea pointer and dereferences it later during keyboard event handling.
- /// Callers must ensure the textarea outlives the keyboard attachment or is detached before the
- /// textarea is deleted.
- unsafe fn set_textarea(&self, textarea: Option<&LvTextarea>) {
- unsafe {
- ffi::lv_keyboard_set_textarea(
- self.as_ptr(),
- textarea.map_or(core::ptr::null_mut(), LvHandle::as_ptr),
- )
- }
- }
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BitboxKeyboardMode {
+ Number,
+ User1,
+ User2,
+ User3,
+ User4,
+}
+
+#[derive(Clone, Copy)]
+struct Map {
+ keys: &'static [BitboxKeyboardMapEntry],
+ controls: &'static [LvButtonmatrixCtrl],
+}
+
+struct State {
+ mode: BitboxKeyboardMode,
+ maps: [Option<Map>; 5],
+}
- fn set_mode(&self, mode: LvKeyboardMode) {
- unsafe { ffi::lv_keyboard_set_mode(self.as_ptr(), mode) }
+const fn symbol(bytes: &'static [u8]) -> BitboxKeyboardMapEntry {
+ match core::ffi::CStr::from_bytes_with_nul(bytes) {
+ Ok(text) => BitboxKeyboardMapEntry::new(text),
+ Err(_) => panic!("invalid LVGL symbol"),
}
+}
+
+const NUMBER_MAP: Map = Map {
+ keys: &[
+ BitboxKeyboardMapEntry::new(c"1"),
+ BitboxKeyboardMapEntry::new(c"2"),
+ BitboxKeyboardMapEntry::new(c"3"),
+ symbol(ffi::LV_SYMBOL_KEYBOARD),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"4"),
+ BitboxKeyboardMapEntry::new(c"5"),
+ BitboxKeyboardMapEntry::new(c"6"),
+ symbol(ffi::LV_SYMBOL_OK),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"7"),
+ BitboxKeyboardMapEntry::new(c"8"),
+ BitboxKeyboardMapEntry::new(c"9"),
+ symbol(ffi::LV_SYMBOL_BACKSPACE),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"+/-"),
+ BitboxKeyboardMapEntry::new(c"0"),
+ BitboxKeyboardMapEntry::new(c"."),
+ symbol(ffi::LV_SYMBOL_LEFT),
+ symbol(ffi::LV_SYMBOL_RIGHT),
+ BitboxKeyboardMapEntry::new(c""),
+ ],
+ controls: &number_controls(),
+};
- fn set_popovers(&self, enable: bool) {
- unsafe { ffi::lv_keyboard_set_popovers(self.as_ptr(), enable) }
+const fn number_controls() -> [LvButtonmatrixCtrl; 17] {
+ let mut controls = [LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_WIDTH_1; 17];
+ controls[3] = LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_WIDTH_2;
+ controls[7] = LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_WIDTH_2;
+ controls[11] = LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_WIDTH_2;
+ controls
+}
+
+fn state(obj: *mut ffi::lv_obj_t) -> Rc<RefCell<State>> {
+ unsafe { super::util::widget_state::<class::KeyboardTag, RefCell<State>>(obj) }
+}
+
+pub trait KeyboardExt: ButtonmatrixExt {
+ fn set_mode(&self, mode: BitboxKeyboardMode) {
+ let map = {
+ let state = state(self.as_ptr());
+ let mut state = state.borrow_mut();
+ let map = state.maps[mode as usize].expect("keyboard mode has no map");
+ state.mode = mode;
+ map
+ };
+ ButtonmatrixExt::set_map(self, map.keys);
+ self.set_ctrl_map(map.controls);
+ if mode == BitboxKeyboardMode::Number {
+ for id in [3, 7] {
+ for ctrl in [
+ LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_NO_REPEAT,
+ LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_CLICK_TRIG,
+ LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_CHECKED,
+ ] {
+ self.set_button_ctrl(id, ctrl);
+ }
+ }
+ }
}
/// `map` must be a `'static` LVGL keyboard map terminated by an empty string.
fn set_map(
&self,
- mode: LvKeyboardMode,
- map: &'static [LvKeyboardMapEntry],
+ mode: BitboxKeyboardMode,
+ map: &'static [BitboxKeyboardMapEntry],
ctrl_map: &'static [LvButtonmatrixCtrl],
) {
let button_count = validate_map(map);
@@ -49,48 +117,106 @@ pub trait KeyboardExt: ButtonmatrixExt {
button_count,
"LVGL keyboard control map length must match the number of buttons in the map"
);
- unsafe {
- ffi::lv_keyboard_set_map(self.as_ptr(), mode, map.as_ptr().cast(), ctrl_map.as_ptr())
+ state(self.as_ptr()).borrow_mut().maps[mode as usize] = Some(Map {
+ keys: map,
+ controls: ctrl_map,
+ });
+ if self.get_mode() == mode {
+ self.set_mode(mode);
}
}
- fn get_textarea(&self) -> Option<LvTextarea> {
- NonNull::new(unsafe { ffi::lv_keyboard_get_textarea(self.as_ptr()) })
- .map(LvHandle::from_ptr)
+ fn get_mode(&self) -> BitboxKeyboardMode {
+ state(self.as_ptr()).borrow().mode
}
- fn get_mode(&self) -> LvKeyboardMode {
- unsafe { ffi::lv_keyboard_get_mode(self.as_ptr()) }
- }
-
- fn get_popovers(&self) -> bool {
- unsafe { ffi::lv_keyboard_get_popovers(self.as_ptr()) }
- }
-
- fn get_map_array(&self) -> Vec<CString> {
- unsafe {
- cstr_array_from_ptr(ffi::lv_keyboard_get_map_array(self.as_ptr()))
- .into_iter()
- .map(|entry| entry.to_owned())
- .collect()
- }
+ fn get_map_array(&self) -> Vec<ZeroizingText> {
+ self.get_map()
}
}
impl LvHandle<class::KeyboardTag> {
+ /// Adds input handling for a Rust textarea. Deleting the textarea disables the binding.
+ pub fn bind_textarea(
+ &self,
+ textarea: &BitboxTextarea,
+ ) -> Result<(), crate::LvEventRegistrationError> {
+ let textarea = textarea.weak_handle();
+ let keyboard = Self::from_ptr(NonNull::new(self.as_ptr()).unwrap());
+ self.add_event_cb(crate::LvEventCode::LV_EVENT_VALUE_CHANGED, move || {
+ let Some(text) = keyboard.get_button_text(keyboard.get_selected_button()) else {
+ return;
+ };
+ let text = text.to_str().unwrap();
+ let symbol = |bytes: &[u8]| {
+ core::ffi::CStr::from_bytes_with_nul(bytes)
+ .unwrap()
+ .to_bytes()
+ == text.as_bytes()
+ };
+ let event = if text == "Enter"
+ || symbol(ffi::LV_SYMBOL_NEW_LINE)
+ || symbol(ffi::LV_SYMBOL_OK)
+ {
+ Some(crate::LvEventCode::LV_EVENT_READY)
+ } else if symbol(ffi::LV_SYMBOL_CLOSE) || symbol(ffi::LV_SYMBOL_KEYBOARD) {
+ Some(crate::LvEventCode::LV_EVENT_CANCEL)
+ } else {
+ None
+ };
+ if let Some(event) = event {
+ if unsafe {
+ ffi::lv_obj_send_event(keyboard.as_ptr(), event, core::ptr::null_mut())
+ } != ffi::lv_result_t::LV_RESULT_OK
+ {
+ return;
+ }
+ if let Some(textarea) = textarea() {
+ unsafe {
+ ffi::lv_obj_send_event(textarea.as_ptr(), event, core::ptr::null_mut());
+ }
+ }
+ return;
+ }
+ let Some(textarea) = textarea() else { return };
+ if symbol(ffi::LV_SYMBOL_LEFT) {
+ textarea.cursor_left();
+ } else if symbol(ffi::LV_SYMBOL_RIGHT) {
+ textarea.cursor_right();
+ } else if symbol(ffi::LV_SYMBOL_BACKSPACE) {
+ textarea.delete_char();
+ } else if text == "+/-" {
+ textarea.toggle_sign();
+ } else {
+ textarea.add_text(text).unwrap();
+ }
+ })?;
+ Ok(())
+ }
+
pub fn new<P: class::LvClass>(parent: &LvHandle<P>) -> Option<Self> {
- NonNull::new(unsafe { ffi::lv_keyboard_create(parent.as_ptr()) }).map(LvHandle::from_ptr)
+ unsafe extern "C" fn event(_: *mut ffi::lv_event_t) {}
+ let keyboard: Self = unsafe {
+ super::util::create_widget(
+ parent,
+ Rc::new(RefCell::new(State {
+ mode: BitboxKeyboardMode::Number,
+ maps: [Some(NUMBER_MAP), None, None, None, None],
+ })),
+ event,
+ )
+ }?;
+ keyboard.remove_flag(crate::LvObjFlag::LV_OBJ_FLAG_CLICK_FOCUSABLE);
+ keyboard.set_mode(BitboxKeyboardMode::Number);
+ Some(keyboard)
}
pub fn get_selected_button(&self) -> u32 {
- unsafe { ffi::lv_keyboard_get_selected_button(self.as_ptr()) }
+ ButtonmatrixExt::get_selected_button(self)
}
- pub fn get_button_text(&self, button_id: u32) -> Option<CString> {
- unsafe {
- optional_cstr_from_ptr(ffi::lv_keyboard_get_button_text(self.as_ptr(), button_id))
- .map(|text| text.to_owned())
- }
+ pub fn get_button_text(&self, button_id: u32) -> Option<ZeroizingText> {
+ ButtonmatrixExt::get_button_text(self, button_id)
}
pub fn to_buttonmatrix(self) -> LvButtonmatrix {
@@ -104,38 +230,116 @@ impl LvHandle<class::KeyboardTag> {
impl KeyboardExt for LvHandle<class::KeyboardTag> {}
-/// # Safety
-/// `event` must point to a valid LVGL keyboard event.
-pub unsafe fn keyboard_def_event_cb(event: *mut ffi::lv_event_t) {
- unsafe { ffi::lv_keyboard_def_event_cb(event) }
-}
-
#[cfg(test)]
mod tests {
use alloc::boxed::Box;
- use core::{mem, ptr::NonNull};
+ use core::ptr::NonNull;
- use super::{KeyboardExt, LvKeyboard, LvKeyboardMapEntry};
+ use super::{BitboxKeyboard, BitboxKeyboardMapEntry, KeyboardExt, symbol};
+ use crate::{BitboxKeyboardMode, BitboxTextarea, ObjExt, TextareaExt, ffi};
use crate::{LvButtonmatrixCtrl, LvHandle, class};
- fn dummy_keyboard() -> LvKeyboard {
+ #[test]
+ fn test_bind_textarea_input_and_deletion() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(320, 240).unwrap();
+ let screen = display.screen_active().unwrap();
+ let textarea = BitboxTextarea::new(&screen).unwrap();
+ let keyboard = BitboxKeyboard::new(&screen).unwrap();
+ keyboard.bind_textarea(&textarea).unwrap();
+ const MAP: &[BitboxKeyboardMapEntry] = &[
+ BitboxKeyboardMapEntry::new(c"ö"),
+ symbol(ffi::LV_SYMBOL_LEFT),
+ symbol(ffi::LV_SYMBOL_BACKSPACE),
+ BitboxKeyboardMapEntry::new(c"+/-"),
+ BitboxKeyboardMapEntry::new(c""),
+ ];
+ keyboard.set_map(
+ BitboxKeyboardMode::User1,
+ MAP,
+ &[LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_WIDTH_1; 4],
+ );
+ keyboard.set_mode(BitboxKeyboardMode::User1);
+ let press = |id| {
+ crate::ButtonmatrixExt::set_selected_button(&keyboard, id);
+ unsafe {
+ ffi::lv_obj_send_event(
+ keyboard.as_ptr(),
+ crate::LvEventCode::LV_EVENT_VALUE_CHANGED,
+ core::ptr::null_mut(),
+ );
+ }
+ };
+ textarea.set_text("ab").unwrap();
+ press(1);
+ press(0);
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "aöb");
+ press(2);
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "ab");
+ press(3);
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "-ab");
+ press(3);
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "+ab");
+ unsafe { textarea.delete() };
+ press(0);
+ unsafe { keyboard.delete() };
+ }
+
+ fn dummy_keyboard() -> BitboxKeyboard {
LvHandle::<class::KeyboardTag>::from_ptr(NonNull::dangling())
}
+ #[test]
+ fn test_bind_textarea_number_mode_and_ready_deletion() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(320, 240).unwrap();
+ let screen = display.screen_active().unwrap();
+ let parent = crate::LvObj::with_parent(&screen).unwrap();
+ let textarea = BitboxTextarea::new(&parent).unwrap();
+ textarea.set_accepted_chars(Some(c"0123456789"));
+ let keyboard = BitboxKeyboard::new(&parent).unwrap();
+ keyboard.bind_textarea(&textarea).unwrap();
+ let press = |id| {
+ crate::ButtonmatrixExt::set_selected_button(&keyboard, id);
+ unsafe {
+ ffi::lv_obj_send_event(
+ keyboard.as_ptr(),
+ crate::LvEventCode::LV_EVENT_VALUE_CHANGED,
+ core::ptr::null_mut(),
+ )
+ };
+ };
+ press(0);
+ press(4);
+ press(12);
+ press(14);
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "14");
+ press(11);
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "1");
+ let live = textarea.weak_handle();
+ keyboard
+ .add_event_cb(crate::LvEventCode::LV_EVENT_READY, move || {
+ unsafe { ffi::lv_obj_delete(parent.as_ptr()) };
+ })
+ .unwrap();
+ press(7);
+ assert!(live().is_none());
+ }
+
#[test]
#[should_panic(
expected = "LVGL keyboard control map length must match the number of buttons in the map"
)]
fn test_set_map_rejects_incorrect_ctrl_map_length() {
let keyboard = dummy_keyboard();
- let map: &'static [LvKeyboardMapEntry] = Box::leak(Box::new([
- LvKeyboardMapEntry::new(c"1"),
- LvKeyboardMapEntry::new(c"2"),
- LvKeyboardMapEntry::new(c""),
+ let map: &'static [BitboxKeyboardMapEntry] = Box::leak(Box::new([
+ BitboxKeyboardMapEntry::new(c"1"),
+ BitboxKeyboardMapEntry::new(c"2"),
+ BitboxKeyboardMapEntry::new(c""),
]));
let ctrl_map: &'static [LvButtonmatrixCtrl] =
- Box::leak(Box::new([unsafe { mem::zeroed() }]));
+ Box::leak(Box::new([LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_WIDTH_1]));
- keyboard.set_map(unsafe { mem::zeroed() }, map, ctrl_map);
+ keyboard.set_map(BitboxKeyboardMode::User1, map, ctrl_map);
}
}
### src/rust/bitbox-lvgl/src/widgets/label.rs
@@ -1,107 +1,508 @@
// SPDX-License-Identifier: Apache-2.0
-use alloc::borrow::ToOwned;
-use alloc::ffi::CString;
-use core::ffi::CStr;
-use core::ptr::NonNull;
+//! A Rust reimplementation of LVGL's label widget, built on `lv_obj`.
+//!
+//! Owns zeroizing text storage and renders through `lv_draw_label`.
-use crate::{LvHandle, LvLabelLongMode, LvObj, LvPoint, ObjExt, class, ffi};
-use util::strings::{optional_cstr_from_ptr, str_to_cstr_vec_zeroizing};
+use alloc::{boxed::Box, rc::Rc, string::String};
+use core::{cell::RefCell, ffi::CStr, ops::Deref};
+use zeroize::Zeroizing;
-pub type LvLabelTextError = super::LvTextError;
-pub type LvLabel = LvHandle<class::LabelTag>;
+use crate::{LvHandle, LvObj, LvPoint, ObjExt, ZeroizingText, class, ffi};
-pub trait LabelExt: ObjExt {
- fn set_text(&self, txt: &str) -> Result<(), LvLabelTextError> {
- let txt = str_to_cstr_vec_zeroizing(txt).map_err(|_| LvLabelTextError::ContainsNul)?;
- unsafe { ffi::lv_label_set_text(self.as_ptr(), txt.as_ptr()) }
- Ok(())
- }
+pub type BitboxLabelTextError = super::LvTextError;
+pub type BitboxLabel = LvHandle<class::LabelTag>;
- fn set_text_static(&self, text: Option<&'static CStr>) {
- unsafe {
- ffi::lv_label_set_text_static(
- self.as_ptr(),
- text.map_or(core::ptr::null(), CStr::as_ptr),
- )
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BitboxLabelLongMode {
+ Wrap,
+ Clip,
+}
+
+#[derive(Clone)]
+enum Text {
+ Owned(Rc<ZeroizingText>),
+ Static(&'static CStr),
+}
+
+impl Deref for Text {
+ type Target = CStr;
+ fn deref(&self) -> &CStr {
+ match self {
+ Self::Owned(text) => text,
+ Self::Static(text) => text,
}
}
+}
- fn set_long_mode(&self, long_mode: LvLabelLongMode) {
- unsafe { ffi::lv_label_set_long_mode(self.as_ptr(), long_mode) }
- }
+struct State {
+ text: Text,
+ mode: BitboxLabelLongMode,
+}
+
+type TextState = RefCell<State>;
+
+fn text_state(obj: *mut ffi::lv_obj_t) -> Rc<TextState> {
+ unsafe { super::util::widget_state::<class::LabelTag, TextState>(obj) }
+}
- fn set_text_selection_start(&self, index: u32) {
- unsafe { ffi::lv_label_set_text_selection_start(self.as_ptr(), index) }
+fn draw_descriptor(
+ obj: *mut ffi::lv_obj_t,
+ mode: BitboxLabelLongMode,
+ layer: *mut ffi::lv_layer_t,
+) -> ffi::lv_draw_label_dsc_t {
+ let mut dsc = ffi::lv_draw_label_dsc_t::default();
+ unsafe {
+ ffi::lv_draw_label_dsc_init(&mut dsc);
+ dsc.base.layer = layer;
+ ffi::lv_obj_init_draw_label_dsc(obj, crate::LvPart::LV_PART_MAIN, &mut dsc);
+ // The draw initializer skips these properties when text opacity is zero.
+ dsc.font = ffi::lv_obj_get_style_prop(
+ obj,
+ crate::LvPart::LV_PART_MAIN,
+ ffi::_lv_style_id_t::LV_STYLE_TEXT_FONT as ffi::lv_style_prop_t,
+ )
+ .ptr
+ .cast();
}
+ dsc.letter_space = style_num(obj, ffi::_lv_style_id_t::LV_STYLE_TEXT_LETTER_SPACE);
+ dsc.line_space = style_num(obj, ffi::_lv_style_id_t::LV_STYLE_TEXT_LINE_SPACE);
+ if mode == BitboxLabelLongMode::Clip {
+ dsc.set_flag(ffi::lv_text_flag_t::LV_TEXT_FLAG_EXPAND);
+ }
+ dsc
+}
- fn set_text_selection_end(&self, index: u32) {
- unsafe { ffi::lv_label_set_text_selection_end(self.as_ptr(), index) }
+fn style_num(obj: *mut ffi::lv_obj_t, property: ffi::_lv_style_id_t) -> i32 {
+ unsafe {
+ ffi::lv_obj_get_style_prop(
+ obj,
+ crate::LvPart::LV_PART_MAIN,
+ property as ffi::lv_style_prop_t,
+ )
+ .num
}
+}
- fn set_recolor(&self, enable: bool) {
- unsafe { ffi::lv_label_set_recolor(self.as_ptr(), enable) }
+unsafe extern "C" fn release_draw_text(event: *mut ffi::lv_event_t) {
+ let code = unsafe { ffi::lv_event_get_code(event) };
+ if matches!(
+ code,
+ crate::LvEventCode::LV_EVENT_RENDER_READY | crate::LvEventCode::LV_EVENT_DELETE
+ ) {
+ unsafe {
+ let display = ffi::lv_event_get_current_target(event).cast();
+ let text = ffi::lv_event_get_user_data(event);
+ ffi::lv_display_remove_event_cb_with_user_data(display, Some(release_draw_text), text);
+ drop(Box::from_raw(text.cast::<Rc<ZeroizingText>>()));
+ }
}
+}
- fn get_text(&self) -> Option<CString> {
+fn retain_draw_text(obj: *mut ffi::lv_obj_t, text: &Text) {
+ if let Text::Owned(text) = text {
+ // Draw tasks can outlive this callback, including replacement of the label text.
+ let text = Box::into_raw(Box::new(Rc::clone(text))).cast();
unsafe {
- // Snapshot the current text instead of borrowing LVGL-owned storage.
- optional_cstr_from_ptr(ffi::lv_label_get_text(self.as_ptr()))
- .map(|text| text.to_owned())
+ ffi::lv_display_add_event_cb(
+ ffi::lv_obj_get_display(obj),
+ Some(release_draw_text),
+ crate::LvEventCode::LV_EVENT_ALL,
+ text,
+ );
}
}
+}
- fn get_long_mode(&self) -> LvLabelLongMode {
- unsafe { ffi::lv_label_get_long_mode(self.as_ptr()) }
+fn refresh(obj: *mut ffi::lv_obj_t) {
+ unsafe {
+ ffi::lv_obj_refresh_self_size(obj);
+ ffi::lv_obj_invalidate(obj);
}
+}
- fn get_letter_pos(&self, char_id: u32) -> LvPoint {
- let mut pos = LvPoint { x: 0, y: 0 };
- unsafe { ffi::lv_label_get_letter_pos(self.as_ptr(), char_id, &mut pos) }
- pos
+unsafe extern "C" fn label_event(event: *mut ffi::lv_event_t) {
+ let obj = unsafe { ffi::lv_event_get_current_target(event) }.cast::<ffi::lv_obj_t>();
+ let code = unsafe { ffi::lv_event_get_code(event) };
+ if code == crate::LvEventCode::LV_EVENT_DELETE {
+ text_state(obj).borrow_mut().text = Text::Static(c"");
+ return;
+ }
+ if matches!(
+ code,
+ crate::LvEventCode::LV_EVENT_STYLE_CHANGED | crate::LvEventCode::LV_EVENT_SIZE_CHANGED
+ ) {
+ refresh(obj);
+ return;
}
+ if !matches!(
+ code,
+ crate::LvEventCode::LV_EVENT_GET_SELF_SIZE
+ | crate::LvEventCode::LV_EVENT_DRAW_MAIN
+ | crate::LvEventCode::LV_EVENT_REFR_EXT_DRAW_SIZE
+ ) {
+ return;
+ }
+ let (text, mode) = {
+ let state = text_state(obj);
+ let state = state.borrow();
+ (state.text.clone(), state.mode)
+ };
+ let layer = if code == crate::LvEventCode::LV_EVENT_DRAW_MAIN {
+ unsafe { ffi::lv_event_get_layer(event) }
+ } else {
+ core::ptr::null_mut()
+ };
+ let mut dsc = draw_descriptor(obj, mode, layer);
+ if code == crate::LvEventCode::LV_EVENT_REFR_EXT_DRAW_SIZE {
+ unsafe { ffi::lv_event_set_ext_draw_size(event, (*dsc.font).line_height / 4) };
+ } else if code == crate::LvEventCode::LV_EVENT_GET_SELF_SIZE {
+ let width = style_num(obj, ffi::_lv_style_id_t::LV_STYLE_WIDTH);
+ let grow = style_num(obj, ffi::_lv_style_id_t::LV_STYLE_FLEX_GROW);
+ let max_width = if width == ffi::LV_SIZE_CONTENT as i32 && grow == 0 {
+ ffi::LV_COORD_MAX as i32
+ } else {
+ unsafe { ffi::lv_obj_get_content_width(obj) }.max(0)
+ }
+ .min(style_num(obj, ffi::_lv_style_id_t::LV_STYLE_MAX_WIDTH));
+ let mut size = LvPoint { x: 0, y: 0 };
+ unsafe {
+ ffi::lv_text_get_size(
+ &mut size,
+ text.as_ptr(),
+ dsc.font,
+ dsc.letter_space,
+ dsc.line_space,
+ max_width,
+ dsc.flag(),
+ );
+ size.y = size
+ .y
+ .min(style_num(obj, ffi::_lv_style_id_t::LV_STYLE_MAX_HEIGHT));
+ let result = &mut *ffi::lv_event_get_param(event).cast::<LvPoint>();
+ result.x = result.x.max(size.x);
+ result.y = result.y.max(size.y);
+ }
+ } else {
+ let mut area = crate::LvArea {
+ x1: 0,
+ y1: 0,
+ x2: 0,
+ y2: 0,
+ };
+ unsafe {
+ ffi::lv_obj_get_content_coords(obj, &mut area);
+ dsc.text = text.as_ptr();
+ dsc.set_text_static(u8::from(matches!(text, Text::Static(_))));
+ let original_clip = (*layer)._clip_area;
+ let clip = crate::LvArea {
+ x1: area.x1.max(original_clip.x1),
+ y1: area.y1.max(original_clip.y1),
+ x2: area.x2.min(original_clip.x2),
+ y2: area.y2.min(original_clip.y2),
+ };
+ if clip.x1 > clip.x2
+ || clip.y1 > clip.y2
+ || text.is_empty()
+ || dsc.opa <= ffi::LV_OPA_MIN as u8
+ {
+ return;
+ }
+ retain_draw_text(obj, &text);
+ if mode == BitboxLabelLongMode::Clip {
+ (*layer)._clip_area = clip;
+ } else {
+ (*layer)._clip_area.y2 = clip.y2;
+ }
+ ffi::lv_draw_label(dsc.base.layer, &dsc, &area);
+ (*layer)._clip_area = original_clip;
+ }
+ }
+}
- fn get_letter_on(&self, pos: &LvPoint, bidi: bool) -> u32 {
- let mut pos = LvPoint { x: pos.x, y: pos.y };
- unsafe { ffi::lv_label_get_letter_on(self.as_ptr(), &mut pos, bidi) }
+pub trait LabelExt: ObjExt {
+ /// Replaces the zeroizing text buffer and sends `LV_EVENT_VALUE_CHANGED`.
+ fn set_text(&self, txt: &str) -> Result<(), BitboxLabelTextError> {
+ let text = Rc::new(ZeroizingText::new(txt)?);
+ text_state(self.as_ptr()).borrow_mut().text = Text::Owned(text);
+ refresh(self.as_ptr());
+ unsafe {
+ ffi::lv_obj_send_event(
+ self.as_ptr(),
+ crate::LvEventCode::LV_EVENT_VALUE_CHANGED,
+ core::ptr::null_mut(),
+ );
+ }
+ Ok(())
}
- fn is_char_under_pos(&self, pos: &LvPoint) -> bool {
- let mut pos = LvPoint { x: pos.x, y: pos.y };
- unsafe { ffi::lv_label_is_char_under_pos(self.as_ptr(), &mut pos) }
+ fn set_text_static(&self, text: Option<&'static CStr>) {
+ if let Some(text) = text {
+ text.to_str().expect("label text must be UTF-8");
+ text_state(self.as_ptr()).borrow_mut().text = Text::Static(text);
+ }
+ refresh(self.as_ptr());
}
- fn get_text_selection_start(&self) -> u32 {
- unsafe { ffi::lv_label_get_text_selection_start(self.as_ptr()) }
+ fn set_long_mode(&self, mode: BitboxLabelLongMode) {
+ text_state(self.as_ptr()).borrow_mut().mode = mode;
+ refresh(self.as_ptr());
}
- fn get_text_selection_end(&self) -> u32 {
- unsafe { ffi::lv_label_get_text_selection_end(self.as_ptr()) }
+ fn get_long_mode(&self) -> BitboxLabelLongMode {
+ text_state(self.as_ptr()).borrow().mode
}
- fn get_recolor(&self) -> bool {
- unsafe { ffi::lv_label_get_recolor(self.as_ptr()) }
+ fn get_text(&self) -> Option<ZeroizingText> {
+ Some(ZeroizingText::from_cstr(
+ &text_state(self.as_ptr()).borrow().text,
+ ))
}
- fn ins_text(&self, pos: u32, txt: &str) -> Result<(), LvLabelTextError> {
- let txt = CString::new(txt).map_err(|_| LvLabelTextError::ContainsNul)?;
- unsafe { ffi::lv_label_ins_text(self.as_ptr(), pos, txt.as_ptr()) }
- Ok(())
+ fn ins_text(&self, pos: u32, txt: &str) -> Result<(), BitboxLabelTextError> {
+ if txt.as_bytes().contains(&0) {
+ return Err(BitboxLabelTextError::ContainsNul);
+ }
+ let current = self.get_text().unwrap();
+ let current = current.to_str().unwrap();
+ let offset = char_offset(current, pos as usize);
+ let mut text = Zeroizing::new(String::with_capacity(current.len() + txt.len()));
+ text.push_str(¤t[..offset]);
+ text.push_str(txt);
+ text.push_str(¤t[offset..]);
+ self.set_text(&text)
}
fn cut_text(&self, pos: u32, count: u32) {
- unsafe { ffi::lv_label_cut_text(self.as_ptr(), pos, count) }
+ let current = self.get_text().unwrap();
+ let current = current.to_str().unwrap();
+ let start = char_offset(current, pos as usize);
+ let end = start + char_offset(¤t[start..], count as usize);
+ let mut text = Zeroizing::new(String::with_capacity(current.len() - (end - start)));
+ text.push_str(¤t[..start]);
+ text.push_str(¤t[end..]);
+ self.set_text(&text).unwrap();
}
}
impl LvHandle<class::LabelTag> {
pub fn new<P: class::LvClass>(parent: &LvHandle<P>) -> Option<Self> {
- NonNull::new(unsafe { ffi::lv_label_create(parent.as_ptr()) }).map(LvHandle::from_ptr)
+ let label: Self = unsafe {
+ super::util::create_widget(
+ parent,
+ Rc::new(RefCell::new(State {
+ text: Text::Static(c""),
+ mode: BitboxLabelLongMode::Wrap,
+ })),
+ label_event,
+ )
+ }?;
+ label.remove_flag(crate::LvObjFlag::LV_OBJ_FLAG_CLICKABLE);
+ label.remove_flag(crate::LvObjFlag::LV_OBJ_FLAG_SCROLLABLE);
+ Some(label)
}
pub fn to_obj(self) -> LvObj {
self.cast()
}
+
+ fn prefix_width(&self, text: &CStr, offset: usize) -> i32 {
+ let dsc = draw_descriptor(
+ self.as_ptr(),
+ BitboxLabelLongMode::Clip,
+ core::ptr::null_mut(),
+ );
+ let attrs = ffi::lv_text_attributes_t {
+ letter_space: dsc.letter_space,
+ line_space: dsc.line_space,
+ max_width: ffi::LV_COORD_MAX as i32,
+ text_flags: ffi::lv_text_flag_t::LV_TEXT_FLAG_EXPAND,
+ };
+ let width = unsafe {
+ ffi::lv_text_get_width(text.as_ptr(), offset.try_into().unwrap(), dsc.font, &attrs)
+ };
+ width + if offset > 0 { dsc.letter_space } else { 0 }
+ }
+
+ pub(crate) fn letter_position(&self, index: usize) -> LvPoint {
+ assert_eq!(self.get_long_mode(), BitboxLabelLongMode::Clip);
+ let text = text_state(self.as_ptr()).borrow().text.clone();
+ let offset = char_offset(text.to_str().unwrap(), index);
+ LvPoint {
+ x: self.prefix_width(&text, offset),
+ y: 0,
+ }
+ }
+
+ pub(crate) fn letter_at(&self, x: i32) -> usize {
+ assert_eq!(self.get_long_mode(), BitboxLabelLongMode::Clip);
+ let text = text_state(self.as_ptr()).borrow().text.clone();
+ let value = text.to_str().unwrap();
+ let mut previous = 0;
+ let mut index = 0;
+ for offset in value
+ .char_indices()
+ .skip(1)
+ .map(|(offset, _)| offset)
+ .chain(core::iter::once(value.len()))
+ {
+ let next = self.prefix_width(&text, offset);
+ if x < (previous + next) / 2 {
+ return index;
+ }
+ previous = next;
+ index += 1;
+ }
+ index.min(value.chars().count())
+ }
}
impl LabelExt for LvHandle<class::LabelTag> {}
+
+pub(crate) fn char_offset(text: &str, index: usize) -> usize {
+ text.char_indices()
+ .nth(index)
+ .map_or(text.len(), |(offset, _)| offset)
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_set_text_shares_storage_and_releases_it_on_deletion() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(64, 64).unwrap();
+ let screen = display.screen_active().unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
+ let state = text_state(label.as_ptr());
+ label.set_text("abstract").unwrap();
+ let original = {
+ let state = state.borrow();
+ let Text::Owned(text) = &state.text else {
+ panic!("expected owned text")
+ };
+ Rc::downgrade(text)
+ };
+ let alias = screen
+ .child(0)
+ .unwrap()
+ .try_downcast::<class::LabelTag>()
+ .unwrap();
+ alias.set_text("a longer recovery word display").unwrap();
+ assert!(original.upgrade().is_none());
+ assert_eq!(
+ label.get_text().unwrap().to_str().unwrap(),
+ "a longer recovery word display"
+ );
+ alias.set_text("act").unwrap();
+ let on_delete = state.clone();
+ label
+ .add_event_cb(crate::LvEventCode::LV_EVENT_DELETE, move || {
+ assert!(on_delete.borrow().text.is_empty());
+ })
+ .unwrap();
+ unsafe { alias.delete() };
+ assert!(state.borrow().text.is_empty());
+ assert_eq!(Rc::strong_count(&state), 1);
+ }
+
+ #[test]
+ fn test_ins_text_and_cut_text_utf8() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(64, 64).unwrap();
+ let screen = display.screen_active().unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
+ label.set_text_static(Some(c"aö🙂z"));
+ label.ins_text(2, "ä").unwrap();
+ assert_eq!(label.get_text().unwrap().to_str().unwrap(), "aöä🙂z");
+ label.cut_text(1, 3);
+ assert_eq!(label.get_text().unwrap().to_str().unwrap(), "az");
+ label.ins_text(u32::MAX, "ü").unwrap();
+ assert_eq!(label.get_text().unwrap().to_str().unwrap(), "azü");
+ label.cut_text(1, u32::MAX);
+ assert_eq!(label.get_text().unwrap().to_str().unwrap(), "a");
+ label.set_text_static(Some(c"static"));
+ assert!(matches!(
+ text_state(label.as_ptr()).borrow().text,
+ Text::Static(_)
+ ));
+ label.set_text_static(None);
+ assert_eq!(label.get_text().unwrap().to_str().unwrap(), "static");
+ unsafe { label.delete() };
+ }
+
+ #[test]
+ fn test_set_text_snapshot_survives_replacement() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(64, 64).unwrap();
+ let screen = display.screen_active().unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
+ label.set_text("recovery words").unwrap();
+ let snapshot = label.get_text().unwrap();
+ assert_eq!(
+ label.set_text("invalid\0text"),
+ Err(BitboxLabelTextError::ContainsNul)
+ );
+ assert_eq!(
+ label.get_text().unwrap().to_str().unwrap(),
+ "recovery words"
+ );
+ label.set_text("replacement").unwrap();
+ unsafe { label.delete() };
+ assert_eq!(snapshot.to_str().unwrap(), "recovery words");
+ }
+
+ #[test]
+ fn test_retain_draw_text_until_render_ready() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(64, 64).unwrap();
+ let screen = display.screen_active().unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
+ label.set_text("pending draw").unwrap();
+ let display = unsafe { ffi::lv_obj_get_display(label.as_ptr()) };
+ let text = text_state(label.as_ptr()).borrow().text.clone();
+ let Text::Owned(owned) = &text else {
+ panic!("expected owned text")
+ };
+ let weak = Rc::downgrade(owned);
+ retain_draw_text(label.as_ptr(), &text);
+ retain_draw_text(label.as_ptr(), &text);
+ drop(text);
+ label.set_text("").unwrap();
+ unsafe { label.delete() };
+ assert!(weak.upgrade().is_some());
+ unsafe {
+ ffi::lv_display_send_event(
+ display,
+ crate::LvEventCode::LV_EVENT_RENDER_READY,
+ core::ptr::null_mut(),
+ )
+ };
+ assert!(weak.upgrade().is_none());
+ }
+
+ #[test]
+ fn test_layout_wrapping_clipping_and_transparent_text() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(320, 240).unwrap();
+ let screen = display.screen_active().unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
+ label.set_style_text_font(crate::fonts::INTER_REGULAR_32, 0);
+ label.set_text("one two three four").unwrap();
+ label.set_width(100);
+ unsafe { ffi::lv_obj_update_layout(label.as_ptr()) };
+ let wrapped = unsafe { ffi::lv_obj_get_height(label.as_ptr()) };
+ label.set_long_mode(BitboxLabelLongMode::Clip);
+ unsafe { ffi::lv_obj_update_layout(label.as_ptr()) };
+ let clipped = unsafe { ffi::lv_obj_get_height(label.as_ptr()) };
+ assert!(wrapped > clipped);
+ label.set_style_text_opa(0, 0);
+ unsafe { ffi::lv_obj_update_layout(label.as_ptr()) };
+ assert_eq!(unsafe { ffi::lv_obj_get_height(label.as_ptr()) }, clipped);
+ label.set_text("aöyz").unwrap();
+ for index in 0..=4 {
+ assert_eq!(label.letter_at(label.letter_position(index).x), index);
+ }
+ unsafe { label.delete() };
+ }
+}
### src/rust/bitbox-lvgl/src/widgets/mod.rs
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
+//! LVGL widget wrappers (`Lv*`) and custom Rust widgets (`Bitbox*`).
+
pub mod arc;
pub mod bar;
pub mod button;
@@ -41,7 +43,7 @@ mod tests {
assert_image_ext::<canvas::LvCanvas>();
assert_arc_ext::<spinner::LvSpinner>();
assert_bar_ext::<slider::LvSlider>();
- assert_buttonmatrix_ext::<keyboard::LvKeyboard>();
+ assert_buttonmatrix_ext::<keyboard::BitboxKeyboard>();
assert_spangroup_ext::<span::LvSpangroup>();
}
### src/rust/bitbox-lvgl/src/widgets/span.rs
@@ -4,13 +4,11 @@ use core::ffi::CStr;
use core::ptr::NonNull;
use ::util::strings::optional_cstr_from_ptr;
-use alloc::borrow::ToOwned;
-use alloc::ffi::CString;
use crate::{
LvAlign, LvBaseDir, LvBlendMode, LvBorderSide, LvColor, LvFlexAlign, LvFlexFlow, LvFont,
LvGradDir, LvGridAlign, LvGridTemplate, LvHandle, LvObj, LvOpa, LvPoint, LvSpanCoords,
- LvSpanMode, LvSpanOverflow, LvTextAlign, LvTextDecor, ObjExt, class, ffi,
+ LvSpanMode, LvSpanOverflow, LvTextAlign, LvTextDecor, ObjExt, ZeroizingText, class, ffi,
};
pub type LvSpanTextError = super::LvTextError;
@@ -86,7 +84,7 @@ impl LvSpan {
}
pub fn set_text(&self, text: &str) -> Result<(), LvSpanTextError> {
- let text = CString::new(text).map_err(|_| LvSpanTextError::ContainsNul)?;
+ let text = ZeroizingText::new(text)?;
unsafe { ffi::lv_span_set_text(self.as_ptr(), text.as_ptr()) }
Ok(())
}
@@ -113,9 +111,10 @@ impl LvSpan {
self.get_style().as_ptr()
}
- pub fn get_text(&self) -> Option<CString> {
+ pub fn get_text(&self) -> Option<ZeroizingText> {
unsafe {
- optional_cstr_from_ptr(ffi::lv_span_get_text(self.as_ptr())).map(|text| text.to_owned())
+ optional_cstr_from_ptr(ffi::lv_span_get_text(self.as_ptr()))
+ .map(ZeroizingText::from_cstr)
}
}
@@ -292,7 +291,7 @@ pub trait SpangroupExt: ObjExt {
}
fn set_span_text(&self, span: &LvSpan, text: &str) -> Result<(), LvSpanTextError> {
- let text = CString::new(text).map_err(|_| LvSpanTextError::ContainsNul)?;
+ let text = ZeroizingText::new(text)?;
unsafe { ffi::lv_spangroup_set_span_text(self.as_ptr(), span.as_ptr(), text.as_ptr()) }
Ok(())
}
### src/rust/bitbox-lvgl/src/widgets/textarea.rs
@@ -1,205 +1,537 @@
// SPDX-License-Identifier: Apache-2.0
-use alloc::borrow::ToOwned;
-use alloc::ffi::CString;
-use core::ffi::CStr;
-use core::ptr::NonNull;
-
-use super::label::LvLabel;
-use crate::{LvHandle, LvObj, LvTextAlign, ObjExt, class, ffi};
-use util::strings::{optional_cstr_from_ptr, str_to_cstr_vec_zeroizing};
-
-pub type LvTextareaTextError = super::LvTextError;
-pub type LvTextarea = LvHandle<class::TextareaTag>;
-
-pub trait TextareaExt: ObjExt {
- fn add_char(&self, ch: u32) {
- unsafe { ffi::lv_textarea_add_char(self.as_ptr(), ch) }
- }
-
- fn add_text(&self, txt: &str) -> Result<(), LvTextareaTextError> {
- let txt = str_to_cstr_vec_zeroizing(txt).map_err(|_| LvTextareaTextError::ContainsNul)?;
- unsafe { ffi::lv_textarea_add_text(self.as_ptr(), txt.as_ptr()) }
- Ok(())
- }
-
- fn delete_char(&self) {
- unsafe { ffi::lv_textarea_delete_char(self.as_ptr()) }
- }
-
- fn delete_char_forward(&self) {
- unsafe { ffi::lv_textarea_delete_char_forward(self.as_ptr()) }
- }
-
- fn set_text(&self, txt: &str) -> Result<(), LvTextareaTextError> {
- let txt = str_to_cstr_vec_zeroizing(txt).map_err(|_| LvTextareaTextError::ContainsNul)?;
- unsafe { ffi::lv_textarea_set_text(self.as_ptr(), txt.as_ptr()) }
- Ok(())
- }
-
- fn set_placeholder_text(&self, txt: &str) -> Result<(), LvTextareaTextError> {
- let txt = CString::new(txt).map_err(|_| LvTextareaTextError::ContainsNul)?;
- unsafe { ffi::lv_textarea_set_placeholder_text(self.as_ptr(), txt.as_ptr()) }
- Ok(())
- }
-
- fn set_cursor_pos(&self, pos: i32) {
- unsafe { ffi::lv_textarea_set_cursor_pos(self.as_ptr(), pos) }
- }
+//! A Rust reimplementation of LVGL's single-line textarea, built from `lv_obj`
+//! and [`BitboxLabel`]. Input filtering, password masking, and cursor handling
+//! are implemented here.
+
+use alloc::{rc::Rc, string::String, vec};
+use core::{cell::RefCell, ffi::CStr};
+use zeroize::Zeroizing;
+
+use super::label::{BitboxLabel, char_offset};
+use crate::{LabelExt, LvHandle, LvObj, ObjExt, ZeroizingText, class, ffi};
+
+pub type BitboxTextareaTextError = super::LvTextError;
+/// A single-line text editor with Rust-owned, zeroizing text storage.
+pub type BitboxTextarea = LvHandle<class::TextareaTag>;
+
+struct State {
+ deleted: bool,
+ text: Rc<ZeroizingText>,
+ cursor: usize,
+ accepted: Option<&'static CStr>,
+ max_length: usize,
+ password: bool,
+ bullet: Rc<ZeroizingText>,
+ scroll_x: i32,
+}
- fn set_cursor_click_pos(&self, enable: bool) {
- unsafe { ffi::lv_textarea_set_cursor_click_pos(self.as_ptr(), enable) }
- }
+type TextareaState = RefCell<State>;
- fn set_password_mode(&self, enable: bool) {
- unsafe { ffi::lv_textarea_set_password_mode(self.as_ptr(), enable) }
- }
+fn state(obj: *mut ffi::lv_obj_t) -> Rc<TextareaState> {
+ unsafe { super::util::widget_state::<class::TextareaTag, TextareaState>(obj) }
+}
- fn set_password_bullet(&self, bullet: &str) -> Result<(), LvTextareaTextError> {
- let bullet = CString::new(bullet).map_err(|_| LvTextareaTextError::ContainsNul)?;
- unsafe { ffi::lv_textarea_set_password_bullet(self.as_ptr(), bullet.as_ptr()) }
- Ok(())
- }
+fn handle(obj: *mut ffi::lv_obj_t) -> BitboxTextarea {
+ LvHandle::from_ptr(core::ptr::NonNull::new(obj).unwrap())
+}
- fn set_one_line(&self, enable: bool) {
- unsafe { ffi::lv_textarea_set_one_line(self.as_ptr(), enable) }
+fn refresh_cursor(textarea: &BitboxTextarea) {
+ let Some(label) = textarea.get_label() else {
+ return;
+ };
+ let Some(cursor) = textarea.child(1) else {
+ return;
+ };
+ unsafe { ffi::lv_obj_update_layout(textarea.as_ptr()) };
+ let state = state(textarea.as_ptr());
+ let position = state.borrow().cursor;
+ let point = label.letter_position(position);
+ let width = unsafe { ffi::lv_obj_get_content_width(textarea.as_ptr()) }.max(1);
+ let scroll_x = {
+ let mut state = state.borrow_mut();
+ state.scroll_x = state.scroll_x.min(point.x).max(point.x - width + 2).max(0);
+ state.scroll_x
+ };
+ label.set_pos(-scroll_x, 0);
+ cursor.set_pos(point.x - scroll_x, point.y);
+ unsafe {
+ let font = ffi::lv_obj_get_style_prop(
+ label.as_ptr(),
+ crate::LvPart::LV_PART_MAIN,
+ ffi::_lv_style_id_t::LV_STYLE_TEXT_FONT as ffi::lv_style_prop_t,
+ )
+ .ptr
+ .cast::<ffi::lv_font_t>();
+ cursor.set_height((*font).line_height);
+ let color = ffi::lv_obj_get_style_prop(
+ label.as_ptr(),
+ crate::LvPart::LV_PART_MAIN,
+ ffi::_lv_style_id_t::LV_STYLE_TEXT_COLOR as ffi::lv_style_prop_t,
+ )
+ .color;
+ cursor.set_style_bg_color(color, 0);
}
+}
- fn set_accepted_chars(&self, accepted: Option<&'static CStr>) {
- unsafe {
- ffi::lv_textarea_set_accepted_chars(
- self.as_ptr(),
- accepted.map_or(core::ptr::null(), CStr::as_ptr),
- )
+fn refresh_text(textarea: &BitboxTextarea) {
+ let Some(label) = textarea.get_label() else {
+ return;
+ };
+ let (text, password, bullet) = {
+ let state = state(textarea.as_ptr());
+ let state = state.borrow();
+ (
+ Rc::clone(&state.text),
+ state.password,
+ Rc::clone(&state.bullet),
+ )
+ };
+ let text = text.to_str().unwrap();
+ if password {
+ let bullet = bullet.to_str().unwrap();
+ let count = text.chars().count();
+ let mut masked = Zeroizing::new(String::with_capacity(count * bullet.len()));
+ for _ in 0..count {
+ masked.push_str(bullet);
}
+ label.set_text(&masked).unwrap();
+ } else {
+ label.set_text(text).unwrap();
}
+ refresh_cursor(textarea);
+}
- fn set_max_length(&self, max_length: u32) {
- unsafe { ffi::lv_textarea_set_max_length(self.as_ptr(), max_length) }
- }
-
- fn set_insert_replace(&self, text: Option<&'static CStr>) {
- unsafe {
- ffi::lv_textarea_set_insert_replace(
- self.as_ptr(),
- text.map_or(core::ptr::null(), CStr::as_ptr),
- )
+unsafe extern "C" fn textarea_event(event: *mut ffi::lv_event_t) {
+ let obj = unsafe { ffi::lv_event_get_current_target(event) }.cast::<ffi::lv_obj_t>();
+ let textarea = handle(obj);
+ match unsafe { ffi::lv_event_get_code(event) } {
+ crate::LvEventCode::LV_EVENT_DELETE => {
+ // Child labels wipe their own displayed text when LVGL deletes them next.
+ let state = state(obj);
+ state.borrow_mut().deleted = true;
+ state.borrow_mut().text = Rc::new(ZeroizingText::new("").unwrap());
}
+ crate::LvEventCode::LV_EVENT_SIZE_CHANGED | crate::LvEventCode::LV_EVENT_STYLE_CHANGED => {
+ refresh_cursor(&textarea);
+ }
+ crate::LvEventCode::LV_EVENT_PRESSED => {
+ let indev = unsafe { ffi::lv_indev_active() };
+ if indev.is_null() {
+ return;
+ }
+ let Some(label) = textarea.get_label() else {
+ return;
+ };
+ let mut point = crate::LvPoint { x: 0, y: 0 };
+ let mut area = crate::LvArea {
+ x1: 0,
+ y1: 0,
+ x2: 0,
+ y2: 0,
+ };
+ unsafe {
+ ffi::lv_indev_get_point(indev, &mut point);
+ ffi::lv_obj_get_coords(label.as_ptr(), &mut area);
+ }
+ point.x -= area.x1;
+ point.y -= area.y1;
+ textarea.set_cursor_pos(label.letter_at(point.x));
+ }
+ crate::LvEventCode::LV_EVENT_FOCUSED => {
+ if let Some(cursor) = textarea.child(1) {
+ cursor.remove_flag(crate::LvObjFlag::LV_OBJ_FLAG_HIDDEN);
+ }
+ }
+ crate::LvEventCode::LV_EVENT_DEFOCUSED => {
+ if let Some(cursor) = textarea.child(1) {
+ cursor.add_flag(crate::LvObjFlag::LV_OBJ_FLAG_HIDDEN);
+ }
+ }
+ _ => {}
}
+}
- fn set_text_selection(&self, enable: bool) {
- unsafe { ffi::lv_textarea_set_text_selection(self.as_ptr(), enable) }
- }
-
- fn set_password_show_time(&self, time_ms: u32) {
- unsafe { ffi::lv_textarea_set_password_show_time(self.as_ptr(), time_ms) }
- }
-
- fn set_align(&self, align: LvTextAlign) {
- unsafe { ffi::lv_textarea_set_align(self.as_ptr(), align) }
+fn replace_text(textarea: &BitboxTextarea, text: &str, cursor: usize) {
+ let text = Rc::new(ZeroizingText::new(text).unwrap());
+ {
+ let state = state(textarea.as_ptr());
+ let mut state = state.borrow_mut();
+ state.text = text;
+ state.cursor = cursor;
+ }
+ refresh_text(textarea);
+ unsafe {
+ ffi::lv_obj_send_event(
+ textarea.as_ptr(),
+ crate::LvEventCode::LV_EVENT_VALUE_CHANGED,
+ core::ptr::null_mut(),
+ );
}
+}
- fn get_text(&self) -> Option<CString> {
- unsafe {
- // Snapshot the current text instead of borrowing LVGL-owned storage.
- optional_cstr_from_ptr(ffi::lv_textarea_get_text(self.as_ptr()))
- .map(|text| text.to_owned())
+fn insert_text(
+ textarea: &BitboxTextarea,
+ text: &str,
+ replace: bool,
+) -> Result<(), BitboxTextareaTextError> {
+ if text.as_bytes().contains(&0) {
+ return Err(BitboxTextareaTextError::ContainsNul);
+ }
+ let (current, cursor, accepted, max_length) = {
+ let state = state(textarea.as_ptr());
+ let state = state.borrow();
+ (
+ Rc::clone(&state.text),
+ state.cursor,
+ state.accepted,
+ state.max_length,
+ )
+ };
+ let current = if replace {
+ ""
+ } else {
+ current.to_str().unwrap()
+ };
+ let cursor = if replace { 0 } else { cursor };
+ let offset = char_offset(current, cursor);
+ let available = max_length.saturating_sub(current.chars().count());
+ let accepted = accepted.map(|chars| chars.to_str().expect("accepted characters must be UTF-8"));
+ let mut result = Zeroizing::new(String::with_capacity(current.len() + text.len()));
+ result.push_str(¤t[..offset]);
+ let mut added = 0;
+ for (offset, ch) in text.char_indices() {
+ if added == available {
+ break;
}
- }
-
- fn get_placeholder_text(&self) -> Option<CString> {
- unsafe {
- // Snapshot the current placeholder instead of borrowing LVGL-owned storage.
- optional_cstr_from_ptr(ffi::lv_textarea_get_placeholder_text(self.as_ptr()))
- .map(|text| text.to_owned())
+ if matches!(ch, '\n' | '\r') || accepted.is_some_and(|chars| !chars.contains(ch)) {
+ continue;
}
+ result.push_str(&text[offset..offset + ch.len_utf8()]);
+ added += 1;
}
-
- fn get_label(&self) -> Option<LvLabel> {
- NonNull::new(unsafe { ffi::lv_textarea_get_label(self.as_ptr()) }).map(LvHandle::from_ptr)
+ result.push_str(¤t[offset..]);
+ if replace || added > 0 {
+ replace_text(textarea, &result, cursor + added);
}
+ Ok(())
+}
- fn get_cursor_pos(&self) -> u32 {
- unsafe { ffi::lv_textarea_get_cursor_pos(self.as_ptr()) }
+pub trait TextareaExt: ObjExt {
+ fn add_char(&self, ch: char) {
+ let mut bytes = Zeroizing::new(vec![0; ch.len_utf8()].into_boxed_slice());
+ let text = ch.encode_utf8(&mut bytes);
+ self.add_text(text).unwrap();
}
- fn get_cursor_click_pos(&self) -> bool {
- unsafe { ffi::lv_textarea_get_cursor_click_pos(self.as_ptr()) }
+ fn add_text(&self, text: &str) -> Result<(), BitboxTextareaTextError> {
+ insert_text(&handle(self.as_ptr()), text, false)
}
- fn get_password_mode(&self) -> bool {
- unsafe { ffi::lv_textarea_get_password_mode(self.as_ptr()) }
+ fn set_text(&self, text: &str) -> Result<(), BitboxTextareaTextError> {
+ insert_text(&handle(self.as_ptr()), text, true)
}
- fn get_password_bullet(&self) -> Option<CString> {
- unsafe {
- // Snapshot the current bullet instead of borrowing LVGL-owned storage.
- optional_cstr_from_ptr(ffi::lv_textarea_get_password_bullet(self.as_ptr()))
- .map(|text| text.to_owned())
+ fn delete_char(&self) {
+ let (text, cursor) = {
+ let state = state(self.as_ptr());
+ let state = state.borrow();
+ (Rc::clone(&state.text), state.cursor)
+ };
+ if cursor == 0 {
+ return;
}
+ let text = text.to_str().unwrap();
+ let start = char_offset(text, cursor - 1);
+ let end = char_offset(text, cursor);
+ let mut result = Zeroizing::new(String::with_capacity(text.len() - (end - start)));
+ result.push_str(&text[..start]);
+ result.push_str(&text[end..]);
+ replace_text(&handle(self.as_ptr()), &result, cursor - 1);
}
- fn get_one_line(&self) -> bool {
- unsafe { ffi::lv_textarea_get_one_line(self.as_ptr()) }
- }
-
- fn get_accepted_chars(&self) -> Option<CString> {
- unsafe {
- // Snapshot the accepted-char list instead of borrowing LVGL-owned storage.
- optional_cstr_from_ptr(ffi::lv_textarea_get_accepted_chars(self.as_ptr()))
- .map(|text| text.to_owned())
+ fn delete_char_forward(&self) {
+ let cursor = self.get_cursor_pos();
+ if cursor < self.with_text(|text| text.chars().count()) {
+ self.set_cursor_pos(cursor + 1);
+ self.delete_char();
}
}
- fn get_max_length(&self) -> u32 {
- unsafe { ffi::lv_textarea_get_max_length(self.as_ptr()) }
+ fn set_cursor_pos(&self, position: usize) {
+ {
+ let state = state(self.as_ptr());
+ let mut state = state.borrow_mut();
+ state.cursor = position.min(state.text.to_str().unwrap().chars().count());
+ }
+ refresh_cursor(&handle(self.as_ptr()));
}
- fn text_is_selected(&self) -> bool {
- unsafe { ffi::lv_textarea_text_is_selected(self.as_ptr()) }
+ fn get_cursor_pos(&self) -> usize {
+ state(self.as_ptr()).borrow().cursor
}
- fn get_text_selection(&self) -> bool {
- unsafe { ffi::lv_textarea_get_text_selection(self.as_ptr()) }
+ fn cursor_left(&self) {
+ self.set_cursor_pos(self.get_cursor_pos().saturating_sub(1));
}
- fn get_password_show_time(&self) -> u32 {
- unsafe { ffi::lv_textarea_get_password_show_time(self.as_ptr()) }
+ fn cursor_right(&self) {
+ self.set_cursor_pos(self.get_cursor_pos() + 1);
}
- fn get_current_char(&self) -> u32 {
- unsafe { ffi::lv_textarea_get_current_char(self.as_ptr()) }
+ fn set_password_mode(&self, enable: bool) {
+ state(self.as_ptr()).borrow_mut().password = enable;
+ refresh_text(&handle(self.as_ptr()));
+ }
+
+ fn set_password_bullet(&self, bullet: &str) -> Result<(), BitboxTextareaTextError> {
+ let text = ZeroizingText::new(bullet)?;
+ assert_eq!(
+ bullet.chars().count(),
+ 1,
+ "password bullet must be one character"
+ );
+ state(self.as_ptr()).borrow_mut().bullet = Rc::new(text);
+ refresh_text(&handle(self.as_ptr()));
+ Ok(())
}
- fn clear_selection(&self) {
- unsafe { ffi::lv_textarea_clear_selection(self.as_ptr()) }
+ fn set_accepted_chars(&self, accepted: Option<&'static CStr>) {
+ if let Some(chars) = accepted {
+ chars.to_str().expect("accepted characters must be UTF-8");
+ }
+ state(self.as_ptr()).borrow_mut().accepted = accepted;
}
- fn cursor_right(&self) {
- unsafe { ffi::lv_textarea_cursor_right(self.as_ptr()) }
+ fn set_max_length(&self, max_length: usize) {
+ state(self.as_ptr()).borrow_mut().max_length = if max_length == 0 {
+ usize::MAX
+ } else {
+ max_length
+ };
}
- fn cursor_left(&self) {
- unsafe { ffi::lv_textarea_cursor_left(self.as_ptr()) }
+ fn get_text(&self) -> Option<ZeroizingText> {
+ Some(ZeroizingText::from_cstr(
+ &state(self.as_ptr()).borrow().text,
+ ))
}
- fn cursor_down(&self) {
- unsafe { ffi::lv_textarea_cursor_down(self.as_ptr()) }
+ /// Reads through an owned snapshot, so the callback can also update the textarea.
+ fn with_text<R>(&self, f: impl FnOnce(&str) -> R) -> R {
+ let text = self.get_text().unwrap();
+ f(text.to_str().unwrap())
}
- fn cursor_up(&self) {
- unsafe { ffi::lv_textarea_cursor_up(self.as_ptr()) }
+ fn get_label(&self) -> Option<BitboxLabel> {
+ self.child(0)?.try_downcast::<class::LabelTag>().ok()
}
}
impl LvHandle<class::TextareaTag> {
pub fn new<P: class::LvClass>(parent: &LvHandle<P>) -> Option<Self> {
- NonNull::new(unsafe { ffi::lv_textarea_create(parent.as_ptr()) }).map(LvHandle::from_ptr)
+ let state = Rc::new(RefCell::new(State {
+ deleted: false,
+ text: Rc::new(ZeroizingText::new("").unwrap()),
+ cursor: 0,
+ accepted: None,
+ max_length: usize::MAX,
+ password: false,
+ bullet: Rc::new(ZeroizingText::new("*").unwrap()),
+ scroll_x: 0,
+ }));
+ let textarea: Self = unsafe { super::util::create_widget(parent, state, textarea_event) }?;
+ textarea.remove_flag(crate::LvObjFlag::LV_OBJ_FLAG_SCROLLABLE);
+ let Some(label) = BitboxLabel::new(&textarea) else {
+ unsafe { textarea.delete() };
+ return None;
+ };
+ label.set_long_mode(crate::BitboxLabelLongMode::Clip);
+ let Some(cursor) = LvObj::with_parent(&textarea) else {
+ unsafe { textarea.delete() };
+ return None;
+ };
+ cursor.set_width(2);
+ cursor.set_style_border_width(0, 0);
+ cursor.set_style_radius(0, 0);
+ cursor.set_style_bg_opa(crate::LvOpacityLevel::LV_OPA_COVER as u8, 0);
+ cursor.remove_flag(crate::LvObjFlag::LV_OBJ_FLAG_CLICKABLE);
+ cursor.remove_flag(crate::LvObjFlag::LV_OBJ_FLAG_SCROLLABLE);
+ cursor.add_flag(crate::LvObjFlag::LV_OBJ_FLAG_IGNORE_LAYOUT);
+ refresh_cursor(&textarea);
+ Some(textarea)
}
pub fn to_obj(self) -> LvObj {
self.cast()
}
+
+ pub(crate) fn toggle_sign(&self) {
+ let (text, cursor, accepted, max_length) = {
+ let state = state(self.as_ptr());
+ let state = state.borrow();
+ (
+ Rc::clone(&state.text),
+ state.cursor,
+ state.accepted,
+ state.max_length,
+ )
+ };
+ let text = text.to_str().unwrap();
+ let sign = if text.starts_with('-') { "+" } else { "-" };
+ if accepted.is_some_and(|chars| !chars.to_str().unwrap().contains(sign)) {
+ return;
+ }
+ let has_sign = text.starts_with(['-', '+']);
+ if !has_sign && text.chars().count() >= max_length {
+ return;
+ }
+ let mut result = Zeroizing::new(String::with_capacity(text.len() + usize::from(!has_sign)));
+ result.push_str(sign);
+ result.push_str(if has_sign { &text[1..] } else { text });
+ replace_text(self, &result, cursor + usize::from(!has_sign));
+ }
+
+ pub(crate) fn weak_handle(&self) -> impl Fn() -> Option<Self> + 'static {
+ let state = Rc::downgrade(&state(self.as_ptr()));
+ let obj = self.as_ptr();
+ move || {
+ let state = state.upgrade()?;
+ if state.borrow().deleted {
+ None
+ } else {
+ Some(handle(obj))
+ }
+ }
+ }
}
impl TextareaExt for LvHandle<class::TextareaTag> {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_add_text_filters_limits_and_events() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(64, 64).unwrap();
+ let screen = display.screen_active().unwrap();
+ let textarea = BitboxTextarea::new(&screen).unwrap();
+ let alias = screen
+ .child(0)
+ .unwrap()
+ .try_downcast::<class::TextareaTag>()
+ .unwrap();
+ let changes = Rc::new(core::cell::Cell::new(0));
+ let changes_cb = Rc::clone(&changes);
+ textarea
+ .add_event_cb(crate::LvEventCode::LV_EVENT_VALUE_CHANGED, move || {
+ changes_cb.set(changes_cb.get() + 1);
+ assert!(alias.with_text(|text| text.chars().all(|ch| ch.is_ascii_digit())));
+ alias.set_cursor_pos(alias.get_cursor_pos());
+ })
+ .unwrap();
+ textarea.set_accepted_chars(Some(c"0123456789"));
+ textarea.set_max_length(3);
+ textarea.add_text("a12\n3z4").unwrap();
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "123");
+ assert_eq!(changes.get(), 1);
+ textarea.add_text("5").unwrap();
+ assert_eq!(changes.get(), 1);
+ assert_eq!(
+ textarea.set_text("9\0x"),
+ Err(BitboxTextareaTextError::ContainsNul)
+ );
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "123");
+ textarea.set_cursor_pos(1);
+ textarea.delete_char();
+ textarea.add_text("7").unwrap();
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "723");
+ assert_eq!(textarea.get_cursor_pos(), 1);
+ assert_eq!(changes.get(), 3);
+ unsafe { textarea.delete() };
+ }
+
+ #[test]
+ fn test_delete_char_and_mask_utf8() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(64, 64).unwrap();
+ let screen = display.screen_active().unwrap();
+ let textarea = BitboxTextarea::new(&screen).unwrap();
+ textarea.set_max_length(4);
+ textarea.set_text("aö🙂z").unwrap();
+ textarea.set_password_mode(true);
+ textarea.set_password_bullet("#").unwrap();
+ assert_eq!(
+ textarea
+ .get_label()
+ .unwrap()
+ .get_text()
+ .unwrap()
+ .to_str()
+ .unwrap(),
+ "####"
+ );
+ textarea.set_cursor_pos(2);
+ textarea.delete_char_forward();
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "aöz");
+ textarea.delete_char();
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "az");
+ textarea.add_text("ä🙂extra").unwrap();
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "aä🙂z");
+ textarea.set_password_mode(false);
+ assert_eq!(
+ textarea
+ .get_label()
+ .unwrap()
+ .get_text()
+ .unwrap()
+ .to_str()
+ .unwrap(),
+ "aä🙂z"
+ );
+ textarea.set_cursor_pos(0);
+ textarea.delete_char();
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "aä🙂z");
+ unsafe { textarea.delete() };
+ }
+
+ #[test]
+ fn test_delete_releases_text_and_invalidates_weak_handles() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(64, 64).unwrap();
+ let screen = display.screen_active().unwrap();
+ let parent = LvObj::with_parent(&screen).unwrap();
+ let textarea = BitboxTextarea::new(&parent).unwrap();
+ textarea.set_text("sensitive input").unwrap();
+ let state = state(textarea.as_ptr());
+ let text = Rc::downgrade(&state.borrow().text);
+ let weak_handle = textarea.weak_handle();
+ let snapshot = textarea.get_text().unwrap();
+ assert!(weak_handle().is_some());
+ unsafe { parent.delete() };
+ assert!(weak_handle().is_none());
+ assert!(text.upgrade().is_none());
+ assert_eq!(Rc::strong_count(&state), 1);
+ assert_eq!(snapshot.to_str().unwrap(), "sensitive input");
+ }
+
+ #[test]
+ fn test_with_text_allows_replacement() {
+ let _lock = crate::test_util::lock_and_init();
+ let display = crate::LvDisplay::new(64, 64).unwrap();
+ let screen = display.screen_active().unwrap();
+ let textarea = BitboxTextarea::new(&screen).unwrap();
+ assert!(textarea.with_text(str::is_empty));
+ textarea.set_text("öäü").unwrap();
+ let len = textarea.with_text(|text| {
+ textarea.set_text("replacement").unwrap();
+ assert_eq!(text, "öäü");
+ text.len()
+ });
+ assert_eq!(len, 6);
+ textarea.with_text(|text| assert_eq!(text, "replacement"));
+ unsafe { textarea.delete() };
+ }
+}
### src/rust/bitbox-lvgl/src/widgets/util.rs
@@ -26,6 +26,72 @@ pub enum LvEventRegistrationError {
type EventCallback = RefCell<Box<dyn FnMut() + 'static>>;
+#[repr(C)]
+struct WidgetState<T> {
+ drop: unsafe fn(*mut c_void),
+ state: Rc<T>,
+}
+
+unsafe fn drop_widget_state<T>(ptr: *mut c_void) {
+ drop(unsafe { Box::from_raw(ptr.cast::<WidgetState<T>>()) });
+}
+
+// LVGL runs the destructor after all deletion callbacks and child deletion.
+#[unsafe(no_mangle)]
+unsafe extern "C" fn bitbox_lv_widget_destructor(
+ _class: *const ffi::lv_obj_class_t,
+ obj: *mut ffi::lv_obj_t,
+) {
+ let ptr = unsafe { ffi::lv_obj_get_user_data(obj) };
+ if !ptr.is_null() {
+ unsafe {
+ ffi::lv_obj_set_user_data(obj, core::ptr::null_mut());
+ let drop = *ptr.cast::<unsafe fn(*mut c_void)>();
+ drop(ptr);
+ }
+ }
+}
+
+// Only classes with bitbox_lv_widget_destructor may use this user-data layout.
+pub(crate) unsafe fn create_widget<C: class::LvClass, T>(
+ parent: &LvHandle<impl class::LvClass>,
+ state: Rc<T>,
+ callback: unsafe extern "C" fn(*mut ffi::lv_event_t),
+) -> Option<LvHandle<C>> {
+ let raw =
+ NonNull::new(unsafe { ffi::lv_obj_class_create_obj(C::class_ptr(), parent.as_ptr()) })?;
+ let obj = LvHandle::from_ptr(raw);
+ let state = Box::into_raw(Box::new(WidgetState {
+ drop: drop_widget_state::<T>,
+ state,
+ }))
+ .cast();
+ unsafe {
+ ffi::lv_obj_set_user_data(obj.as_ptr(), state);
+ if ffi::lv_obj_add_event_cb(
+ obj.as_ptr(),
+ Some(callback),
+ ffi::lv_event_code_t::LV_EVENT_ALL,
+ core::ptr::null_mut(),
+ )
+ .is_null()
+ {
+ ffi::lv_obj_delete(obj.as_ptr());
+ return None;
+ }
+ ffi::lv_obj_class_init_obj(obj.as_ptr());
+ }
+ Some(obj)
+}
+
+// C and T must match the class/state pair passed to create_widget.
+pub(crate) unsafe fn widget_state<C: class::LvClass, T>(obj: *mut ffi::lv_obj_t) -> Rc<T> {
+ assert!(unsafe { ffi::lv_obj_has_class(obj, C::class_ptr()) });
+ let ptr = unsafe { ffi::lv_obj_get_user_data(obj) }.cast::<WidgetState<T>>();
+ assert!(!ptr.is_null(), "widget has been deleted");
+ Rc::clone(unsafe { &(*ptr).state })
+}
+
unsafe extern "C" fn on_delete_drop_attachment<T>(e: *mut ffi::lv_event_t) {
if unsafe { ffi::lv_event_get_code(e) } != ffi::lv_event_code_t::LV_EVENT_DELETE {
return;
### src/rust/bitbox03/src/ui.rs
@@ -4,8 +4,8 @@ use alloc::format;
use alloc::vec::Vec;
use bitbox_hal as hal;
use bitbox_lvgl::{
- self as lvgl, LabelExt, LvAlign, LvDisplay, LvHandle, LvLabel, LvObj, LvOpacityLevel, LvPart,
- LvSpangroup, ObjExt, SpangroupExt,
+ self as lvgl, BitboxLabel, LabelExt, LvAlign, LvDisplay, LvHandle, LvObj, LvOpacityLevel,
+ LvPart, LvSpangroup, ObjExt, SpangroupExt,
};
use core::marker::PhantomData;
use tracing::info;
@@ -131,7 +131,7 @@ impl<Timer: bitbox_hal::timer::Timer> hal::ui::Ui for BitBox03Ui<Timer> {
let screen = LvObj::new().unwrap();
screen.set_style_bg_color(lvgl::color::black(), 0);
screen.set_style_text_color(lvgl::color::white(), 0);
- let label = LvLabel::new(&screen).unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
label.set_width(380);
label.set_text(message).unwrap();
label.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
@@ -328,8 +328,8 @@ impl<Timer> BitBox03Ui<Timer> {
screen.set_style_pad_top(40, 0);
screen.set_style_pad_left(50, 0);
- let label = LvLabel::new(&screen).unwrap();
- label.set_text("Welcome!").unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
+ label.set_text_static(Some(c"Welcome!"));
label.set_style_margin_bottom(60, 0);
label.set_style_text_font(
lvgl::fonts::INTER_REGULAR_48,
@@ -342,27 +342,25 @@ impl<Timer> BitBox03Ui<Timer> {
spangroup.set_height(lvgl::ffi::LV_SIZE_CONTENT as i32);
let span0 = spangroup.add_span().unwrap();
- span0
- .set_text("Let's get started\nsetting up your ")
- .unwrap();
+ span0.set_text_static(Some(c"Let's get started\nsetting up your "));
span0.set_style_text_font(lvgl::fonts::INTER_REGULAR_48);
let span1 = spangroup.add_span().unwrap();
- span1.set_text("BitBox").unwrap();
+ span1.set_text_static(Some(c"BitBox"));
span1.set_style_text_font(lvgl::fonts::INTER_BOLD_48);
let span2 = spangroup.add_span().unwrap();
- span2.set_text("03").unwrap();
+ span2.set_text_static(Some(c"03"));
span2.set_style_text_font(lvgl::fonts::INTER_REGULAR_48);
- let label = LvLabel::new(&screen).unwrap();
- label.set_text("Download and open\nthe BitBoxApp.").unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
+ label.set_text_static(Some(c"Download and open\nthe BitBoxApp."));
label.set_style_margin_bottom(60, 0);
label.set_style_text_font(
lvgl::fonts::INTER_REGULAR_32,
lvgl::LvState::LV_STATE_DEFAULT as u32,
);
- let label = LvLabel::new(&screen).unwrap();
- label.set_text("bitbox.swiss/start").unwrap();
+ let label = BitboxLabel::new(&screen).unwrap();
+ label.set_text_static(Some(c"bitbox.swiss/start"));
label.set_style_text_font(
lvgl::fonts::INTER_BOLD_32,
lvgl::LvState::LV_STATE_DEFAULT as u32,
### src/rust/bitbox03/src/ui/choice.rs
@@ -5,8 +5,8 @@ use alloc::vec::Vec;
use bitbox_hal::ui::TrinaryChoice;
use bitbox_lvgl::{
- self as lvgl, LabelExt, LvAlign, LvButton, LvLabel, LvLabelLongMode, LvObj, LvOpacityLevel,
- ObjExt,
+ self as lvgl, BitboxLabel, BitboxLabelLongMode, LabelExt, LvAlign, LvButton, LvObj,
+ LvOpacityLevel, ObjExt,
};
use util::futures::completion::Responder;
@@ -30,7 +30,7 @@ fn add_button(
.add_click_cb(move || responder.resolve(choice))
.expect("failed to register choice callback");
- let button_label = LvLabel::new(&button).unwrap();
+ let button_label = BitboxLabel::new(&button).unwrap();
button_label.set_text(label).unwrap();
button_label.set_style_text_font(
lvgl::fonts::INTER_BOLD_32,
@@ -62,9 +62,9 @@ pub fn build_trinary_choice_screen(
screen.set_style_pad_left(50, 0);
screen.set_style_pad_row(24, 0);
- let title = LvLabel::new(&screen).unwrap();
+ let title = BitboxLabel::new(&screen).unwrap();
title.set_width(380);
- title.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
+ title.set_long_mode(BitboxLabelLongMode::Wrap);
title.set_text(message).unwrap();
title.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
title.set_style_text_font(
### src/rust/bitbox03/src/ui/confirm.rs
@@ -3,7 +3,8 @@
use alloc::string::String;
use bitbox_hal::ui::{ConfirmParams, MAX_CONFIRM_BODY_SIZE, UserAbort};
use bitbox_lvgl::{
- self as lvgl, LabelExt, LvLabel, LvLabelLongMode, LvObj, LvObjFlag, LvOpacityLevel, ObjExt,
+ self as lvgl, BitboxLabel, BitboxLabelLongMode, LabelExt, LvObj, LvObjFlag, LvOpacityLevel,
+ ObjExt,
};
use util::futures::completion::Responder;
use zeroize::Zeroizing;
@@ -46,9 +47,9 @@ pub fn build_confirm_screen(
screen.set_style_pad_left(50, 0);
screen.set_style_pad_row(24, 0);
- let title = LvLabel::new(&screen).unwrap();
+ let title = BitboxLabel::new(&screen).unwrap();
title.set_width(380);
- title.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
+ title.set_long_mode(BitboxLabelLongMode::Wrap);
title.set_text(params.title).unwrap();
title.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
title.set_style_text_font(
@@ -70,9 +71,9 @@ pub fn build_confirm_screen(
body_container.set_style_bg_opa(LvOpacityLevel::LV_OPA_TRANSP as u8, 0);
body_container.add_flag(LvObjFlag::LV_OBJ_FLAG_SCROLLABLE);
- let body = LvLabel::new(&body_container).unwrap();
+ let body = BitboxLabel::new(&body_container).unwrap();
body.set_width(380);
- body.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
+ body.set_long_mode(BitboxLabelLongMode::Wrap);
body.set_text(&truncate_body(params.body)).unwrap();
body.set_style_text_font(
lvgl::fonts::INTER_REGULAR_32,
### src/rust/bitbox03/src/ui/demo.rs
@@ -5,7 +5,8 @@
//! press-invert feedback and take no action; the top-right corner close button dismisses the demo.
use bitbox_lvgl::{
- self as lvgl, LabelExt, LvLabel, LvLabelLongMode, LvObj, LvObjFlag, LvOpacityLevel, ObjExt,
+ self as lvgl, BitboxLabel, BitboxLabelLongMode, LabelExt, LvObj, LvObjFlag, LvOpacityLevel,
+ ObjExt,
};
use util::futures::completion::Responder;
@@ -23,10 +24,10 @@ pub fn build_demo_screen(responder: Responder<()>) -> LvObj {
screen.set_style_pad_right(50, 0);
screen.set_style_pad_row(40, 0);
- let title = LvLabel::new(&screen).unwrap();
+ let title = BitboxLabel::new(&screen).unwrap();
title.set_width(380);
- title.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
- title.set_text("Navigation buttons").unwrap();
+ title.set_long_mode(BitboxLabelLongMode::Wrap);
+ title.set_text_static(Some(c"Navigation buttons"));
title.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
title.set_style_text_font(
lvgl::fonts::INTER_REGULAR_32,
@@ -62,10 +63,10 @@ pub fn build_demo_screen(responder: Responder<()>) -> LvObj {
// flag so it sits in the column flow (centred) instead of the corner, and wire no action.
build_close_button(&screen).remove_flag(LvObjFlag::LV_OBJ_FLAG_FLOATING);
- let hint = LvLabel::new(&screen).unwrap();
+ let hint = BitboxLabel::new(&screen).unwrap();
hint.set_width(380);
- hint.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
- hint.set_text("Tap to preview. Close with the X.").unwrap();
+ hint.set_long_mode(BitboxLabelLongMode::Wrap);
+ hint.set_text_static(Some(c"Tap to preview. Close with the X."));
hint.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
hint.set_style_text_font(
lvgl::fonts::INTER_REGULAR_32,
### src/rust/bitbox03/src/ui/enter_string.rs
@@ -1,12 +1,13 @@
// SPDX-License-Identifier: Apache-2.0
use alloc::{rc::Rc, string::String, vec::Vec};
+use core::ffi::CStr;
use bitbox_hal::ui::{CanCancel, EnterStringParams, UserAbort, WordlistEntryAbort};
use bitbox_lvgl::{
- self as lvgl, KeyboardExt, LabelExt, LvAlign, LvButton, LvButtonmatrixCtrl, LvKeyboard,
- LvKeyboardMapEntry, LvLabel, LvLabelLongMode, LvObj, LvOpacityLevel, LvPart, LvTextarea,
- ObjExt, TextareaExt, class,
+ self as lvgl, BitboxKeyboard, BitboxKeyboardMapEntry, BitboxLabel, BitboxLabelLongMode,
+ BitboxTextarea, KeyboardExt, LabelExt, LvAlign, LvButton, LvButtonmatrixCtrl, LvObj,
+ LvOpacityLevel, LvPart, ObjExt, TextareaExt, class,
};
use util::futures::completion::Responder;
@@ -15,46 +16,22 @@ use super::keypad::build_keypad;
use super::nav_button::{NavIcon, build_close_button, build_nav_button};
use super::slide_to_confirm::build_slide_to_confirm;
-/// Snapshots the (possibly secret) textarea content into a zeroized-on-drop string. Reads LVGL's
-/// buffer in place — `TextareaExt::get_text` would copy the content into an intermediate
-/// `CString` that is dropped without zeroizing. The single `push_str` into the empty string
-/// allocates exactly once, so no reallocation leaves an unzeroized copy behind either.
-fn snapshot_text(textarea: &LvTextarea) -> zeroize::Zeroizing<String> {
- let mut snapshot = zeroize::Zeroizing::new(String::new());
- let text = unsafe { lvgl::ffi::lv_textarea_get_text(textarea.as_ptr()) };
- if !text.is_null() {
- let text = unsafe { core::ffi::CStr::from_ptr(text) };
- snapshot.push_str(text.to_str().expect("textarea content must be valid UTF-8"));
- }
- snapshot
+/// Snapshots the (possibly secret) textarea content into a zeroized-on-drop string.
+/// Both the intermediate snapshot and the returned string are wiped on drop. Constructing
+/// the string in one allocation avoids leaving copies behind during reallocation.
+fn snapshot_text(textarea: &BitboxTextarea) -> zeroize::Zeroizing<String> {
+ textarea.with_text(|text| zeroize::Zeroizing::new(String::from(text)))
}
-/// Whether the textarea is empty, read in place from LVGL's buffer — unlike [`snapshot_text`]
-/// this does not copy the (possibly secret) content to the heap.
-pub(super) fn textarea_is_empty(textarea: &LvTextarea) -> bool {
- let text = unsafe { lvgl::ffi::lv_textarea_get_text(textarea.as_ptr()) };
- text.is_null() || unsafe { *text == 0 }
+/// Whether the textarea is empty. The wrapper wipes its temporary text snapshot on drop.
+pub(super) fn textarea_is_empty(textarea: &BitboxTextarea) -> bool {
+ textarea.with_text(str::is_empty)
}
-/// The textarea's length in bytes and its last byte, read in place from LVGL's buffer without
-/// copying the (possibly secret) content to the heap. The passphrase keyboard only enters ASCII,
-/// so bytes are characters.
-fn textarea_len_and_last(textarea: &LvTextarea) -> (usize, Option<u8>) {
- let text = unsafe { lvgl::ffi::lv_textarea_get_text(textarea.as_ptr()) };
- if text.is_null() {
- return (0, None);
- }
- let mut len = 0usize;
- let mut last = 0u8;
- loop {
- let byte = unsafe { *text.add(len) } as u8;
- if byte == 0 {
- break;
- }
- last = byte;
- len += 1;
- }
- (len, (len > 0).then_some(last))
+/// The textarea's length in bytes and its last byte. The passphrase keyboard only enters ASCII,
+/// so bytes are characters. The wrapper wipes its temporary text snapshot on drop.
+fn textarea_len_and_last(textarea: &BitboxTextarea) -> (usize, Option<u8>) {
+ textarea.with_text(|text| (text.len(), text.as_bytes().last().copied()))
}
/// Diameter of a circle masking one entered passphrase character.
@@ -89,179 +66,175 @@ impl KeyboardMode {
}
}
- fn switch_label(self, special_chars: bool) -> &'static str {
+ fn switch_label(self, special_chars: bool) -> &'static CStr {
match self {
- Self::LowerCase => "ABC",
- Self::UpperCase => "123",
+ Self::LowerCase => c"ABC",
+ Self::UpperCase => c"123",
Self::Digits => {
if special_chars {
- "&?+"
+ c"&?+"
} else {
- "abc"
+ c"abc"
}
}
- Self::SpecialChars => "abc",
+ Self::SpecialChars => c"abc",
}
}
- fn lvgl_mode(self) -> lvgl::LvKeyboardMode {
+ fn lvgl_mode(self) -> lvgl::BitboxKeyboardMode {
match self {
- Self::LowerCase => lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_USER_1,
- Self::UpperCase => lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_USER_2,
- Self::Digits => lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_USER_3,
- Self::SpecialChars => lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_USER_4,
+ Self::LowerCase => lvgl::BitboxKeyboardMode::User1,
+ Self::UpperCase => lvgl::BitboxKeyboardMode::User2,
+ Self::Digits => lvgl::BitboxKeyboardMode::User3,
+ Self::SpecialChars => lvgl::BitboxKeyboardMode::User4,
}
}
}
const KEY_WIDTH_1: LvButtonmatrixCtrl = LvButtonmatrixCtrl::LV_BUTTONMATRIX_CTRL_WIDTH_1;
-const LOWERCASE_MAP: &[LvKeyboardMapEntry] = &[
- LvKeyboardMapEntry::new(c"a"),
- LvKeyboardMapEntry::new(c"b"),
- LvKeyboardMapEntry::new(c"c"),
- LvKeyboardMapEntry::new(c"d"),
- LvKeyboardMapEntry::new(c"e"),
- LvKeyboardMapEntry::new(c"f"),
- LvKeyboardMapEntry::new(c"g"),
- LvKeyboardMapEntry::new(c"h"),
- LvKeyboardMapEntry::new(c"i"),
- LvKeyboardMapEntry::new(c"\n"),
- LvKeyboardMapEntry::new(c"j"),
- LvKeyboardMapEntry::new(c"k"),
- LvKeyboardMapEntry::new(c"l"),
- LvKeyboardMapEntry::new(c"m"),
- LvKeyboardMapEntry::new(c"n"),
- LvKeyboardMapEntry::new(c"o"),
- LvKeyboardMapEntry::new(c"p"),
- LvKeyboardMapEntry::new(c"q"),
- LvKeyboardMapEntry::new(c"r"),
- LvKeyboardMapEntry::new(c"\n"),
- LvKeyboardMapEntry::new(c"s"),
- LvKeyboardMapEntry::new(c"t"),
- LvKeyboardMapEntry::new(c"u"),
- LvKeyboardMapEntry::new(c"v"),
- LvKeyboardMapEntry::new(c"w"),
- LvKeyboardMapEntry::new(c"x"),
- LvKeyboardMapEntry::new(c"y"),
- LvKeyboardMapEntry::new(c"z"),
- LvKeyboardMapEntry::new(c""),
+const LOWERCASE_MAP: &[BitboxKeyboardMapEntry] = &[
+ BitboxKeyboardMapEntry::new(c"a"),
+ BitboxKeyboardMapEntry::new(c"b"),
+ BitboxKeyboardMapEntry::new(c"c"),
+ BitboxKeyboardMapEntry::new(c"d"),
+ BitboxKeyboardMapEntry::new(c"e"),
+ BitboxKeyboardMapEntry::new(c"f"),
+ BitboxKeyboardMapEntry::new(c"g"),
+ BitboxKeyboardMapEntry::new(c"h"),
+ BitboxKeyboardMapEntry::new(c"i"),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"j"),
+ BitboxKeyboardMapEntry::new(c"k"),
+ BitboxKeyboardMapEntry::new(c"l"),
+ BitboxKeyboardMapEntry::new(c"m"),
+ BitboxKeyboardMapEntry::new(c"n"),
+ BitboxKeyboardMapEntry::new(c"o"),
+ BitboxKeyboardMapEntry::new(c"p"),
+ BitboxKeyboardMapEntry::new(c"q"),
+ BitboxKeyboardMapEntry::new(c"r"),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"s"),
+ BitboxKeyboardMapEntry::new(c"t"),
+ BitboxKeyboardMapEntry::new(c"u"),
+ BitboxKeyboardMapEntry::new(c"v"),
+ BitboxKeyboardMapEntry::new(c"w"),
+ BitboxKeyboardMapEntry::new(c"x"),
+ BitboxKeyboardMapEntry::new(c"y"),
+ BitboxKeyboardMapEntry::new(c"z"),
+ BitboxKeyboardMapEntry::new(c""),
];
-const UPPERCASE_MAP: &[LvKeyboardMapEntry] = &[
- LvKeyboardMapEntry::new(c"A"),
- LvKeyboardMapEntry::new(c"B"),
- LvKeyboardMapEntry::new(c"C"),
- LvKeyboardMapEntry::new(c"D"),
- LvKeyboardMapEntry::new(c"E"),
- LvKeyboardMapEntry::new(c"F"),
- LvKeyboardMapEntry::new(c"G"),
- LvKeyboardMapEntry::new(c"H"),
- LvKeyboardMapEntry::new(c"I"),
- LvKeyboardMapEntry::new(c"\n"),
- LvKeyboardMapEntry::new(c"J"),
- LvKeyboardMapEntry::new(c"K"),
- LvKeyboardMapEntry::new(c"L"),
- LvKeyboardMapEntry::new(c"M"),
- LvKeyboardMapEntry::new(c"N"),
- LvKeyboardMapEntry::new(c"O"),
- LvKeyboardMapEntry::new(c"P"),
- LvKeyboardMapEntry::new(c"Q"),
- LvKeyboardMapEntry::new(c"R"),
- LvKeyboardMapEntry::new(c"\n"),
- LvKeyboardMapEntry::new(c"S"),
- LvKeyboardMapEntry::new(c"T"),
- LvKeyboardMapEntry::new(c"U"),
- LvKeyboardMapEntry::new(c"V"),
- LvKeyboardMapEntry::new(c"W"),
- LvKeyboardMapEntry::new(c"X"),
- LvKeyboardMapEntry::new(c"Y"),
- LvKeyboardMapEntry::new(c"Z"),
- LvKeyboardMapEntry::new(c""),
+const UPPERCASE_MAP: &[BitboxKeyboardMapEntry] = &[
+ BitboxKeyboardMapEntry::new(c"A"),
+ BitboxKeyboardMapEntry::new(c"B"),
+ BitboxKeyboardMapEntry::new(c"C"),
+ BitboxKeyboardMapEntry::new(c"D"),
+ BitboxKeyboardMapEntry::new(c"E"),
+ BitboxKeyboardMapEntry::new(c"F"),
+ BitboxKeyboardMapEntry::new(c"G"),
+ BitboxKeyboardMapEntry::new(c"H"),
+ BitboxKeyboardMapEntry::new(c"I"),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"J"),
+ BitboxKeyboardMapEntry::new(c"K"),
+ BitboxKeyboardMapEntry::new(c"L"),
+ BitboxKeyboardMapEntry::new(c"M"),
+ BitboxKeyboardMapEntry::new(c"N"),
+ BitboxKeyboardMapEntry::new(c"O"),
+ BitboxKeyboardMapEntry::new(c"P"),
+ BitboxKeyboardMapEntry::new(c"Q"),
+ BitboxKeyboardMapEntry::new(c"R"),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"S"),
+ BitboxKeyboardMapEntry::new(c"T"),
+ BitboxKeyboardMapEntry::new(c"U"),
+ BitboxKeyboardMapEntry::new(c"V"),
+ BitboxKeyboardMapEntry::new(c"W"),
+ BitboxKeyboardMapEntry::new(c"X"),
+ BitboxKeyboardMapEntry::new(c"Y"),
+ BitboxKeyboardMapEntry::new(c"Z"),
+ BitboxKeyboardMapEntry::new(c""),
];
-const DIGITS_MAP: &[LvKeyboardMapEntry] = &[
- LvKeyboardMapEntry::new(c"1"),
- LvKeyboardMapEntry::new(c"2"),
- LvKeyboardMapEntry::new(c"3"),
- LvKeyboardMapEntry::new(c"4"),
- LvKeyboardMapEntry::new(c"5"),
- LvKeyboardMapEntry::new(c"\n"),
- LvKeyboardMapEntry::new(c"6"),
- LvKeyboardMapEntry::new(c"7"),
- LvKeyboardMapEntry::new(c"8"),
- LvKeyboardMapEntry::new(c"9"),
- LvKeyboardMapEntry::new(c"0"),
- LvKeyboardMapEntry::new(c""),
+const DIGITS_MAP: &[BitboxKeyboardMapEntry] = &[
+ BitboxKeyboardMapEntry::new(c"1"),
+ BitboxKeyboardMapEntry::new(c"2"),
+ BitboxKeyboardMapEntry::new(c"3"),
+ BitboxKeyboardMapEntry::new(c"4"),
+ BitboxKeyboardMapEntry::new(c"5"),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"6"),
+ BitboxKeyboardMapEntry::new(c"7"),
+ BitboxKeyboardMapEntry::new(c"8"),
+ BitboxKeyboardMapEntry::new(c"9"),
+ BitboxKeyboardMapEntry::new(c"0"),
+ BitboxKeyboardMapEntry::new(c""),
];
-const SPECIAL_CHARS_MAP: &[LvKeyboardMapEntry] = &[
- LvKeyboardMapEntry::new(c" "),
- LvKeyboardMapEntry::new(c"!"),
- LvKeyboardMapEntry::new(c"\""),
- LvKeyboardMapEntry::new(c"#"),
- LvKeyboardMapEntry::new(c"$"),
- LvKeyboardMapEntry::new(c"%"),
- LvKeyboardMapEntry::new(c"&"),
- LvKeyboardMapEntry::new(c"'"),
- LvKeyboardMapEntry::new(c"\n"),
- LvKeyboardMapEntry::new(c"("),
- LvKeyboardMapEntry::new(c")"),
- LvKeyboardMapEntry::new(c"*"),
- LvKeyboardMapEntry::new(c"+"),
- LvKeyboardMapEntry::new(c","),
- LvKeyboardMapEntry::new(c"-"),
- LvKeyboardMapEntry::new(c"."),
- LvKeyboardMapEntry::new(c"/"),
- LvKeyboardMapEntry::new(c"\n"),
- LvKeyboardMapEntry::new(c":"),
- LvKeyboardMapEntry::new(c";"),
- LvKeyboardMapEntry::new(c"<"),
- LvKeyboardMapEntry::new(c"="),
- LvKeyboardMapEntry::new(c">"),
- LvKeyboardMapEntry::new(c"?"),
- LvKeyboardMapEntry::new(c"^"),
- LvKeyboardMapEntry::new(c"["),
- LvKeyboardMapEntry::new(c"\n"),
- LvKeyboardMapEntry::new(c"\\"),
- LvKeyboardMapEntry::new(c"]"),
- LvKeyboardMapEntry::new(c"@"),
- LvKeyboardMapEntry::new(c"_"),
- LvKeyboardMapEntry::new(c"{"),
- LvKeyboardMapEntry::new(c"|"),
- LvKeyboardMapEntry::new(c"}"),
- LvKeyboardMapEntry::new(c""),
+const SPECIAL_CHARS_MAP: &[BitboxKeyboardMapEntry] = &[
+ BitboxKeyboardMapEntry::new(c" "),
+ BitboxKeyboardMapEntry::new(c"!"),
+ BitboxKeyboardMapEntry::new(c"\""),
+ BitboxKeyboardMapEntry::new(c"#"),
+ BitboxKeyboardMapEntry::new(c"$"),
+ BitboxKeyboardMapEntry::new(c"%"),
+ BitboxKeyboardMapEntry::new(c"&"),
+ BitboxKeyboardMapEntry::new(c"'"),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"("),
+ BitboxKeyboardMapEntry::new(c")"),
+ BitboxKeyboardMapEntry::new(c"*"),
+ BitboxKeyboardMapEntry::new(c"+"),
+ BitboxKeyboardMapEntry::new(c","),
+ BitboxKeyboardMapEntry::new(c"-"),
+ BitboxKeyboardMapEntry::new(c"."),
+ BitboxKeyboardMapEntry::new(c"/"),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c":"),
+ BitboxKeyboardMapEntry::new(c";"),
+ BitboxKeyboardMapEntry::new(c"<"),
+ BitboxKeyboardMapEntry::new(c"="),
+ BitboxKeyboardMapEntry::new(c">"),
+ BitboxKeyboardMapEntry::new(c"?"),
+ BitboxKeyboardMapEntry::new(c"^"),
+ BitboxKeyboardMapEntry::new(c"["),
+ BitboxKeyboardMapEntry::new(c"\n"),
+ BitboxKeyboardMapEntry::new(c"\\"),
+ BitboxKeyboardMapEntry::new(c"]"),
+ BitboxKeyboardMapEntry::new(c"@"),
+ BitboxKeyboardMapEntry::new(c"_"),
+ BitboxKeyboardMapEntry::new(c"{"),
+ BitboxKeyboardMapEntry::new(c"|"),
+ BitboxKeyboardMapEntry::new(c"}"),
+ BitboxKeyboardMapEntry::new(c""),
];
const LOWERCASE_CTRL_MAP: &[LvButtonmatrixCtrl] = &[KEY_WIDTH_1; 26];
const UPPERCASE_CTRL_MAP: &[LvButtonmatrixCtrl] = &[KEY_WIDTH_1; 26];
const DIGITS_CTRL_MAP: &[LvButtonmatrixCtrl] = &[KEY_WIDTH_1; 10];
const SPECIAL_CHARS_CTRL_MAP: &[LvButtonmatrixCtrl] = &[KEY_WIDTH_1; 31];
-fn configure_keyboard_maps(keyboard: &LvKeyboard) {
+fn configure_keyboard_maps(keyboard: &BitboxKeyboard) {
keyboard.set_map(
- lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_USER_1,
+ lvgl::BitboxKeyboardMode::User1,
LOWERCASE_MAP,
LOWERCASE_CTRL_MAP,
);
keyboard.set_map(
- lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_USER_2,
+ lvgl::BitboxKeyboardMode::User2,
UPPERCASE_MAP,
UPPERCASE_CTRL_MAP,
);
+ keyboard.set_map(lvgl::BitboxKeyboardMode::User3, DIGITS_MAP, DIGITS_CTRL_MAP);
keyboard.set_map(
- lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_USER_3,
- DIGITS_MAP,
- DIGITS_CTRL_MAP,
- );
- keyboard.set_map(
- lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_USER_4,
+ lvgl::BitboxKeyboardMode::User4,
SPECIAL_CHARS_MAP,
SPECIAL_CHARS_CTRL_MAP,
);
}
-fn add_button<F>(parent: &LvObj, width: i32, height: i32, label: &str, cb: F)
+fn add_button<F>(parent: &LvObj, width: i32, height: i32, label: &'static CStr, cb: F)
where
F: FnMut() + 'static,
{
@@ -275,8 +248,8 @@ where
.add_click_cb(cb)
.expect("failed to register click callback");
- let button_label = LvLabel::new(&button).unwrap();
- button_label.set_text(label).unwrap();
+ let button_label = BitboxLabel::new(&button).unwrap();
+ button_label.set_text_static(Some(label));
button_label.set_style_text_font(
lvgl::fonts::INTER_BOLD_32,
lvgl::LvState::LV_STATE_DEFAULT as u32,
@@ -287,9 +260,9 @@ where
/// Adds the standard entry-screen title label (32px regular, standard content width, wrapping).
fn add_title(screen: &LvObj, text: &str) {
- let title = LvLabel::new(screen).unwrap();
+ let title = BitboxLabel::new(screen).unwrap();
title.set_width(380);
- title.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
+ title.set_long_mode(BitboxLabelLongMode::Wrap);
title.set_text(text).unwrap();
title.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
title.set_style_text_font(
@@ -299,10 +272,9 @@ fn add_title(screen: &LvObj, text: &str) {
}
/// Adds the standard entry text field (380×72; masked with `*` bullets when `hide`).
-fn add_textarea(screen: &LvObj, preset: &str, hide: bool) -> LvTextarea {
- let textarea = LvTextarea::new(screen).unwrap();
+fn add_textarea(screen: &LvObj, preset: &str, hide: bool) -> BitboxTextarea {
+ let textarea = BitboxTextarea::new(screen).unwrap();
textarea.set_size(380, 72);
- textarea.set_one_line(true);
textarea
.set_text(preset)
.expect("preset must not contain NUL");
@@ -325,7 +297,6 @@ fn add_textarea(screen: &LvObj, preset: &str, hide: bool) -> LvTextarea {
textarea
.set_password_bullet("*")
.expect("valid password bullet");
- textarea.set_password_show_time(0);
}
textarea
}
@@ -458,17 +429,6 @@ fn set_nav_button_enabled(button: &LvButton, icon: &LvObj, enabled: bool) {
}
}
-/// Runs `f` on the textarea's content, borrowed in place from LVGL's buffer — unlike
-/// [`snapshot_text`] this makes no copy of the (possibly secret) content.
-fn with_textarea_text<R>(textarea: &LvTextarea, f: impl FnOnce(&str) -> R) -> R {
- let text = unsafe { lvgl::ffi::lv_textarea_get_text(textarea.as_ptr()) };
- if text.is_null() {
- return f("");
- }
- let text = unsafe { core::ffi::CStr::from_ptr(text) };
- f(text.to_str().expect("textarea content must be valid UTF-8"))
-}
-
/// The BIP39 English word at `idx`, or `None` if out of range. The wordlist is public
/// compiled-in data, so the returned `&'static str` needs no zeroizing.
fn bip39_word(idx: u16) -> Option<&'static str> {
@@ -515,12 +475,12 @@ fn wordlist_matches(wordlist: &[u16], prefix: &str) -> WordlistMatch {
}
}
-/// Adds the visible word entry display: the standard entry field, centred (via a `flex_grow`
+/// Adds the visible word entry display: a zeroizing label, centred (via a `flex_grow`
/// wrapper, like the passphrase screen's masked display) in the space the screen's flex flow
/// leaves between the title and the bottom-anchored keyboard region.
///
-/// Returns the textarea (the display row's child 0) that the input widgets operate on.
-fn add_word_display(screen: &LvObj, preset: &str) -> Rc<LvTextarea> {
+/// Returns the label (the display row's child 0) that the input widgets update.
+fn add_word_display(screen: &LvObj, preset: &str) -> Rc<BitboxLabel> {
let display = LvObj::with_parent(screen).unwrap();
display.set_size(380, 72);
display.set_style_flex_grow(1, 0);
@@ -540,28 +500,25 @@ fn add_word_display(screen: &LvObj, preset: &str) -> Rc<LvTextarea> {
display.remove_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_SCROLLABLE);
display.remove_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_CLICKABLE);
- let textarea = add_textarea(&display, preset, false);
// The field is display-only: a tap must not move the insertion cursor into the middle of
// the word (letters always append; backspace always deletes the last one).
- textarea.remove_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_CLICKABLE);
+ assert!(preset.len() <= 8 && preset.bytes().all(|byte| byte.is_ascii_lowercase()));
+ let label = BitboxLabel::new(&display).unwrap();
+ label.set_text(preset).unwrap();
+ label.remove_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_CLICKABLE);
// No entry box on this screen: the letters sit directly on the background, centred, in the
- // same bold 48px the mnemonic review screen shows the words in. The standard field's 72px
- // box (16px paddings) cannot hold that line height, so the field sizes to its content.
- textarea.set_style_bg_opa(LvOpacityLevel::LV_OPA_TRANSP as u8, 0);
- textarea.set_style_border_width(0, 0);
- textarea.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
- textarea.set_style_text_font(
+ // same bold 48px the mnemonic review screen shows the words in. Size to the line's height.
+ label.set_width(380);
+ label.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
+ label.set_style_text_font(
lvgl::fonts::INTER_BOLD_48,
lvgl::LvState::LV_STATE_DEFAULT as u32,
);
- textarea.set_style_pad_top(0, 0);
- textarea.set_style_pad_bottom(0, 0);
- textarea.set_height(lvgl::ffi::LV_SIZE_CONTENT as i32);
- Rc::new(textarea)
+ Rc::new(label)
}
-/// The BIP39 recovery-word entry screen: title ("x of y"), the word being typed in the standard
-/// entry field (recovery words are shown in plaintext — reading the word back is the point of
+/// The BIP39 recovery-word entry screen: title ("x of y"), the word being typed in a zeroizing
+/// label (recovery words are shown in plaintext — reading the word back is the point of
/// the entry), the letters-only keyboard and a backspace/confirm navigation row.
///
/// The keyboard only ever offers letters that extend the entry towards one of the
@@ -588,40 +545,38 @@ pub fn build_wordlist_screen(
add_title(&screen, params.title);
- let textarea = add_word_display(&screen, preset);
- // Wordlist words are lowercase ASCII, at most 8 letters; refuse anything else at the widget
- // level too (the key filtering already guarantees it for touch input).
- textarea.set_accepted_chars(Some(c"abcdefghijklmnopqrstuvwxyz"));
- textarea.set_max_length(8);
-
+ let word_display = add_word_display(&screen, preset);
let wordlist: Rc<[u16]> = wordlist.into();
// BitBox02 parity: a typed letter that leaves exactly one candidate autocompletes the whole
- // word. This runs from the keyboard's insert path, not the textarea change callback: only
- // insertions may autocomplete (completing after a deletion would trap backspace in an
- // undo-redo loop right after it deletes an autocompleted letter), and the textarea callback
- // cannot mutate the textarea anyway (that would re-enter it). The `set_text` here fires the
- // change callback below, which then relays the completed state to the keys and buttons.
- let autocomplete_textarea = Rc::clone(&textarea);
- let autocomplete_wordlist = Rc::clone(&wordlist);
- let autocomplete: Rc<dyn Fn()> = Rc::new(move || {
- let unique = with_textarea_text(autocomplete_textarea.as_ref(), |prefix| {
- wordlist_matches(&autocomplete_wordlist, prefix)
- .unique
- .filter(|word| word.len() > prefix.len())
- });
- if let Some(word) = unique {
- autocomplete_textarea
- .set_text(word)
- .expect("wordlist words contain no NUL");
+ // word. Only insertions may autocomplete: completing after a deletion would trap backspace
+ // in an undo-redo loop right after it deletes an autocompleted letter. The label's change
+ // callback below relays the completed state to the keys and buttons without mutating it.
+ let insert_display = Rc::clone(&word_display);
+ let insert_wordlist = Rc::clone(&wordlist);
+ let insert = Rc::new(move |text: &str| {
+ let current = insert_display.get_text().unwrap();
+ // Wordlist words are lowercase ASCII, at most 8 letters; refuse anything else here too
+ // (the key filtering already guarantees it for touch input).
+ if current.to_bytes().len() + text.len() > 8
+ || !text.bytes().all(|byte| byte.is_ascii_lowercase())
+ {
+ return;
}
+ let mut prefix = zeroize::Zeroizing::new(Vec::with_capacity(8));
+ prefix.extend_from_slice(current.to_bytes());
+ prefix.extend_from_slice(text.as_bytes());
+ let prefix = core::str::from_utf8(&prefix).unwrap();
+ let word = wordlist_matches(&insert_wordlist, prefix)
+ .unique
+ .unwrap_or(prefix);
+ insert_display.set_text(word).unwrap();
});
// Keyboard and navigation row are bottom-anchored like on the passphrase screen (see
// `build_passphrase_screen`), with the keyboard sitting 50px higher over the navigation
// row here.
- let keyboard =
- super::keyboard::build_wordlist_keyboard(&screen, Rc::clone(&textarea), autocomplete);
+ let keyboard = super::keyboard::build_wordlist_keyboard(&screen, insert);
keyboard.add_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_FLOATING);
keyboard.align(LvAlign::LV_ALIGN_BOTTOM_MID, 0, -(82 + 20 + 50));
@@ -641,12 +596,14 @@ pub fn build_wordlist_screen(
let allow_back_out = matches!(can_cancel, CanCancel::Yes);
let backspace = build_nav_button(&actions, NavIcon::Back);
let backspace_icon = style_nav_button_disabled(&backspace);
- let delete_textarea = Rc::clone(&textarea);
+ let delete_display = Rc::clone(&word_display);
let back_responder = responder.clone();
backspace
.add_click_cb(move || {
- if !textarea_is_empty(delete_textarea.as_ref()) {
- delete_textarea.delete_char();
+ let text = delete_display.get_text().unwrap();
+ let text = text.to_str().unwrap();
+ if !text.is_empty() {
+ delete_display.set_text(&text[..text.len() - 1]).unwrap();
} else if allow_back_out {
back_responder.resolve(Err(WordlistEntryAbort::Back));
}
@@ -669,31 +626,31 @@ pub fn build_wordlist_screen(
let accept = build_nav_button(&actions, NavIcon::Confirm);
let accept_icon = style_nav_button_disabled(&accept);
{
- let textarea = Rc::clone(&textarea);
+ let word_display = Rc::clone(&word_display);
accept
.add_click_cb(move || {
- responder.resolve(Ok(snapshot_text(textarea.as_ref())));
+ let text = word_display.get_text().unwrap();
+ responder.resolve(Ok(zeroize::Zeroizing::new(String::from(
+ text.to_str().unwrap(),
+ ))));
})
.expect("failed to register confirm callback");
}
// Relay the word-entry state — which letters may come next and whether the entry is a
// complete word — from the wordlist to the keys and buttons on every content change.
- let refresh_textarea = Rc::clone(&textarea);
- let refresh = Rc::new(move || {
- let (len, matches) = with_textarea_text(refresh_textarea.as_ref(), |prefix| {
- (prefix.len(), wordlist_matches(&wordlist, prefix))
- });
+ let refresh_display = Rc::clone(&word_display);
+ let refresh = move || {
+ let text = refresh_display.get_text().unwrap();
+ let prefix = text.to_str().unwrap();
+ let (len, matches) = (prefix.len(), wordlist_matches(&wordlist, prefix));
super::keyboard::set_enabled_letters(&keyboard, matches.next_letters);
set_nav_button_enabled(&backspace, &backspace_icon, len > 0 || allow_back_out);
set_nav_button_enabled(&accept, &accept_icon, matches.complete);
- });
+ };
refresh();
- let refresh_cb = Rc::clone(&refresh);
- textarea
- .add_event_cb(lvgl::LvEventCode::LV_EVENT_VALUE_CHANGED, move || {
- refresh_cb()
- })
+ word_display
+ .add_event_cb(lvgl::LvEventCode::LV_EVENT_VALUE_CHANGED, refresh)
.expect("failed to register wordlist refresh callback");
screen
@@ -782,7 +739,7 @@ pub fn build_pin_screen(
///
/// Returns the invisible storage/event textarea (the display row's child 0) that the input
/// widgets operate on.
-fn add_masked_display(screen: &LvObj, preset: &str) -> Rc<LvTextarea> {
+fn add_masked_display(screen: &LvObj, preset: &str) -> Rc<BitboxTextarea> {
let display = LvObj::with_parent(screen).unwrap();
display.set_size(380, 72);
// Fill the whole area between the title and the (bottom-anchored) keyboard, so the centred
@@ -837,7 +794,7 @@ fn add_masked_display(screen: &LvObj, preset: &str) -> Rc<LvTextarea> {
dot.add_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_HIDDEN);
dots.push(dot);
}
- let last_char_label = LvLabel::new(&display).unwrap();
+ let last_char_label = BitboxLabel::new(&display).unwrap();
last_char_label.set_style_text_color(lvgl::color::white(), 0);
last_char_label.set_style_text_font(
lvgl::fonts::INTER_REGULAR_48,
@@ -848,7 +805,7 @@ fn add_masked_display(screen: &LvObj, preset: &str) -> Rc<LvTextarea> {
// even one — the font's natural 59px line height would nudge the circles by 1px whenever
// the label appears or hides.
last_char_label.set_height(60);
- last_char_label.set_text("").unwrap();
+ last_char_label.set_text_static(Some(c""));
last_char_label.add_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_HIDDEN);
let display_textarea = Rc::clone(&textarea);
@@ -875,7 +832,10 @@ fn add_masked_display(screen: &LvObj, preset: &str) -> Rc<LvTextarea> {
.expect("entered text contains no NUL");
last_char_label.remove_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_HIDDEN);
}
- None => last_char_label.add_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_HIDDEN),
+ None => {
+ last_char_label.set_text_static(Some(c""));
+ last_char_label.add_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_HIDDEN);
+ }
}
});
refresh_display();
@@ -931,13 +891,12 @@ pub fn build_enter_string_screen(
let textarea = Rc::new(textarea);
- let keyboard = LvKeyboard::new(&screen).unwrap();
+ let keyboard = BitboxKeyboard::new(&screen).unwrap();
keyboard.set_width(380);
keyboard.set_height(260);
keyboard.set_style_flex_grow(1, 0);
// No extra margin: LVGL's flex sizing does not subtract margins when distributing
// flex_grow space, so a margin here overflows the screen's bottom padding.
- keyboard.set_popovers(false);
let show_keyboard_switch = !params.number_input;
let initial_keyboard_mode = if params.number_input {
None
@@ -950,11 +909,11 @@ pub fn build_enter_string_screen(
configure_keyboard_maps(&keyboard);
keyboard.set_mode(mode.lvgl_mode());
} else {
- keyboard.set_mode(lvgl::LvKeyboardMode::LV_KEYBOARD_MODE_NUMBER);
+ keyboard.set_mode(lvgl::BitboxKeyboardMode::Number);
}
- // Safe because the textarea and keyboard are siblings on the same screen and remain alive
- // until the whole screen is popped.
- unsafe { keyboard.set_textarea(Some(textarea.as_ref())) };
+ keyboard
+ .bind_textarea(textarea.as_ref())
+ .expect("failed to bind keyboard");
// Discard the key selection once an interaction ends (after the class handler has processed
// a legitimate click): LVGL keeps the lastly clicked key selected forever, and a press
// sliding in from the Delete/switch buttons below reaches the keyboard without a PRESSED
@@ -1008,10 +967,8 @@ pub fn build_enter_string_screen(
switch_button.set_style_bg_opa(LvOpacityLevel::LV_OPA_COVER as u8, 0);
switch_button.set_style_border_width(2, 0);
switch_button.set_style_border_color(lvgl::color::white(), 0);
- let switch_button_label = LvLabel::new(&switch_button).unwrap();
- switch_button_label
- .set_text(keyboard_mode.switch_label(allow_special_chars))
- .unwrap();
+ let switch_button_label = BitboxLabel::new(&switch_button).unwrap();
+ switch_button_label.set_text_static(Some(keyboard_mode.switch_label(allow_special_chars)));
switch_button_label.set_style_text_font(
lvgl::fonts::INTER_BOLD_32,
lvgl::LvState::LV_STATE_DEFAULT as u32,
@@ -1023,8 +980,7 @@ pub fn build_enter_string_screen(
keyboard_mode = keyboard_mode.next(allow_special_chars);
keyboard.set_mode(keyboard_mode.lvgl_mode());
switch_button_label
- .set_text(keyboard_mode.switch_label(allow_special_chars))
- .expect("valid switch label");
+ .set_text_static(Some(keyboard_mode.switch_label(allow_special_chars)));
})
.expect("failed to register keyboard switch callback");
}
@@ -1034,7 +990,7 @@ pub fn build_enter_string_screen(
&input_controls,
if show_keyboard_switch { 184 } else { 380 },
56,
- "Delete",
+ c"Delete",
move || delete_textarea.delete_char(),
);
@@ -1224,7 +1180,7 @@ mod tests {
self.screen.child(1).expect("entry display")
}
- fn textarea(&self) -> LvTextarea {
+ fn textarea(&self) -> BitboxTextarea {
self.entry_display()
.child(0)
.expect("textarea")
@@ -1259,7 +1215,13 @@ mod tests {
}
fn text(&self) -> zeroize::Zeroizing<String> {
- snapshot_text(&self.textarea())
+ let entry = self.entry_display().child(0).unwrap();
+ if entry.has_class::<class::LabelTag>() {
+ let label = entry.try_downcast::<class::LabelTag>().unwrap();
+ zeroize::Zeroizing::new(String::from(label.get_text().unwrap().to_str().unwrap()))
+ } else {
+ snapshot_text(&self.textarea())
+ }
}
fn keyboard(&self) -> LvObj {
@@ -1404,6 +1366,55 @@ mod tests {
}
}
+ #[test]
+ fn test_generic_textarea_cursor_scrolling_and_masking() {
+ let _lock = lock_and_init();
+ let params = EnterStringParams {
+ title: "Name",
+ ..Default::default()
+ };
+ let mut harness = Harness::with_params(¶ms, CanCancel::Yes, "ab");
+ let textarea = harness
+ .screen
+ .child(1)
+ .unwrap()
+ .try_downcast::<class::TextareaTag>()
+ .unwrap();
+ let keyboard = harness
+ .screen
+ .child(2)
+ .unwrap()
+ .try_downcast::<class::KeyboardTag>()
+ .unwrap();
+ let label = textarea.get_label().unwrap();
+ let area = coords(&label);
+ harness.touch.tap(area.x1, (area.y1 + area.y2) / 2);
+ assert_eq!(textarea.get_cursor_pos(), 0);
+ let area = coords(&keyboard);
+ harness.touch.tap(area.x1 + 25, area.y1 + 35);
+ assert_eq!(textarea.get_text().unwrap().to_str().unwrap(), "aab");
+ assert_eq!(textarea.get_cursor_pos(), 1);
+ textarea
+ .set_text("abcdefghijklmnopqrstuvwxyz0123456789")
+ .unwrap();
+ pump_for(40);
+ let scrolled = coords(&label);
+ let field = coords(&textarea);
+ let caret = coords(&textarea.child(1).unwrap());
+ assert!(scrolled.x1 < field.x1);
+ assert!(caret.x1 > field.x1 && caret.x2 < field.x2);
+ textarea.set_cursor_pos(0);
+ pump_for(40);
+ assert!(coords(&label).x1 > field.x1);
+ textarea.set_password_mode(true);
+ pump_for(40);
+ assert_eq!(
+ label.get_text().unwrap().to_str().unwrap(),
+ "************************************"
+ );
+ assert_eq!(textarea.get_text().unwrap().to_bytes().len(), 36);
+ }
+
#[test]
fn test_types_lowercase_and_digits() {
let _lock = lock_and_init();
@@ -2375,6 +2386,7 @@ mod tests {
harness.touch.push(x, y, false);
pump_for(120);
assert!(Harness::hidden(&preview));
+ assert_eq!(label.get_text().unwrap().to_str().unwrap(), "");
}
assert_eq!(harness.text().as_str(), "sc");
}
### src/rust/bitbox03/src/ui/keyboard.rs
@@ -25,11 +25,12 @@
use alloc::rc::Rc;
use alloc::vec;
use core::cell::{Cell, RefCell};
+use core::ffi::CStr;
use bitbox_lvgl::{
- self as lvgl, ButtonmatrixExt, LabelExt, LvButton, LvButtonmatrix, LvButtonmatrixCtrl,
- LvButtonmatrixMapEntry, LvCanvas, LvEventCode, LvLabel, LvObj, LvOpacityLevel, LvPart, LvState,
- LvTextarea, ObjExt, TextareaExt,
+ self as lvgl, BitboxLabel, BitboxTextarea, ButtonmatrixExt, LabelExt, LvButton, LvButtonmatrix,
+ LvButtonmatrixCtrl, LvButtonmatrixMapEntry, LvCanvas, LvEventCode, LvObj, LvOpacityLevel,
+ LvPart, LvState, ObjExt, TextareaExt,
};
use super::nav_button::{add_icon, enable_press_invert, style_outline_button};
@@ -283,7 +284,7 @@ struct Widgets {
key_rows: [LvButtonmatrix; ROWS],
capslock: LvButton,
capslock_icon: LvObj,
- symbols_label: LvLabel,
+ symbols_label: BitboxLabel,
}
/// Applies `mode`: swaps the key-row maps and geometry, enables/disables caps lock (it has no
@@ -324,19 +325,19 @@ fn apply_mode(widgets: &Widgets, mode: Mode) {
widgets
.symbols_label
.set_style_text_font(lvgl::fonts::INTER_REGULAR_24, 0);
- widgets.symbols_label.set_text("abc").unwrap();
+ widgets.symbols_label.set_text_static(Some(c"abc"));
} else {
widgets
.symbols_label
.set_style_text_font(lvgl::fonts::INTER_BOLD_32, 0);
- widgets.symbols_label.set_text("!@").unwrap();
+ widgets.symbols_label.set_text_static(Some(c"!@"));
}
}
/// The pressed-key preview balloon (a canvas with the balloon bitmap plus the character label).
struct Preview {
root: LvObj,
- label: LvLabel,
+ label: BitboxLabel,
/// The (row, key) the preview currently shows, to skip redundant updates from the
/// once-per-input-period `LV_EVENT_PRESSING` stream.
shown: Cell<Option<(usize, u32)>>,
@@ -369,11 +370,11 @@ impl Preview {
LvCanvas::new(&root, data, header.width, header.height).expect("key preview canvas");
canvas.align(lvgl::LvAlign::LV_ALIGN_TOP_MID, 0, 0);
- let label = LvLabel::new(&root).unwrap();
+ let label = BitboxLabel::new(&root).unwrap();
label.set_style_text_color(lvgl::color::white(), 0);
label.set_style_text_font(lvgl::fonts::INTER_BOLD_48, 0);
label.align(lvgl::LvAlign::LV_ALIGN_TOP_MID, 0, PREVIEW_LABEL_Y);
- label.set_text("").unwrap();
+ label.set_text_static(Some(c""));
Self {
root,
@@ -385,12 +386,12 @@ impl Preview {
/// Shows the balloon for the key `id` of `row` (labelled `text`), positioned over the key.
/// `count` is the row's current key count (shorter rows are centred, so it shifts key
/// positions).
- fn show(&self, count: usize, row: usize, id: u32, text: &str) {
+ fn show(&self, count: usize, row: usize, id: u32, text: &'static CStr) {
if self.shown.get() == Some((row, id)) {
return;
}
self.shown.set(Some((row, id)));
- self.label.set_text(text).expect("key text contains no NUL");
+ self.label.set_text_static(Some(text));
self.root.set_pos(
key_x(count, id as usize) + PREVIEW_OFFSET_X,
key_y(row) + PREVIEW_OFFSET_Y,
@@ -399,6 +400,7 @@ impl Preview {
}
fn hide(&self) {
+ self.label.set_text_static(Some(c""));
self.shown.set(None);
self.root.add_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_HIDDEN);
}
@@ -492,35 +494,34 @@ fn build_container(parent: &LvObj, height: i32) -> LvObj {
/// Wires a key-row buttonmatrix's input behaviour: the jet-out preview over the pressed key
/// while pressed (hidden again if the finger slides off it, which also discards the selection),
-/// insertion of the selected key's character into `textarea` on release over it (`CLICK_TRIG`),
-/// and discarding the selection once the interaction ends. `count_of_row` resolves the row's
-/// current key count (layouts with mode switching change it per call); `after_insert` runs
-/// after each inserted character (and only then — not on deletions or programmatic changes).
+/// passing the selected key's character to `insert` on release over it (`CLICK_TRIG`),
+/// and discarding the selection once the interaction ends. `map_of_row` resolves the row's
+/// current static map (layouts with mode switching change it per call). `insert` only runs for
+/// typed characters — not on deletions or programmatic changes.
fn wire_key_row<F>(
container: &LvObj,
row: usize,
- textarea: &Rc<LvTextarea>,
+ insert: Rc<dyn Fn(&str)>,
preview: &Rc<Preview>,
- count_of_row: F,
- after_insert: Option<Rc<dyn Fn()>>,
+ map_of_row: F,
) where
- F: Fn(usize) -> usize + Clone + 'static,
+ F: Fn(usize) -> &'static [LvButtonmatrixMapEntry] + Clone + 'static,
{
let matrix = matrix_handle(container, row);
{
let matrix_cb = matrix_handle(container, row);
- let textarea = Rc::clone(textarea);
- let count_of_row = count_of_row.clone();
+ let map_of_row = map_of_row.clone();
matrix
.add_event_cb(LvEventCode::LV_EVENT_VALUE_CHANGED, move || {
let id = matrix_cb.get_selected_button();
- if (id as usize) < count_of_row(row)
- && let Some(text) = matrix_cb.get_button_text(id)
- {
- let _ = textarea.add_text(text.to_str().expect("key text is ASCII"));
- if let Some(after_insert) = &after_insert {
- after_insert();
- }
+ let map = map_of_row(row);
+ if (id as usize) < map.len() - 1 {
+ insert(
+ map[id as usize]
+ .as_cstr()
+ .to_str()
+ .expect("key text is ASCII"),
+ );
}
})
.expect("failed to register key callback");
@@ -531,23 +532,14 @@ fn wire_key_row<F>(
] {
let matrix_cb = matrix_handle(container, row);
let preview = Rc::clone(preview);
- let count_of_row = count_of_row.clone();
+ let map_of_row = map_of_row.clone();
matrix
.add_event_cb(code, move || {
let id = matrix_cb.get_selected_button();
- let count = count_of_row(row);
+ let map = map_of_row(row);
+ let count = map.len() - 1;
if (id as usize) < count {
- // PRESSING fires every input period; skip the button-text lookup (which
- // allocates) while the preview already shows this key.
- if preview.shown.get() == Some((row, id)) {
- return;
- }
- match matrix_cb.get_button_text(id) {
- Some(text) => {
- preview.show(count, row, id, text.to_str().expect("key text is ASCII"))
- }
- None => preview.hide(),
- }
+ preview.show(count, row, id, map[id as usize].as_cstr());
} else {
// The finger slid off the keys (e.g. into a row gap).
preview.hide();
@@ -581,7 +573,7 @@ fn wire_key_row<F>(
///
/// Child order (see the `CHILD_INDEX_*` constants): `ROWS` key-row buttonmatrices, caps lock,
/// space bar, symbols toggle, preview balloon.
-pub fn build_keyboard(parent: &LvObj, textarea: Rc<LvTextarea>) -> LvObj {
+pub fn build_keyboard(parent: &LvObj, textarea: Rc<BitboxTextarea>) -> LvObj {
let container = build_container(parent, KEYBOARD_HEIGHT);
let mode = Rc::new(RefCell::new(Mode {
@@ -621,7 +613,7 @@ pub fn build_keyboard(parent: &LvObj, textarea: Rc<LvTextarea>) -> LvObj {
{
let textarea = Rc::clone(&textarea);
space
- .add_click_cb(move || textarea.add_char(u32::from(b' ')))
+ .add_click_cb(move || textarea.add_char(' '))
.expect("failed to register space callback");
}
@@ -633,11 +625,11 @@ pub fn build_keyboard(parent: &LvObj, textarea: Rc<LvTextarea>) -> LvObj {
FUNCTION_ROW_Y,
);
style_function_key(&symbols);
- let symbols_label = LvLabel::new(&symbols).unwrap();
+ let symbols_label = BitboxLabel::new(&symbols).unwrap();
symbols_label.set_style_text_color(lvgl::color::white(), 0);
symbols_label.set_style_text_color(lvgl::color::black(), PRESSED);
symbols_label.align(lvgl::LvAlign::LV_ALIGN_CENTER, 0, 0);
- symbols_label.set_text("").unwrap();
+ symbols_label.set_text_static(Some(c""));
let symbols_label_part = symbols.child(0).expect("symbols toggle label");
enable_press_invert(&symbols, vec![symbols_label_part]);
@@ -648,13 +640,15 @@ pub fn build_keyboard(parent: &LvObj, textarea: Rc<LvTextarea>) -> LvObj {
// active layout, so they are resolved through the mode cell on every event.
for row in 0..ROWS {
let mode = Rc::clone(&mode);
+ let textarea = Rc::clone(&textarea);
wire_key_row(
&container,
row,
- &textarea,
+ Rc::new(move |text| {
+ let _ = textarea.add_text(text);
+ }),
&preview,
- move |row| row_count(*mode.borrow(), row),
- None,
+ move |row| row_map(*mode.borrow(), row),
);
}
@@ -721,22 +715,16 @@ pub fn build_keyboard(parent: &LvObj, textarea: Rc<LvTextarea>) -> LvObj {
/// Builds the letters-only keyboard for BIP39 wordlist (recovery word) entry and appends it to
/// `parent`: the three lowercase QWERTY letter rows, without the digit row and the caps-lock /
/// space / symbols function row — no digit, space, capital or special character occurs in a
-/// BIP39 word. Typed characters are inserted into `textarea`; the jet-out preview and
+/// BIP39 word. Typed characters are passed to `insert`; the jet-out preview and
/// slide-off-to-cancel behave as on the passphrase keyboard. All keys start enabled; the caller
/// filters them with [`set_enabled_letters`].
///
-/// `after_insert` runs after each letter inserted by a key (and only then — the entry screen
-/// autocompletes there, which it must not do for deletions and cannot do from a textarea
-/// `VALUE_CHANGED` callback, where mutating the textarea would recursively re-enter that
-/// callback).
+/// `insert` runs for each letter typed by a key (and only then — the entry screen
+/// autocompletes there, which it must not do for deletions).
///
/// Child order: `WORDLIST_ROWS` key-row buttonmatrices, preview balloon
/// ([`WORDLIST_CHILD_INDEX_PREVIEW`]).
-pub fn build_wordlist_keyboard(
- parent: &LvObj,
- textarea: Rc<LvTextarea>,
- after_insert: Rc<dyn Fn()>,
-) -> LvObj {
+pub fn build_wordlist_keyboard(parent: &LvObj, insert: Rc<dyn Fn(&str)>) -> LvObj {
let container = build_container(parent, WORDLIST_KEYBOARD_HEIGHT);
for (row, letters) in WORDLIST_ROW_LETTERS.iter().enumerate() {
@@ -765,14 +753,15 @@ pub fn build_wordlist_keyboard(
let preview = Rc::new(Preview::build(&container));
for row in 0..WORDLIST_ROWS {
- wire_key_row(
- &container,
- row,
- &textarea,
- &preview,
- |row| WORDLIST_ROW_LETTERS[row].len(),
- Some(Rc::clone(&after_insert)),
- );
+ wire_key_row(&container, row, Rc::clone(&insert), &preview, |row| {
+ row_map(
+ Mode {
+ caps: false,
+ symbols: false,
+ },
+ row + 1,
+ )
+ });
}
container
### src/rust/bitbox03/src/ui/keypad.rs
@@ -7,8 +7,11 @@
use alloc::rc::Rc;
use alloc::vec;
+use core::ffi::CStr;
-use bitbox_lvgl::{self as lvgl, LabelExt, LvLabel, LvObj, LvTextarea, ObjExt, TextareaExt};
+use bitbox_lvgl::{
+ self as lvgl, BitboxLabel, BitboxTextarea, LabelExt, LvObj, ObjExt, TextareaExt,
+};
use super::keyboard::gray;
use super::nav_button::{NavIcon, build_nav_button, enable_press_invert, style_outline_button};
@@ -36,28 +39,32 @@ pub(super) fn key_center(row: usize, col: usize) -> (i32, i32) {
/// Adds one digit key: the navigation-button frame with the digit as its label; inserts the
/// digit on release.
-fn add_digit_key(container: &LvObj, textarea: &Rc<LvTextarea>, digit: u8, x: i32, y: i32) {
+fn add_digit_key(
+ container: &LvObj,
+ textarea: &Rc<BitboxTextarea>,
+ digit: &'static CStr,
+ x: i32,
+ y: i32,
+) {
let key = lvgl::LvButton::new(container).unwrap();
key.set_size(KEY_SIZE, KEY_SIZE);
key.set_pos(x, y);
key.set_style_radius(19, 0); // navigation-button corner radius
style_outline_button(&key, 3);
- let label = LvLabel::new(&key).unwrap();
+ let label = BitboxLabel::new(&key).unwrap();
label.set_style_text_color(lvgl::color::white(), 0);
label.set_style_text_color(lvgl::color::black(), PRESSED);
label.set_style_text_font(
lvgl::fonts::INTER_REGULAR_48,
lvgl::LvState::LV_STATE_DEFAULT as u32,
);
- let text = [digit];
- label
- .set_text(core::str::from_utf8(&text).expect("keypad digits are ASCII"))
- .expect("keypad digits contain no NUL");
+ label.set_text_static(Some(digit));
label.align(lvgl::LvAlign::LV_ALIGN_CENTER, 0, 0);
let label_part = key.child(0).expect("digit label");
enable_press_invert(&key, vec![label_part]);
let textarea = Rc::clone(textarea);
- key.add_click_cb(move || textarea.add_char(u32::from(digit)))
+ let digit = char::from(digit.to_bytes()[0]);
+ key.add_click_cb(move || textarea.add_char(digit))
.expect("failed to register digit callback");
}
@@ -66,7 +73,7 @@ fn add_digit_key(container: &LvObj, textarea: &Rc<LvTextarea>, digit: u8, x: i32
///
/// Child order is row-major over the grid: digits 1–9 (0..=8), backspace (9), 0 (10),
/// confirm (11).
-pub fn build_keypad<F>(parent: &LvObj, textarea: Rc<LvTextarea>, on_confirm: F) -> LvObj
+pub fn build_keypad<F>(parent: &LvObj, textarea: Rc<BitboxTextarea>, on_confirm: F) -> LvObj
where
F: FnMut() + 'static,
{
@@ -81,7 +88,10 @@ where
container.set_style_pad_right(0, 0);
container.remove_flag(lvgl::LvObjFlag::LV_OBJ_FLAG_SCROLLABLE);
- for (i, digit) in (b'1'..=b'9').enumerate() {
+ for (i, digit) in [c"1", c"2", c"3", c"4", c"5", c"6", c"7", c"8", c"9"]
+ .into_iter()
+ .enumerate()
+ {
let (row, col) = (i / 3, i % 3);
add_digit_key(
&container,
@@ -121,7 +131,7 @@ where
.add_event_cb(lvgl::LvEventCode::LV_EVENT_VALUE_CHANGED, refresh_backspace)
.expect("failed to register backspace state callback");
- add_digit_key(&container, &textarea, b'0', KEY_PITCH, bottom);
+ add_digit_key(&container, &textarea, c"0", KEY_PITCH, bottom);
let confirm = build_nav_button(&container, NavIcon::Confirm);
confirm.set_pos(2 * KEY_PITCH, bottom);
### src/rust/bitbox03/src/ui/menu.rs
@@ -3,7 +3,7 @@
use alloc::format;
use bitbox_lvgl::{
- self as lvgl, LabelExt, LvLabel, LvLabelLongMode, LvObj, LvOpacityLevel, ObjExt,
+ self as lvgl, BitboxLabel, BitboxLabelLongMode, LabelExt, LvObj, LvOpacityLevel, ObjExt,
};
use util::futures::completion::Responder;
@@ -61,19 +61,19 @@ pub fn build_menu_screen(
let title_text = title
.map(alloc::string::ToString::to_string)
.unwrap_or_else(|| format!("{:02}", index + 1));
- let title_label = LvLabel::new(&screen).unwrap();
+ let title_label = BitboxLabel::new(&screen).unwrap();
title_label.set_width(380);
- title_label.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
+ title_label.set_long_mode(BitboxLabelLongMode::Wrap);
title_label.set_text(&title_text).unwrap();
title_label.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
title_label.set_style_text_font(
lvgl::fonts::INTER_REGULAR_32,
lvgl::LvState::LV_STATE_DEFAULT as u32,
);
- let word_label = LvLabel::new(&screen).unwrap();
+ let word_label = BitboxLabel::new(&screen).unwrap();
word_label.set_width(380);
- word_label.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
+ word_label.set_long_mode(BitboxLabelLongMode::Wrap);
word_label.set_text(words[index]).unwrap();
word_label.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
word_label.set_style_text_font(
### src/rust/bitbox03/src/ui/recovery_words.rs
@@ -10,10 +10,13 @@
//! [`build_recovery_words_screen`].
use alloc::string::String;
+use alloc::vec::Vec;
use core::fmt::Write as _;
-use bitbox_hal::ui::{MAX_MNEMONIC_BYTES, UserAbort};
-use bitbox_lvgl::{self as lvgl, LabelExt, LvFont, LvLabel, LvObj, LvOpacityLevel, ObjExt, fonts};
+use bitbox_hal::ui::UserAbort;
+use bitbox_lvgl::{
+ self as lvgl, BitboxLabel, LabelExt, LvFont, LvObj, LvOpacityLevel, ObjExt, fonts,
+};
use util::futures::completion::Responder;
use super::keyboard::gray;
@@ -53,8 +56,8 @@ fn baseline_from_top(font: LvFont) -> i32 {
}
/// A borderless multi-line label for one sub-column, spacing its lines `ROW_ADVANCE` apart.
-fn build_column_label(parent: &LvObj, text: &str, font: LvFont) -> LvLabel {
- let label = LvLabel::new(parent).unwrap();
+fn build_column_label(parent: &LvObj, text: &str, font: LvFont) -> BitboxLabel {
+ let label = BitboxLabel::new(parent).unwrap();
label.set_text(text).unwrap();
label.set_style_text_font(font, lvgl::LvState::LV_STATE_DEFAULT as u32);
label.set_style_text_line_space(ROW_ADVANCE - font.line_height(), 0);
@@ -78,20 +81,23 @@ fn build_column(parent: &LvObj, words: &[&str], first_number: usize) {
column.set_style_bg_opa(LvOpacityLevel::LV_OPA_TRANSP as u8, 0);
let mut numbers_text = String::new();
- let mut words_text = zeroize::Zeroizing::new(String::with_capacity(MAX_MNEMONIC_BYTES));
+ // Reserve once so growing the buffer cannot leave earlier copies of the words behind.
+ let capacity =
+ words.iter().map(|word| word.len()).sum::<usize>() + words.len().saturating_sub(1);
+ let mut words_text = zeroize::Zeroizing::new(Vec::with_capacity(capacity));
for (i, word) in words.iter().enumerate() {
if i > 0 {
numbers_text.push('\n');
- words_text.push('\n');
+ words_text.push(b'\n');
}
write!(numbers_text, "{}", first_number + i).unwrap();
- words_text.push_str(word);
+ words_text.extend_from_slice(word.as_bytes());
}
#[cfg(test)]
assert_eq!(
words_text.capacity(),
- MAX_MNEMONIC_BYTES,
+ capacity,
"recovery-word buffer must not reallocate"
);
@@ -106,7 +112,11 @@ fn build_column(parent: &LvObj, words: &[&str], first_number: usize) {
0,
);
- let word_label = build_column_label(&column, &words_text, WORD_FONT);
+ let word_label = build_column_label(
+ &column,
+ core::str::from_utf8(&words_text).unwrap(),
+ WORD_FONT,
+ );
word_label.set_style_text_color(lvgl::color::white(), 0);
word_label.set_style_flex_grow(1, 0);
}
@@ -137,9 +147,9 @@ pub fn build_recovery_words_screen(
// where the standard 50px-padded screens put it.
screen.set_style_flex_cross_place(lvgl::LvFlexAlign::LV_FLEX_ALIGN_CENTER, 0);
- let title = LvLabel::new(&screen).unwrap();
+ let title = BitboxLabel::new(&screen).unwrap();
title.set_width(380);
- title.set_text("Recovery words").unwrap();
+ title.set_text_static(Some(c"Recovery words"));
title.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
title.set_style_text_font(
lvgl::fonts::INTER_REGULAR_32,
### src/rust/bitbox03/src/ui/slide_to_confirm.rs
@@ -23,8 +23,8 @@ use alloc::vec::Vec;
use core::cell::Cell;
use bitbox_lvgl::{
- self as lvgl, CanvasExt, LabelExt, LvCanvas, LvHandle, LvImageDsc, LvLabel, LvObj, LvObjFlag,
- LvOpacityLevel, LvSlider, ObjExt, class,
+ self as lvgl, BitboxLabel, CanvasExt, LabelExt, LvCanvas, LvHandle, LvImageDsc, LvObj,
+ LvObjFlag, LvOpacityLevel, LvSlider, ObjExt, class,
};
use core::ptr::NonNull;
@@ -132,8 +132,8 @@ pub fn build_slide_to_confirm(parent: &LvObj, on_confirm: impl FnMut() + 'static
root.set_style_pad_right(0, 0);
root.set_style_pad_row(10, 0);
- let label = LvLabel::new(&root).unwrap();
- label.set_text("Slide to confirm").unwrap();
+ let label = BitboxLabel::new(&root).unwrap();
+ label.set_text_static(Some(c"Slide to confirm"));
label.set_style_text_font(
lvgl::fonts::INTER_REGULAR_24,
lvgl::LvState::LV_STATE_DEFAULT as u32,
### src/rust/bitbox03/src/ui/status.rs
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
use bitbox_lvgl::{
- self as lvgl, LabelExt, LvAlign, LvCanvas, LvLabel, LvLabelLongMode, LvObj, LvOpacityLevel,
- ObjExt,
+ self as lvgl, BitboxLabel, BitboxLabelLongMode, LabelExt, LvAlign, LvCanvas, LvObj,
+ LvOpacityLevel, ObjExt,
};
/// Checkmark shown inside the badge circle on success (white glyph on transparent).
@@ -51,9 +51,9 @@ pub fn build_status_screen(title: &str, status_success: bool) -> LvObj {
LvCanvas::new(&badge, data, header.width, header.height).expect("status icon canvas");
glyph.align(LvAlign::LV_ALIGN_CENTER, 0, 0);
- let title_label = LvLabel::new(&screen).unwrap();
+ let title_label = BitboxLabel::new(&screen).unwrap();
title_label.set_width(380);
- title_label.set_long_mode(LvLabelLongMode::LV_LABEL_LONG_MODE_WRAP);
+ title_label.set_long_mode(BitboxLabelLongMode::Wrap);
title_label.set_text(title).unwrap();
title_label.set_style_text_align(lvgl::LvTextAlign::LV_TEXT_ALIGN_CENTER, 0);
title_label.set_style_text_font(
### test/simulator-graphical-bb03/Cargo.lock
@@ -393,6 +393,7 @@ dependencies = [
"grounded",
"tracing",
"util",
+ "zeroize",
]
[[package]]Why this scored 47/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.