refactor pddb ux thread to use deferred response messaging

This commit is contained in:
bunnie 2022-04-07 14:46:44 +08:00
parent 28de1b27a6
commit 1ad7c43f81

View file

@ -1,19 +1,13 @@
use xous::{SID, CID}; use xous::{SID, CID};
use xous::{msg_scalar_unpack, send_message}; use xous::msg_scalar_unpack;
use xous_ipc::Buffer; use xous_ipc::Buffer;
use std::sync::{Arc, Mutex};
use std::thread;
use core::sync::atomic::{AtomicBool, Ordering};
use num_traits::*; use num_traits::*;
use gam::modal::*; use gam::modal::*;
use locales::t; use locales::t;
use std::fmt::Write;
use crate::BasisRequestPassword; use crate::BasisRequestPassword;
/* /*
Conclusions: Conclusions:
@ -54,12 +48,6 @@ GAM Modal Object -> redraw -> gam requests
pub(crate) enum PwManagerOpcode { pub(crate) enum PwManagerOpcode {
// blocking call to get a password // blocking call to get a password
RequestPassword, RequestPassword,
Quit,
}
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum PwRendererOpcode {
RaisePwModal,
PwReturn, PwReturn,
ModalRedraw, ModalRedraw,
ModalKeypress, ModalKeypress,
@ -73,24 +61,14 @@ pub(crate) fn password_ux_manager(
// the SID we're to use for our loop handler, for getting requests // the SID we're to use for our loop handler, for getting requests
ux_sid: SID) { ux_sid: SID) {
let tt = ticktimer_server::Ticktimer::new().unwrap(); let ux_cid = xous::connect(ux_sid).unwrap();
let renderer_sid = xous::create_server().expect("couldn't create a server for the password UX renderer");
let renderer_cid = xous::connect(renderer_sid).expect("couldn't connect to the password UX renderer");
let plaintext_pw = Arc::new(Mutex::new(xous_ipc::String::<{crate::api::PASSWORD_LEN}>::new()));
let renderer_active = Arc::new(AtomicBool::new(false));
// create a thread that just handles the redrawing requests // create a thread that just handles the redrawing requests
let redraw_handle = thread::spawn({
let renderer_active = Arc::clone(&renderer_active);
let plaintext_pw = Arc::clone(&plaintext_pw);
move || {
// build the core data structure here // build the core data structure here
let password_action = TextEntry { let password_action = TextEntry {
is_password: true, is_password: true,
visibility: TextEntryVisibility::LastChars, visibility: TextEntryVisibility::LastChars,
action_conn: renderer_cid, action_conn: ux_cid,
action_opcode: PwRendererOpcode::PwReturn.to_u32().unwrap(), action_opcode: PwManagerOpcode::PwReturn.to_u32().unwrap(),
action_payload: TextEntryPayload::new(), action_payload: TextEntryPayload::new(),
validator: None, validator: None,
}; };
@ -104,47 +82,56 @@ pub(crate) fn password_ux_manager(
GlyphStyle::Regular, GlyphStyle::Regular,
8 8
); );
pddb_modal.spawn_helper(renderer_sid, pddb_modal.sid, pddb_modal.spawn_helper(ux_sid, pddb_modal.sid,
PwRendererOpcode::ModalRedraw.to_u32().unwrap(), PwManagerOpcode::ModalRedraw.to_u32().unwrap(),
PwRendererOpcode::ModalKeypress.to_u32().unwrap(), PwManagerOpcode::ModalKeypress.to_u32().unwrap(),
PwRendererOpcode::ModalDrop.to_u32().unwrap(), PwManagerOpcode::ModalDrop.to_u32().unwrap(),
); );
let mut dr: Option<xous::MessageEnvelope> = None;
// the main loop merely wraps a blocking wrapper around the renderer thread
loop { loop {
let msg = xous::receive_message(renderer_sid).unwrap(); let msg = xous::receive_message(ux_sid).unwrap();
log::debug!("message: {:?}", msg); log::debug!("message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(PwRendererOpcode::RaisePwModal) => { Some(PwManagerOpcode::RequestPassword) => {
let db_name = {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let db_name = buffer.to_original::<xous_ipc::String::<{crate::api::BASIS_NAME_LEN}>, _>().unwrap(); let request = buffer.to_original::<BasisRequestPassword, _>().unwrap();
request.db_name
};
pddb_modal.modify( pddb_modal.modify(
Some(ActionType::TextEntry(password_action)), Some(ActionType::TextEntry(password_action)),
Some(t!("pddb.password", xous::LANG)), false, Some(t!("pddb.password", xous::LANG)), false,
Some(db_name.as_str().unwrap()), false, None Some(db_name.as_str().unwrap()), false, None
); );
pddb_modal.activate(); pddb_modal.activate();
} dr = Some(msg);
Some(PwRendererOpcode::PwReturn) => {
if renderer_active.load(Ordering::SeqCst) { },
Some(PwManagerOpcode::PwReturn) => {
let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let mut pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap(); let mut pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap();
plaintext_pw.lock().unwrap().clear(); if let Some(mut response) = dr.take() {
write!(plaintext_pw.lock().unwrap(), "{}", pw.as_str()).expect("couldn't transfer password to local buffer"); let mut buffer = unsafe { Buffer::from_memory_message_mut(response.body.memory_message_mut().unwrap()) };
let mut request = buffer.to_original::<BasisRequestPassword, _>().unwrap();
request.plaintext_pw = Some(xous_ipc::String::from_str(pw.as_str()));
// return the password to the caller
buffer.replace(request).unwrap();
// response goes out of scope here and calls Drop which returns the message
} else {
log::error!("Password return received, but no deferred response on record");
}
pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave
buf.volatile_clear(); buf.volatile_clear();
} else {
log::warn!("Fat finger event received from Ux, ignoring");
}
// this resumes the waiting Ux Manager thread
renderer_active.store(false, Ordering::SeqCst);
}, },
Some(PwRendererOpcode::ModalRedraw) => { Some(PwManagerOpcode::ModalRedraw) => {
pddb_modal.redraw(); pddb_modal.redraw();
}, },
Some(PwRendererOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { Some(PwManagerOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [ let keys = [
core::char::from_u32(k1 as u32).unwrap_or('\u{0000}'), core::char::from_u32(k1 as u32).unwrap_or('\u{0000}'),
core::char::from_u32(k2 as u32).unwrap_or('\u{0000}'), core::char::from_u32(k2 as u32).unwrap_or('\u{0000}'),
@ -153,64 +140,20 @@ pub(crate) fn password_ux_manager(
]; ];
pddb_modal.key_event(keys); pddb_modal.key_event(keys);
}), }),
Some(PwRendererOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service Some(PwManagerOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service
panic!("Password modal for PDDB quit unexpectedly"); panic!("Password modal for PDDB quit unexpectedly");
}, },
Some(PwRendererOpcode::Quit) => { Some(PwManagerOpcode::Quit) => {
log::warn!("received quit on PDDB password UX renderer loop"); log::warn!("received quit on PDDB password UX renderer loop");
xous::return_scalar(msg.sender, 0).unwrap(); xous::return_scalar(msg.sender, 0).unwrap();
break; break;
}, },
None => {
log::error!("Couldn't convert opcode: {:?}", msg);
}
}
}
xous::destroy_server(renderer_sid).unwrap();
}
});
// the main loop merely wraps a blocking wrapper around the renderer thread
loop {
let mut msg = xous::receive_message(ux_sid).unwrap();
log::debug!("message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(PwManagerOpcode::RequestPassword) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut request = buffer.to_original::<BasisRequestPassword, _>().unwrap();
let fwd_buf = Buffer::into_buf(request.db_name).unwrap();
renderer_active.store(true, Ordering::SeqCst);
fwd_buf.lend(renderer_cid, PwRendererOpcode::RaisePwModal.to_u32().unwrap()).expect("couldn't request renderer to raise the password modal");
// this returns almost immediately, because the Ux Manager thread can't block (it has to manage rendering), but the password hasn't come back yet.
// so...."busy wait" by polling once every 100ms until the Ux is finished with its task.
// I can't seem to figure out a way to do this using a solely asynchronous method. I really want a spsc queue, but these don't exist in xous stdlib yet.
// apparently the thing I'm looking for is a `condvar`, which is coming Real Soon Now.
while renderer_active.load(Ordering::SeqCst) {
tt.sleep_ms(100).unwrap();
}
// when this unblocks, the password request cycle is done.
let retpw = xous_ipc::String::<{crate::api::PASSWORD_LEN}>::from_str(plaintext_pw.lock().unwrap().as_str().unwrap());
request.plaintext_pw = Some(retpw);
// return the password to the caller
buffer.replace(request).unwrap();
},
Some(PwManagerOpcode::Quit) => {
log::warn!("PDDB password handler exiting.");
send_message(
renderer_cid,
xous::Message::new_blocking_scalar(PwRendererOpcode::Quit.to_usize().unwrap(),
0, 0, 0, 0)).unwrap();
xous::return_scalar(msg.sender, 0).unwrap();
break
},
None => { None => {
log::error!("couldn't convert opcode"); log::error!("couldn't convert opcode");
} }
} }
} }
redraw_handle.join().expect("redraw thread didn't quit as expected");
unsafe{xous::disconnect(renderer_cid).unwrap()}; // can't remember if this is...necessary? it'll throw an error if it's not.
xous::destroy_server(ux_sid).unwrap(); xous::destroy_server(ux_sid).unwrap();
} }