From 6ec99fa7da54ee3b5759ba2092453aa899a878d9 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 17 May 2023 23:27:07 +0800 Subject: [PATCH] add multi-line text editing support to TextEntry, and insertion points TextEntry boxes can now specify "growable" as an option; if this is set true, then, the fields within are considered to be multi-line fields that can grow to fill the screen (even pushing lower ui elements off the screen...); however a text line is limited to 256 characters so generally the overflow issue is hopefully rare-ish. Left/right arrow keys conjure up an insertion point to allow for deleting and inserting text in the middle of a field. The main quirk is that if you enter text that causes a field to grow in size, the overall dialog box can't grow any larger, so the text simply overflows into the UI element above the current line, without limit. Need to check for interactions with other elements that should not be affected but it passes some simple test cases in `vault`. --- apps/vault/src/actions.rs | 2 + services/gam/src/main.rs | 2 +- services/gam/src/modal.rs | 28 ++- services/gam/src/modal/bip39entry.rs | 2 +- services/gam/src/modal/checkboxes.rs | 2 +- services/gam/src/modal/consoleinput.rs | 2 +- services/gam/src/modal/image.rs | 2 +- services/gam/src/modal/notification.rs | 2 +- services/gam/src/modal/radiobuttons.rs | 2 +- services/gam/src/modal/slider.rs | 2 +- services/gam/src/modal/textentry.rs | 270 ++++++++++++++++++++++--- services/modals/src/api.rs | 1 + services/modals/src/lib.rs | 7 + services/modals/src/main.rs | 3 + 14 files changed, 284 insertions(+), 43 deletions(-) diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index d9ba4fe49..ab418e731 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -766,6 +766,7 @@ impl<'a> ActionManager<'a> { .field_placeholder_persist(Some(pw.username), Some(password_validator)) .field_placeholder_persist(Some(pw.password), Some(password_validator)) .field_placeholder_persist(Some(pw.notes), Some(password_validator)) + .set_growable() .build().expect("modals error in edit") } else { // note is placeholder text, treat it as such self.modals @@ -774,6 +775,7 @@ impl<'a> ActionManager<'a> { .field_placeholder_persist(Some(pw.username), Some(password_validator)) .field_placeholder_persist(Some(pw.password), Some(password_validator)) .field(Some(pw.notes), Some(password_validator)) + .set_growable() .build().expect("modals error in edit") }; diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index 7de3e1b59..165d117b8 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -262,7 +262,7 @@ fn wrapped_main() -> ! { } }, TextOp::ComputeBounds => { - log::trace!("render request for {:?}", tv); + log::trace!("bounds request for {:?}", tv); tv.set_dry_run(true); if tv.clip_rect.is_none() { diff --git a/services/gam/src/modal.rs b/services/gam/src/modal.rs index 548447db4..c66ee93ab 100644 --- a/services/gam/src/modal.rs +++ b/services/gam/src/modal.rs @@ -51,7 +51,7 @@ pub enum ActionType { #[enum_dispatch] pub trait ActionApi { - fn height(&self, glyph_height: i16, margin: i16) -> i16 {glyph_height + margin * 2} + fn height(&self, glyph_height: i16, margin: i16, _modal: &Modal) -> i16 {glyph_height + margin * 2} fn redraw(&self, _at_height: i16, _modal: &Modal) { unimplemented!() } fn close(&mut self) {} fn is_password(&self) -> bool { false } @@ -93,6 +93,7 @@ pub struct TextEntryPayload { pub content: String::<256>, pub placeholder: Option>, pub placeholder_persist: bool, + pub insertion_point: Option, } impl TextEntryPayload { @@ -102,11 +103,12 @@ impl TextEntryPayload { content: Default::default(), placeholder: Default::default(), placeholder_persist: false, + insertion_point: None, } } pub fn new_with_fields(content: String::<256>, placeholder: Option>) -> Self { - TextEntryPayload { dirty: false, content: content, placeholder: placeholder, placeholder_persist: false } + TextEntryPayload { dirty: false, content: content, placeholder: placeholder, placeholder_persist: false, insertion_point: None } } /// Ensures that 0's are written to the storage of this struct, and not optimized out; important for password fields. pub fn volatile_clear(&mut self) { @@ -190,6 +192,14 @@ pub struct Modal<'a> { pub top_text: Option, pub bot_text: Option, pub action: ActionType, + /// This is a slightly unsafe option, in that it only works if you have a simple TextEntry + /// box. It enables Line-by-line text reflow selection. If false, then each entry gets only one line. + /// If set to true, operations may slow down proportionally with the size of the text as we have to + /// recompute text reflow every time the object is touched. The algorithm will greedily consume + /// space in the canvas until the entire canvas is filled with the TextEntry box. This means that + /// if you have a compound modal (multiple elements in it), the extra elements will be flowed off + /// the bottom. + pub growable: bool, //pub index: usize, // currently selected item pub canvas: Gid, @@ -197,6 +207,7 @@ pub struct Modal<'a> { pub margin: i16, pub line_height: i16, pub canvas_width: i16, + pub maximal_height: i16, pub inverted: bool, pub style: GlyphStyle, pub helper_data: Option>, @@ -256,7 +267,7 @@ fn recompute_canvas(modal: &mut Modal, top_text: Option<&str>, bot_text: Option< // compute height of action item log::trace!("step 1 total_height: {}", total_height); - total_height += modal.action.height(modal.line_height, modal.margin); + total_height += modal.action.height(modal.line_height, modal.margin, &modal); total_height += modal.margin; // compute height of bot_text, if any @@ -357,6 +368,7 @@ impl<'a> Modal<'a> { margin, line_height, canvas_width: canvas_bounds.x, // memoize this, it shouldn't change + maximal_height: 402, // arbitrary number set for aesthetic reasons; limits growth of modals that request reflowable/growable text boxes inverted, style, helper_data: None, @@ -365,6 +377,7 @@ impl<'a> Modal<'a> { bot_dirty: true, top_memoized_height: None, bot_memoized_height: None, + growable: false, }; recompute_canvas(&mut modal, top_text, bot_text, style); modal @@ -452,7 +465,7 @@ impl<'a> Modal<'a> { self.top_dirty = false; } - let action_height = self.action.height(self.line_height, self.margin); + let action_height = self.action.height(self.line_height, self.margin, &self); if !do_redraw { // the action area wasn't blanked, so blank it as prep for the action redraw self.gam.draw_rectangle(self.canvas, @@ -497,6 +510,13 @@ impl<'a> Modal<'a> { self.redraw(); } + /// This empowers an action within a modal to potentially consume all the available height in a canvas + /// The current implementation works if you have a "simple" TextEntry box, but it will fail if you have + /// stuff below it because the algorithm can't "see" the reserved space at the moment for extra items below. + pub fn set_growable(&mut self, state: bool) { + self.growable = state; + } + /// this function will modify UX elements if any of the arguments are Some() /// if None, the element is unchanged. /// If a text section is set to remove, but Some() is given for the update, the text is not removed, and instead replaced with the updated text. diff --git a/services/gam/src/modal/bip39entry.rs b/services/gam/src/modal/bip39entry.rs index 67ac22d11..985b88b54 100644 --- a/services/gam/src/modal/bip39entry.rs +++ b/services/gam/src/modal/bip39entry.rs @@ -77,7 +77,7 @@ impl ActionApi for Bip39Entry { } /// The total canvas height is computed with this API call /// The canvas height is not dynamically adjustable for modals. - fn height(&self, glyph_height: i16, margin: i16) -> i16 { + fn height(&self, glyph_height: i16, margin: i16, _modal: &Modal) -> i16 { /* cat <-- active entry 1 line + 2x margin diff --git a/services/gam/src/modal/checkboxes.rs b/services/gam/src/modal/checkboxes.rs index 3f3e1a26c..f1496e034 100644 --- a/services/gam/src/modal/checkboxes.rs +++ b/services/gam/src/modal/checkboxes.rs @@ -44,7 +44,7 @@ impl CheckBoxes { } impl ActionApi for CheckBoxes { fn set_action_opcode(&mut self, op: u32) {self.action_opcode = op} - fn height(&self, glyph_height: i16, margin: i16) -> i16 { + fn height(&self, glyph_height: i16, margin: i16, _modal: &Modal) -> i16 { // total items, then +1 for the "Okay" message (self.items.len() as i16 + 1) * glyph_height + margin * 2 + 5 // some slop needed because of the prompt character } diff --git a/services/gam/src/modal/consoleinput.rs b/services/gam/src/modal/consoleinput.rs index 54268ab03..2f2ce083c 100644 --- a/services/gam/src/modal/consoleinput.rs +++ b/services/gam/src/modal/consoleinput.rs @@ -30,7 +30,7 @@ impl ConsoleInput { } impl ActionApi for ConsoleInput { fn set_action_opcode(&mut self, op: u32) {self.action_opcode = op} - fn height(&self, _glyph_height: i16, margin: i16) -> i16 { + fn height(&self, _glyph_height: i16, margin: i16, _modal: &Modal) -> i16 { margin } fn redraw(&self, _at_height: i16, _modal: &Modal) { diff --git a/services/gam/src/modal/image.rs b/services/gam/src/modal/image.rs index ba65cc834..c3954676c 100644 --- a/services/gam/src/modal/image.rs +++ b/services/gam/src/modal/image.rs @@ -28,7 +28,7 @@ impl ActionApi for Image { fn set_action_opcode(&mut self, op: u32) { self.action_opcode = op } - fn height(&self, _glyph_height: i16, margin: i16) -> i16 { + fn height(&self, _glyph_height: i16, margin: i16, _modal: &Modal) -> i16 { let bm_height = match &self.bitmap { Some(bm) => bm.bound.br.y - bm.bound.tl.y, None => 0, diff --git a/services/gam/src/modal/notification.rs b/services/gam/src/modal/notification.rs index 1a662e091..e715e78b8 100644 --- a/services/gam/src/modal/notification.rs +++ b/services/gam/src/modal/notification.rs @@ -151,7 +151,7 @@ impl ActionApi for Notification { fn set_action_opcode(&mut self, op: u32) { self.action_opcode = op } - fn height(&self, glyph_height: i16, margin: i16) -> i16 { + fn height(&self, glyph_height: i16, margin: i16, _modal: &Modal) -> i16 { if self.manual_dismiss { let qr_height = if self.qrwidth > 0 { 300 } else { 0 }; glyph_height + margin * 2 + 5 + qr_height diff --git a/services/gam/src/modal/radiobuttons.rs b/services/gam/src/modal/radiobuttons.rs index 68e4012a8..883e24e13 100644 --- a/services/gam/src/modal/radiobuttons.rs +++ b/services/gam/src/modal/radiobuttons.rs @@ -51,7 +51,7 @@ impl RadioButtons { } impl ActionApi for RadioButtons { fn set_action_opcode(&mut self, op: u32) {self.action_opcode = op} - fn height(&self, glyph_height: i16, margin: i16) -> i16 { + fn height(&self, glyph_height: i16, margin: i16, _modal: &Modal) -> i16 { // total items, then +1 for the "Okay" message (self.items.len() as i16 + 1) * glyph_height + margin * 2 + margin * 2 + 5 // +4 for some bottom margin slop } diff --git a/services/gam/src/modal/slider.rs b/services/gam/src/modal/slider.rs index c28a29dcd..78f34ac73 100644 --- a/services/gam/src/modal/slider.rs +++ b/services/gam/src/modal/slider.rs @@ -69,7 +69,7 @@ impl Slider { } } impl ActionApi for Slider { - fn height(&self, glyph_height: i16, margin: i16) -> i16 { + fn height(&self, glyph_height: i16, margin: i16, _modal: &Modal) -> i16 { /* margin min max <- glyph height diff --git a/services/gam/src/modal/textentry.rs b/services/gam/src/modal/textentry.rs index 462297376..6a3c0f381 100644 --- a/services/gam/src/modal/textentry.rs +++ b/services/gam/src/modal/textentry.rs @@ -7,6 +7,7 @@ use num_traits::*; use core::fmt::Write; use core::cell::Cell; +use std::cell::RefCell; // TODO: figure out this, do we really have to limit ourselves to 10? const MAX_FIELDS: i16 = 10; @@ -56,6 +57,10 @@ pub struct TextEntry { /// instead of having it re-appear every time the text area is cleared keys_hit: [bool; MAX_FIELDS as usize], // gam: crate::Gam, // no GAM field because this needs to be a clone-capable structure. We create a GAM handle when we need it. + /// Stores the allowed height of a given text line, based on the contents and the space available + /// in the box. The height of a given line may be limited to make sure there is enough space for + /// later lines to be rendered. + action_payloads_allowed_heights: RefCell::>, } impl Default for TextEntry { @@ -71,6 +76,7 @@ impl Default for TextEntry { max_field_amount: 0, field_height: Cell::new(0), keys_hit: [false; MAX_FIELDS as usize], + action_payloads_allowed_heights: RefCell::new(Vec::new()), } } } @@ -111,6 +117,7 @@ impl TextEntry { element.placeholder = None; element.placeholder_persist = false; } + element.insertion_point = None; } } @@ -118,6 +125,13 @@ impl TextEntry { self.max_field_amount = fields; self.keys_hit = [false; MAX_FIELDS as usize]; } + fn get_bullet_margin(&self) -> i16 { + if self.action_payloads.len() > 1 { + 17 // this is the margin for drawing the selection bullet + } else { + 0 // no selection bullet + } + } } @@ -128,7 +142,7 @@ impl ActionApi for TextEntry { } /// The total canvas height is computed with this API call /// The canvas height is not dynamically adjustable for modals. - fn height(&self, glyph_height: i16, margin: i16) -> i16 { + fn height(&self, glyph_height: i16, margin: i16, modal: &Modal) -> i16 { /* ------------------- | **** | <-- glyph_height + 2*margin @@ -147,8 +161,100 @@ impl ActionApi for TextEntry { self.field_height.set(glyph_height + 2*margin); // stash a copy for later // compute the overall_height of the entry fields - let mut overall_height = - self.field_height.get() * self.action_payloads.len() as i16; + let mut overall_height = if modal.growable { + let mut editing = false; + for &hit in self.keys_hit.iter() { + if hit { + editing = true; + } + } + if editing { + // don't recompute heights if text fields are being edited + let mut sum = 0; + for &prev_heights in self.action_payloads_allowed_heights.borrow().iter() { + sum += prev_heights; + } + sum + } else { + self.action_payloads_allowed_heights.borrow_mut().clear(); + let growable_limit = modal.maximal_height; + // minimum size required to display exactly one line for every field. + // decrement this by a field_height.get() for every line of content computed. + let mut minimum_size_remaining = self.field_height.get() * self.action_payloads.len() as i16; + if growable_limit < minimum_size_remaining + self.field_height.get() { + // if the user is dumb and specified a growable limit that allows no space for growth, + // "snap" the user spec to something big enough to actually show one line of each bit of text, + // and skip the computation because we know there is nothing to gain from doing it. + for _ in 0..self.action_payloads.len() { + self.action_payloads_allowed_heights.borrow_mut().push(self.field_height.get()); + } + minimum_size_remaining + } else { + let bullet_margin = self.get_bullet_margin(); + let left_text_margin = modal.margin + bullet_margin; // space for the bullet point on the left, if it's there + let mut current_height = 0; + + for payload in self.action_payloads.iter() { + let mut tv = TextView::new( + modal.canvas, + TextBounds::GrowableFromBl( + Point::new(left_text_margin, current_height), + (modal.canvas_width - (modal.margin + bullet_margin) - left_text_margin) as u16 + ) + ); + tv.ellipsis = false; + tv.invert = self.is_password; + tv.style = if self.is_password { + GlyphStyle::Monospace + } else { + modal.style + }; + tv.margin = Point::new(0, 0); + tv.draw_border = false; + tv.text.clear(); + let content = { + if payload.placeholder.is_some() && payload.content.len().is_zero() { + let placeholder_content = payload.placeholder.unwrap(); + placeholder_content.to_string() + } else { + payload.content.to_string() + } + }; + write!(tv.text, "{}", &content).unwrap(); + // select to just compute bounds, not render the text + modal.gam.bounds_compute_textview(&mut tv).expect("couldn't flow textview"); + if let Some(computed_bounds) = tv.bounds_computed { + log::debug!("computed height: {} for {}", computed_bounds.height(), content); + // see if we can "afford" to grow the text to accommodate the total height + let required_extra_height = + (computed_bounds.height() as i16 // height of text as flowed, with no margins + + 2*margin // margin between boxes + + minimum_size_remaining) + .saturating_sub(self.field_height.get()); // subtract one line from the size remaining to account for the fact that we allocated one line for this field already + let provisioned_height = if required_extra_height + current_height > growable_limit { + // it doesn't fit, reduce height so it does fit + // this algorithm will greedily allocate height to the first fields, but will always leave + // at least one line for the remaining yet-to-be-flowed text fields + growable_limit - current_height + // we could, I suppose, at this point just stop rendering the future fields and + // populate the allowable heights based on one line each for the remainder... + } else { + // it can fit, move on to the next field + computed_bounds.height() as i16 + 2*margin + }; + self.action_payloads_allowed_heights.borrow_mut().push(provisioned_height); + current_height += provisioned_height; // reset the current height to after the computed height + minimum_size_remaining -= self.field_height.get(); // decrement one line from the minimum remaining + } else { + log::warn!("{} did not have a computed height!", content); + } + } + current_height + } + } + } else { + self.field_height.get() * self.action_payloads.len() as i16 + }; // if we're a password, we add an extra glyph_height to the bottom for the text visibility items if self.is_password { @@ -168,13 +274,10 @@ impl ActionApi for TextEntry { let mut current_height = at_height; let payloads = self.action_payloads.clone(); - let bullet_margin = if payloads.len() > 1 { - 17 // this is the margin for drawing the selection bullet - } else { - 0 // no selection bullet - }; + let bullet_margin = self.get_bullet_margin(); for (index, payload) in payloads.iter().enumerate() { + log::debug!("{}: {}", index, current_height); if index as i16 == self.selected_field && payloads.len() > 1 { // draw the dot let mut tv = TextView::new( @@ -195,12 +298,24 @@ impl ActionApi for TextEntry { let left_text_margin = modal.margin + bullet_margin; // space for the bullet point on the left, if it's there // draw the currently entered text - let mut tv = TextView::new( - modal.canvas, - TextBounds::BoundingBox(Rectangle::new( - Point::new(left_text_margin, current_height), - Point::new(modal.canvas_width - (modal.margin + bullet_margin), current_height + modal.line_height)) - )); + let mut tv = if modal.growable { + assert!(self.action_payloads_allowed_heights.borrow().len() == payloads.len()); + // growable limit was set, we know what the height of every field should be already, in theory! + TextView::new( + modal.canvas, + TextBounds::GrowableFromBl( + Point::new(left_text_margin, current_height + self.action_payloads_allowed_heights.borrow()[index] - modal.margin - 4), + (modal.canvas_width - (modal.margin + bullet_margin)) as u16 + ) + ) + } else { + TextView::new( + modal.canvas, + TextBounds::BoundingBox(Rectangle::new( + Point::new(left_text_margin, current_height), + Point::new(modal.canvas_width - (modal.margin + bullet_margin), current_height + modal.line_height)) + )) + }; tv.ellipsis = true; tv.invert = self.is_password; tv.style = if self.is_password { @@ -215,7 +330,11 @@ impl ActionApi for TextEntry { }; tv.margin = Point::new(0, 0); tv.draw_border = false; - tv.insertion = Some(payload.content.len() as i32); + tv.insertion = if let Some(index) = payload.insertion_point { + Some(index as i32) + } else { + Some(payload.content.len() as i32) + }; tv.text.clear(); // make sure this is blank let payload_chars = payload.content.as_str().unwrap().chars().count(); // TODO: condense the "above MAX_CHARS" chars length path a bit -- written out "the dumb way" just to reason out the logic a bit @@ -231,10 +350,18 @@ impl ActionApi for TextEntry { }; log::trace!("action payload: {}", content); - if payload_chars < MAX_CHARS { + if modal.growable { + tv.bounds_hint = TextBounds::GrowableFromBl( + Point::new(left_text_margin, current_height + self.action_payloads_allowed_heights.borrow()[index] - modal.margin - 4), + (modal.canvas_width - (modal.margin + bullet_margin) - left_text_margin) as u16, + ); write!(tv.text, "{}", content).unwrap(); } else { - write!(tv.text, "...{}", &content[content.chars().count()-(MAX_CHARS - 3)..]).unwrap(); + if payload_chars < MAX_CHARS { + write!(tv.text, "{}", content).unwrap(); + } else { + write!(tv.text, "...{}", &content[content.chars().count()-(MAX_CHARS - 3)..]).unwrap(); + } } modal.gam.post_textview(&mut tv).expect("couldn't post textview"); }, @@ -356,13 +483,22 @@ impl ActionApi for TextEntry { } // draw a line for where text gets entered (don't use a box, fitting could be awkward) + let line_height = if modal.growable { + self.action_payloads_allowed_heights.borrow()[index] - modal.margin + } else { + modal.line_height + }; modal.gam.draw_line(modal.canvas, Line::new_with_style( - Point::new(left_text_margin, current_height + modal.line_height + 3), - Point::new(modal.canvas_width - (modal.margin + bullet_margin), current_height + modal.line_height + 3), + Point::new(left_text_margin, current_height + line_height + 3), + Point::new(modal.canvas_width - (modal.margin + bullet_margin), current_height + line_height + 3), DrawStyle::new(color, color, 1)) ).expect("couldn't draw entry line"); - current_height += self.field_height.get(); + if modal.growable { + current_height += self.action_payloads_allowed_heights.borrow()[index]; + } else { + current_height += self.field_height.get(); + } } } fn key_action(&mut self, k: char) -> Option { @@ -390,6 +526,12 @@ impl ActionApi for TextEntry { if let Some(placeholder) = payload.placeholder { payload.content.append(placeholder.to_str()).ok(); } + } else { + if let Some(index) = payload.insertion_point { + payload.insertion_point = Some(index.saturating_sub(1)); + } else { + payload.insertion_point = Some(payload.content.len().saturating_sub(1)); + } } } }, @@ -410,6 +552,14 @@ impl ActionApi for TextEntry { if let Some(placeholder) = payload.placeholder { payload.content.append(placeholder.to_str()).ok(); } + } else { + if let Some(index) = payload.insertion_point.take() { + if index + 1 < payload.content.len() { + payload.insertion_point = Some(index + 1); + } + } else { + // going right on a field without an insertion point does nothing + } } } }, @@ -477,16 +627,53 @@ impl ActionApi for TextEntry { // copy the placeholder into the content string before processing the backspace payload.content.append(payload.placeholder.unwrap().to_str()).ok(); } - // coded in a conservative manner to avoid temporary allocations that can leave the plaintext on the stack - if payload.content.len() > 0 { // don't backspace if we have no string. - let mut temp_str = String::<256>::from_str(payload.content.as_str().unwrap()); - let cur_len = temp_str.as_str().unwrap().chars().count(); - let mut c_iter = temp_str.as_str().unwrap().chars(); - payload.content.clear(); - for _ in 0..cur_len-1 { - payload.content.push(c_iter.next().unwrap()).unwrap(); + if let Some(insertion_point) = payload.insertion_point { + if insertion_point > 0 { + assert!(insertion_point < payload.content.len(), "insertion point beyond content length!"); + let new_len = payload.content.as_str().unwrap().chars().count() - 1; + + // have to use a temporary string because index operators are not implemented on Xous strings + let mut temp_str = String::<256>::new(); + let mut original = payload.content.as_str().unwrap().chars().enumerate().peekable(); + // copy the data over, skipping the character that was deleted + loop { + if let Some((index, c)) = original.next() { + if index < insertion_point.saturating_sub(1) { + temp_str.push(c).ok(); + } else { + if let Some((_, next_char)) = original.peek() { + temp_str.push(*next_char).ok(); + } else { + break; + } + } + } else { + break; + } + } + // now copy the data back into the original string + let mut c_iter = temp_str.as_str().unwrap().chars(); + payload.content.clear(); + for _ in 0..new_len { + payload.content.push(c_iter.next().unwrap()).unwrap(); + } + // clear the temp string + temp_str.volatile_clear(); + // bring the insertion point back one index + payload.insertion_point = Some(insertion_point.saturating_sub(1)); + } + } else { + // coded in a conservative manner to avoid temporary allocations that can leave the plaintext on the stack + if payload.content.len() > 0 { // don't backspace if we have no string. + let mut temp_str = String::<256>::from_str(payload.content.as_str().unwrap()); + let cur_len = temp_str.as_str().unwrap().chars().count(); + let mut c_iter = temp_str.as_str().unwrap().chars(); + payload.content.clear(); + for _ in 0..cur_len-1 { + payload.content.push(c_iter.next().unwrap()).unwrap(); + } + temp_str.volatile_clear(); } - temp_str.volatile_clear(); } } _ => { // text entry @@ -505,9 +692,30 @@ impl ActionApi for TextEntry { tts.tts_blocking(&k.to_string()).unwrap(); } match k { - '\u{f701}' | '\u{f700}' => (), + '\u{f701}' | '\u{f700}' => (), _ => { - payload.content.push(k).expect("ran out of space storing password"); + if let Some(insertion_point) = payload.insertion_point { + if insertion_point >= payload.content.len() { + payload.content.push(k).expect("ran out of space storing password"); + payload.insertion_point = None; + } else { + // have to use a temporary string because index operators are not implemented on Xous strings + let mut temp_str = String::<256>::from_str(payload.content.as_str().unwrap()); + let cur_len = temp_str.as_str().unwrap().chars().count(); + let mut c_iter = temp_str.as_str().unwrap().chars(); + payload.content.clear(); + for i in 0..cur_len { + if i == insertion_point { + payload.content.push(k).ok(); // don't panic if we type too much, just silently drop the character + } + payload.content.push(c_iter.next().unwrap()).unwrap(); + } + payload.insertion_point = Some(insertion_point + 1); + temp_str.volatile_clear(); + } + } else { + payload.content.push(k).ok(); // don't panic if we type too much, just silently drop the character + } log::trace!("****update payload: {}", payload.content); payload.dirty = true; } diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs index c15be8c1b..e84c8ba8c 100644 --- a/services/modals/src/api.rs +++ b/services/modals/src/api.rs @@ -33,6 +33,7 @@ pub struct ManagedPromptWithTextResponse { pub fields: u32, /// placeholders pub placeholders: Option<[Option<(xous_ipc::String<256>, bool)>; 10]>, + pub growable: bool, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 4d37e2042..b41e59e0a 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -22,6 +22,7 @@ pub struct AlertModalBuilder<'a> { prompt: String, validators: Vec>, placeholders: Vec>, + growable: bool, modals: &'a Modals, } @@ -56,6 +57,10 @@ impl<'a> AlertModalBuilder<'a> { } self } + pub fn set_growable(&'a mut self) -> &'a mut Self { + self.growable = true; + self + } pub fn build(&self) -> Result { self.modals.lock(); @@ -97,6 +102,7 @@ impl<'a> AlertModalBuilder<'a> { prompt: xous_ipc::String::from_str(&self.prompt), fields: fields_amt as u32, placeholders: final_placeholders, + growable: self.growable, }; // question: do we want to add a retry limit? @@ -190,6 +196,7 @@ impl Modals { validators: vec![], placeholders: vec![], modals: self, + growable: false, } } diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index 774f4f094..70f5b5d34 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -483,6 +483,8 @@ fn wrapped_main() -> ! { log::debug!("initiating text entry modal"); #[cfg(feature = "tts")] tts.tts_simple(config.prompt.as_str().unwrap()).unwrap(); + log::info!("setting growable to: {:?}", config.growable); + renderer_modal.set_growable(config.growable); renderer_modal.modify( Some(ActionType::TextEntry({ let mut ta = text_action.clone(); @@ -815,6 +817,7 @@ fn wrapped_main() -> ! { }, Some(Opcode::TextEntryReturn) => match op { RendererState::RunText(_config) => { + renderer_modal.set_growable(false); // reset the growable state, it's assumed to be default false log::trace!("validating text entry modal"); let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };