password modal box now nominally works

This commit is contained in:
bunnie 2021-07-27 17:30:37 +08:00
parent 1a65cd3389
commit 4affdabc73
10 changed files with 121 additions and 61 deletions

View file

@ -161,4 +161,5 @@ pub(crate) enum Return {
SetCanvasBoundsReturn(SetCanvasBoundsRequest),
ContentCanvasReturn(Option<Gid>),
Failure,
NotCurrentlyDrawable,
}

View file

@ -85,6 +85,9 @@ impl Gam {
tv.bounds_computed = tvr.bounds_computed;
tv.cursor = tvr.cursor;
}
api::Return::NotCurrentlyDrawable => {
tv.bounds_computed = None;
}
_ => panic!("GAM_API: post_textview got a return value from the server that isn't expected or handled")
}
tv.set_op(TextOp::Nop);

View file

@ -776,6 +776,8 @@ fn xmain() -> ! {
}
} else {
info!("attempt to draw TextView on non-drawable canvas. Not fatal, but request ignored. {:?}", tv);
let ret = api::Return::NotCurrentlyDrawable;
buffer.replace(ret).unwrap();
}
} else {
info!("bogus GID {:?} in TextView {}, not doing anything in response to draw request.", tv.get_canvas_gid(), tv.text);

View file

@ -68,31 +68,33 @@ const MAX_ITEMS: usize = 8;
#[derive(Debug, Copy, Clone)]
pub struct ItemName(String::<64>);
#[derive(Debug, Clone)]
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone, Eq, PartialEq)]
pub struct TextEntryPayload(String::<256>);
impl TextEntryPayload {
pub fn new() -> Self {
TextEntryPayload(String::<256>::new())
}
}
impl Drop for TextEntryPayload {
fn drop(&mut self) {
pub fn volatile_clear(&mut self) {
self.0.volatile_clear(); // volatile_clear() ensures that 0's are written and not optimized out; important for password fields
}
pub fn as_str(&self) -> &str {
self.0.as_str().expect("couldn't convert password string")
}
}
#[derive(Debug, Copy, Clone)]
pub struct RadioButtonPayload(ItemName); // returns the name of the item corresponding to the radio button selection
#[derive(Debug, Copy, Clone)]
pub struct CheckBoxPayload([Option<ItemName>; MAX_ITEMS]); // returns a list of potential items that could be selected
#[derive(Debug, Copy, Clone)]
#[derive(Debug, Copy, Clone, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum TextEntryVisibility {
/// text is fully visible
Visible,
Visible = 0,
/// only last chars are shown of text entry, the rest obscured with *
LastChars,
LastChars = 1,
/// all chars hidden as *
Hidden,
Hidden = 2,
}
#[derive(Debug, Clone)]
pub struct TextEntry {
@ -117,7 +119,7 @@ impl ActionApi for TextEntry {
auto-closes on enter
*/
glyph_height + 2*margin + glyph_height + 2*margin
glyph_height + 2*margin + glyph_height + 2*margin + 8 // 8 pixels extra margin because the emoji glyphs are oversized
}
fn redraw(&self, at_height: i16, modal: &Modal) {
let color = if self.is_password {
@ -142,6 +144,7 @@ impl ActionApi for TextEntry {
tv.text.clear(); // make sure this is blank
match self.visibility {
TextEntryVisibility::Visible => {
log::trace!("action payload: {}", self.action_payload.0.as_str().unwrap());
write!(tv.text, "{}", self.action_payload.0.as_str().unwrap());
modal.gam.post_textview(&mut tv).expect("couldn't post textview");
},
@ -152,13 +155,13 @@ impl ActionApi for TextEntry {
modal.gam.post_textview(&mut tv).expect("couldn't post textview");
},
TextEntryVisibility::LastChars => {
let hide_to = if tv.text.len() >= 2 {
tv.text.len() - 2
let hide_to = if self.action_payload.0.as_str().unwrap().chars().count() >= 2 {
self.action_payload.0.as_str().unwrap().chars().count() - 2
} else {
0
};
for (index, ch) in self.action_payload.0.as_str().unwrap().chars().enumerate() {
if index <= hide_to {
if index < hide_to {
tv.text.push('*').expect("text field too long");
} else {
tv.text.push(ch).expect("text field too long");
@ -211,6 +214,53 @@ impl ActionApi for TextEntry {
DrawStyle::new(color, color, 1))
).expect("couldn't draw entry line");
}
fn key_action(&mut self, k: char) {
log::trace!("key_action: {}", k);
match k {
'←' => {
if self.visibility as u32 > 0 {
match FromPrimitive::from_u32(self.visibility as u32 - 1) {
Some(new_visibility) => {
log::trace!("new visibility: {:?}", new_visibility);
self.visibility = new_visibility;
},
_ => {
panic!("internal error: an TextEntryVisibility did not resolve correctly");
}
}
}
},
'→' => {
if (self.visibility as u32) < (TextEntryVisibility::Hidden as u32) {
match FromPrimitive::from_u32(self.visibility as u32 + 1) {
Some(new_visibility) => {
log::trace!("new visibility: {:?}", new_visibility);
self.visibility = new_visibility
},
_ => {
panic!("internal error: an TextEntryVisibility did not resolve correctly");
}
}
}
},
'∴' | '\u{d}' => {
let mut buf = Buffer::into_buf(self.action_payload).expect("couldn't convert message to payload");
buf.lend(self.action_conn, self.action_opcode).map(|_| ()).expect("couldn't send action message");
self.action_payload.volatile_clear(); // ensure the local copy of text is zero'd out
buf.volatile_clear(); // ensure that the copy of the text used to send the message is also zero'd out
}
'↑' | '↓' => {
// ignore these navigation keys
}
'\u{0}' => {
// ignore null messages
}
_ => { // text entry
self.action_payload.0.push(k).expect("ran out of space storing password");
log::trace!("****update payload: {}", self.action_payload.0);
}
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct RadioButtons {
@ -263,12 +313,18 @@ impl ActionApi for Slider {
}
}
#[enum_dispatch]
trait ActionApi {
fn height(&self, glyph_height: i16, margin: i16) -> i16 {glyph_height + margin * 2}
fn redraw(&self, at_height: i16, modal: &Modal) { unimplemented!() }
fn close(&mut self) {}
fn is_password(&self) -> bool { false }
/// navigation is one of '∴' | '←' | '→' | '↑' | '↓'
fn key_action(&mut self, key: char) {}
}
#[enum_dispatch(ActionApi)]
@ -471,50 +527,21 @@ impl Modal {
pub fn key_event(&mut self, keys: [char; 4]) {
for &k in keys.iter() {
log::debug!("got key '{}'", k);
match k {
'∴' => {
/*
if let Some(mi) = self.items[self.index] {
// give up focus before issuing the command, as some commands conflict with loss of focus...
if mi.close_on_select {
self.gam.relinquish_focus().unwrap();
}
log::debug!("doing modal action for {}", mi.name);
match mi.action_payload {
ModalPayload::Scalar(args) => {
xous::send_message(mi.action_conn,
xous::Message::new_scalar(mi.action_opcode as usize,
args[0] as usize, args[1] as usize, args[2] as usize, args[3] as usize)
).expect("couldn't send modal action");
},
ModalPayload::Memory((_buf, _len)) => {
unimplemented!("modal buffer targets are a future feature");
}
}
self.index = 0; // reset the index to 0
if k != '\u{0}' {
log::debug!("got key '{}'", k);
self.action.key_action(k); // this is where the action is at
match k {
'∴' | '\u{d}' => {
log::trace!("closing modal");
// if it's a "close" button, invoke the GAM to put our box away
self.gam.relinquish_focus().unwrap();
}
_ => {
// already handled by key_action() above
}
*/
self.gam.redraw().unwrap();
},
'←' => {
// placeholder
log::trace!("got left arrow");
}
'→' => {
// placeholder
log::trace!("got right arrow");
}
'↑' => {
//self.prev_item();
self.gam.redraw().unwrap();
}
'↓' => {
//self.next_item();
self.gam.redraw().unwrap();
}
_ => {}
}
}
self.redraw();
}
}

View file

@ -11,6 +11,9 @@ pub(crate) enum Opcode {
TestUx,
/// UX opcodes
PasswordModalEntry,
/// Suspend/resume callback
SuspendResume,

View file

@ -55,11 +55,14 @@ mod implementation {
}
pub(crate) fn rootkeys_ux_thread() {
let xns = xous_names::XousNames::new().unwrap();
let main_conn = xns.request_connection_blocking(api::SERVER_NAME_KEYS).expect("rootkeys password thread can't connect to main thread");
let password_action = gam::modal::TextEntry {
is_password: true,
visibility: gam::modal::TextEntryVisibility::LastChars,
action_conn: 0, //place holder
action_opcode: 0, // placeholder
action_conn: main_conn,
action_opcode: Opcode::PasswordModalEntry.to_u32().unwrap(),
action_payload: TextEntryPayload::new(),
};
log::trace!("building ux thread modal");
@ -67,7 +70,7 @@ pub(crate) fn rootkeys_ux_thread() {
crate::ROOTKEY_MODAL_NAME,
gam::ActionType::TextEntry(password_action),
Some(t!("rootpass.top", xous::LANG)),
Some("Underneath text"),
None,
GlyphStyle::Small,
);
log::trace!("ux thread modal: {:?}", modal);
@ -129,9 +132,10 @@ fn xmain() -> ! {
/*
Connections allowed to the keys server:
1. Shellchat (to originate update test requests)
2. Password entry UX thread
2. (future) PDDB
*/
let keys_sid = xns.register_name(api::SERVER_NAME_KEYS, Some(1)).expect("can't register server");
let keys_sid = xns.register_name(api::SERVER_NAME_KEYS, Some(2)).expect("can't register server");
log::trace!("registered with NS -- {:?}", keys_sid);
let mut keys = RootKeys::new(&xns);
@ -164,6 +168,12 @@ fn xmain() -> ! {
keys.test_ux(arg);
xous::return_scalar(msg.sender, 0).expect("couldn't unblock sender");
}),
Some(Opcode::PasswordModalEntry) => {
let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let mut plaintext_pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap();
log::info!("got pw entry: {}", plaintext_pw.as_str());
plaintext_pw.volatile_clear(); // ensure the data is destroyed after printing
}
Some(Opcode::Quit) => {
log::warn!("password thread received quit, exiting.");
break

View file

@ -69,9 +69,9 @@ impl Repl{
gam.request_focus(token.unwrap()).expect("couldn't take focus");
let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas");
log::debug!("content canvas {:?}", content);
log::trace!("content canvas {:?}", content);
let screensize = gam.get_canvas_bounds(content).expect("couldn't get dimensions of content canvas");
log::debug!("size {:?}", screensize);
log::trace!("size {:?}", screensize);
Repl {
input: None,
msg: None,
@ -308,7 +308,7 @@ fn xmain() -> ! {
repl.update(was_callback).expect("REPL had problems updating");
update_repl = false;
}
log::debug!("reached bottom of main loop");
log::trace!("reached bottom of main loop");
}
// clean up our program
log::error!("main loop exit, destroying servers");

View file

@ -59,6 +59,19 @@ impl<'a> Buffer<'a> {
}
}
// use a volatile write to ensure a clear operation is not optimized out
// for ensuring that a buffer is cleared, e.g. at the exit of a function
pub fn volatile_clear(&mut self) {
let b = self.slice.as_mut_ptr();
for i in 0..self.slice.len() {
unsafe{b.add(i).write_volatile(core::mem::zeroed());}
}
// Ensure the compiler doesn't re-order the clear.
// We use `SeqCst`, because `Acquire` only prevents later accesses from being reordered before
// *reads*, but this method only *writes* to the locations.
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
#[allow(dead_code)]
pub unsafe fn from_memory_message(mem: &'a MemoryMessage) -> Self {
Buffer {

View file

@ -27,6 +27,7 @@ impl<const N: usize> String<N> {
for i in 0..N {
unsafe{b.add(i).write_volatile(core::mem::zeroed());}
}
self.len = 0; // also set my length to 0
// Ensure the compiler doesn't re-order the clear.
// We use `SeqCst`, because `Acquire` only prevents later accesses from being reordered before
// *reads*, but this method only *writes* to the locations.

View file

@ -1 +1 @@
pub const LANG: &'static str = "zh";
pub const LANG: &'static str = "en";