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,144 +61,99 @@ 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({ // build the core data structure here
let renderer_active = Arc::clone(&renderer_active); let password_action = TextEntry {
let plaintext_pw = Arc::clone(&plaintext_pw); is_password: true,
move || { visibility: TextEntryVisibility::LastChars,
// build the core data structure here action_conn: ux_cid,
let password_action = TextEntry { action_opcode: PwManagerOpcode::PwReturn.to_u32().unwrap(),
is_password: true, action_payload: TextEntryPayload::new(),
visibility: TextEntryVisibility::LastChars, validator: None,
action_conn: renderer_cid, };
action_opcode: PwRendererOpcode::PwReturn.to_u32().unwrap(),
action_payload: TextEntryPayload::new(),
validator: None,
};
let mut pddb_modal = let mut pddb_modal =
Modal::new( Modal::new(
gam::PDDB_MODAL_NAME, gam::PDDB_MODAL_NAME,
ActionType::TextEntry(password_action), ActionType::TextEntry(password_action),
Some(t!("pddb.password", xous::LANG)), Some(t!("pddb.password", xous::LANG)),
None, None,
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(),
); );
loop { let mut dr: Option<xous::MessageEnvelope> = None;
let msg = xous::receive_message(renderer_sid).unwrap();
log::debug!("message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(PwRendererOpcode::RaisePwModal) => {
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();
pddb_modal.modify(
Some(ActionType::TextEntry(password_action)),
Some(t!("pddb.password", xous::LANG)), false,
Some(db_name.as_str().unwrap()), false, None
);
pddb_modal.activate();
}
Some(PwRendererOpcode::PwReturn) => {
if renderer_active.load(Ordering::SeqCst) {
let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let mut pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap();
plaintext_pw.lock().unwrap().clear();
write!(plaintext_pw.lock().unwrap(), "{}", pw.as_str()).expect("couldn't transfer password to local buffer");
pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave
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) => {
pddb_modal.redraw();
},
Some(PwRendererOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [
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(k3 as u32).unwrap_or('\u{0000}'),
core::char::from_u32(k4 as u32).unwrap_or('\u{0000}'),
];
pddb_modal.key_event(keys);
}),
Some(PwRendererOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service
panic!("Password modal for PDDB quit unexpectedly");
},
Some(PwRendererOpcode::Quit) => {
log::warn!("received quit on PDDB password UX renderer loop");
xous::return_scalar(msg.sender, 0).unwrap();
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 // the main loop merely wraps a blocking wrapper around the renderer thread
loop { loop {
let mut msg = xous::receive_message(ux_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(PwManagerOpcode::RequestPassword) => { Some(PwManagerOpcode::RequestPassword) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let db_name = {
let mut request = buffer.to_original::<BasisRequestPassword, _>().unwrap(); let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let fwd_buf = Buffer::into_buf(request.db_name).unwrap(); let request = buffer.to_original::<BasisRequestPassword, _>().unwrap();
renderer_active.store(true, Ordering::SeqCst); request.db_name
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. pddb_modal.modify(
// so...."busy wait" by polling once every 100ms until the Ux is finished with its task. Some(ActionType::TextEntry(password_action)),
// 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. Some(t!("pddb.password", xous::LANG)), false,
// apparently the thing I'm looking for is a `condvar`, which is coming Real Soon Now. Some(db_name.as_str().unwrap()), false, None
while renderer_active.load(Ordering::SeqCst) { );
tt.sleep_ms(100).unwrap(); pddb_modal.activate();
} dr = Some(msg);
// 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::PwReturn) => {
let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let mut pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap();
if let Some(mut response) = dr.take() {
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
buf.volatile_clear();
},
Some(PwManagerOpcode::ModalRedraw) => {
pddb_modal.redraw();
},
Some(PwManagerOpcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [
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(k3 as u32).unwrap_or('\u{0000}'),
core::char::from_u32(k4 as u32).unwrap_or('\u{0000}'),
];
pddb_modal.key_event(keys);
}),
Some(PwManagerOpcode::ModalDrop) => { // this guy should never quit, it's a core OS service
panic!("Password modal for PDDB quit unexpectedly");
}, },
Some(PwManagerOpcode::Quit) => { Some(PwManagerOpcode::Quit) => {
log::warn!("PDDB password handler exiting."); log::warn!("received quit on PDDB password UX renderer loop");
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(); xous::return_scalar(msg.sender, 0).unwrap();
break 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();
} }