refactor main loop to use deferred responses

I think things could be compactified even further, but this is a
first-step "merge the threads and break as few things as possible"
pass. Would like to get @gsora's multi-line boxes merged into this
new system before doing even more optimization.
This commit is contained in:
bunnie 2022-04-07 04:04:37 +08:00
parent 360e50a8bb
commit f720f3175c
4 changed files with 485 additions and 503 deletions

View file

@ -89,7 +89,31 @@ pub(crate) enum Opcode {
/// close dynamic notification /// close dynamic notification
CloseDynamicNotification, CloseDynamicNotification,
/// used by libraries to get the mutex on the server
GetMutex, GetMutex,
// these are used internally by the modals to handle intermediate state. Do not call from the outside.
// these were originally handled in a separate thread for deferred responses using busy-waits. They are
// now handled with deferred responses with makes code less complicated and less load on the CPU but
// it does expose some of the internal API mechanics to outside processes. This is fine for the modals
// box because it's a convenience routine used by "everyone"; password boxes are always handled within
// a given secured server so that the attack surface for these do not extend into the modals boundary.
InitiateOp,
DoUpdateProgress,
FinishProgress,
TextEntryReturn,
RadioReturn,
CheckBoxReturn,
NotificationReturn,
DoUpdateDynamicNotification,
DoCloseDynamicNotification,
ModalRedraw,
ModalKeypress,
ModalDrop,
Gutter,
Quit, Quit,
} }

View file

@ -8,10 +8,12 @@ use xous::{CID, SID, send_message, Message};
use num_traits::{ToPrimitive, FromPrimitive}; use num_traits::{ToPrimitive, FromPrimitive};
use xous_ipc::Buffer; use xous_ipc::Buffer;
use std::thread; use std::thread;
use core::cell::Cell;
pub struct Modals { pub struct Modals {
conn: CID, conn: CID,
token: [u32; 4], token: [u32; 4],
have_lock: Cell::<bool>,
} }
impl Modals { impl Modals {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> { pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
@ -23,6 +25,7 @@ impl Modals {
Ok(Modals { Ok(Modals {
conn, conn,
token, token,
have_lock: Cell::new(false),
}) })
} }
@ -78,6 +81,7 @@ impl Modals {
unsafe{xous::disconnect(cid).unwrap()}; // must disconnect before destroy to avoid the CID from hanging out in our outbound table which is limited to 32 entries unsafe{xous::disconnect(cid).unwrap()}; // must disconnect before destroy to avoid the CID from hanging out in our outbound table which is limited to 32 entries
xous::destroy_server(SID::from_array(server)).expect("couldn't destroy temporary server"); xous::destroy_server(SID::from_array(server)).expect("couldn't destroy temporary server");
} }
self.unlock();
match buf.to_original::<TextEntryPayload, _>() { match buf.to_original::<TextEntryPayload, _>() {
Ok(response) => Ok(response), Ok(response) => Ok(response),
_ => Err(xous::Error::InternalError) _ => Err(xous::Error::InternalError)
@ -93,6 +97,7 @@ impl Modals {
}; };
let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::Notification.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::Notification.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
self.unlock();
Ok(()) Ok(())
} }
@ -131,6 +136,7 @@ impl Modals {
self.token[3] as usize, self.token[3] as usize,
) )
).expect("couldn't stop progress"); ).expect("couldn't stop progress");
self.unlock();
Ok(()) Ok(())
} }
@ -154,6 +160,7 @@ impl Modals {
let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::PromptWithFixedResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; buf.lend_mut(self.conn, Opcode::PromptWithFixedResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let itemname = buf.to_original::<ItemName, _>().unwrap(); let itemname = buf.to_original::<ItemName, _>().unwrap();
self.unlock();
Ok(String::from(itemname.as_str())) Ok(String::from(itemname.as_str()))
} }
@ -172,6 +179,7 @@ impl Modals {
ret.push(String::from(item.as_str())); ret.push(String::from(item.as_str()));
} }
} }
self.unlock();
Ok(ret) Ok(ret)
} }
@ -197,7 +205,6 @@ impl Modals {
Ok(()) Ok(())
} }
pub fn dynamic_notification_close(&self) -> Result<(), xous::Error> { pub fn dynamic_notification_close(&self) -> Result<(), xous::Error> {
self.lock();
send_message(self.conn, send_message(self.conn,
Message::new_scalar(Opcode::CloseDynamicNotification.to_usize().unwrap(), Message::new_scalar(Opcode::CloseDynamicNotification.to_usize().unwrap(),
self.token[0] as usize, self.token[0] as usize,
@ -206,11 +213,13 @@ impl Modals {
self.token[3] as usize, self.token[3] as usize,
) )
).expect("couldn't stop progress"); ).expect("couldn't stop progress");
self.unlock();
Ok(()) Ok(())
} }
/// Blocks until we have a lock on the modals server /// Blocks until we have a lock on the modals server
fn lock(&self) { fn lock(&self) {
if !self.have_lock.get() {
match send_message( match send_message(
self.conn, self.conn,
Message::new_blocking_scalar(Opcode::GetMutex.to_usize().unwrap(), Message::new_blocking_scalar(Opcode::GetMutex.to_usize().unwrap(),
@ -229,6 +238,11 @@ impl Modals {
} }
} }
} }
self.have_lock.set(true);
}
fn unlock(&self) {
self.have_lock.set(false);
}
} }
use core::sync::atomic::{AtomicU32, Ordering}; use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -10,9 +10,6 @@ use xous::SID;
use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack, send_message, Message}; use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack, send_message, Message};
use xous_ipc::Buffer; use xous_ipc::Buffer;
use std::sync::{Arc, Mutex};
use std::thread;
use gam::modal::*; use gam::modal::*;
#[cfg(feature="tts")] #[cfg(feature="tts")]
use tts_frontend::TtsFrontend; use tts_frontend::TtsFrontend;
@ -33,36 +30,9 @@ enum RendererState {
RunText(ManagedPromptWithTextResponse), RunText(ManagedPromptWithTextResponse),
RunProgress(ManagedProgress), RunProgress(ManagedProgress),
RunNotification(ManagedNotification), RunNotification(ManagedNotification),
/// response ready state
ResponseText(TextEntryPayload),
ResponseRadio(ItemName),
ResponseCheckBox(CheckBoxPayload),
RunDynamicNotification(DynamicNotification), RunDynamicNotification(DynamicNotification),
} }
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum RendererOp {
InitiateOp,
UpdateProgress,
FinishProgress,
TextEntryReturn,
RadioReturn,
CheckBoxReturn,
NotificationReturn,
AddModalItem,
UpdateDynamicNotification,
CloseDynamicNotification,
ModalRedraw,
ModalKeypress,
ModalDrop,
Quit,
Gutter,
}
#[xous::xous_main] #[xous::xous_main]
fn xmain() -> ! { fn xmain() -> ! {
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
@ -75,41 +45,39 @@ fn xmain() -> ! {
let tt = ticktimer_server::Ticktimer::new().unwrap(); let tt = ticktimer_server::Ticktimer::new().unwrap();
let renderer_sid = xous::create_server().expect("couldn't create a server for the modal UX renderer"); // we are our own renderer now that we implement deferred responses
let renderer_cid = xous::connect(renderer_sid).expect("couldn't connect to the modal UX renderer"); let renderer_cid = xous::connect(modals_sid).expect("couldn't connect to the modal UX renderer");
#[cfg(feature="tts")] #[cfg(feature="tts")]
let tts = TtsFrontend::new(&xns).unwrap(); let tts = TtsFrontend::new(&xns).unwrap();
#[cfg(feature="tts")] #[cfg(feature="tts")]
let mut last_tick = tt.elapsed_ms(); let mut last_tick = tt.elapsed_ms();
let op = Arc::new(Mutex::new(RendererState::None)); // current opcode being processed by the modals server
// create a thread that just handles the redrawing requests let mut op = RendererState::None;
let _redraw_handle = thread::spawn({ // the message for the deferred response
let op = Arc::clone(&op); let mut dr: Option<xous::MessageEnvelope> = None;
move || {
#[cfg(feature="tts")]
let tt = ticktimer_server::Ticktimer::new().unwrap();
// build the core data structure here // build the core data structure here
let text_action = TextEntry { let text_action = TextEntry {
is_password: false, is_password: false,
visibility: TextEntryVisibility::Visible, visibility: TextEntryVisibility::Visible,
action_conn: renderer_cid, action_conn: renderer_cid,
action_opcode: RendererOp::TextEntryReturn.to_u32().unwrap(), action_opcode: Opcode::TextEntryReturn.to_u32().unwrap(),
action_payload: TextEntryPayload::new(), action_payload: TextEntryPayload::new(),
validator: None, validator: None,
}; };
let mut fixed_items = Vec::<ItemName>::new(); let mut fixed_items = Vec::<ItemName>::new();
let notification = gam::modal::Notification::new( let notification = gam::modal::Notification::new(
renderer_cid, renderer_cid,
RendererOp::NotificationReturn.to_u32().unwrap() Opcode::NotificationReturn.to_u32().unwrap()
); );
let mut gutter = gam::modal::Notification::new( let mut gutter = gam::modal::Notification::new(
renderer_cid, renderer_cid,
RendererOp::Gutter.to_u32().unwrap() Opcode::Gutter.to_u32().unwrap()
); );
gutter.set_manual_dismiss(false); gutter.set_manual_dismiss(false);
let mut progress_action = Slider::new(renderer_cid, RendererOp::Gutter.to_u32().unwrap(), let mut progress_action = Slider::new(renderer_cid, Opcode::Gutter.to_u32().unwrap(),
0, 100, 1, Some("%"), 0, true, true 0, 100, 1, Some("%"), 0, true, true
); );
let mut last_percentage = 0; let mut last_percentage = 0;
@ -124,20 +92,194 @@ fn xmain() -> ! {
GlyphStyle::Regular, GlyphStyle::Regular,
8 8
); );
renderer_modal.spawn_helper(renderer_sid, renderer_modal.sid, renderer_modal.spawn_helper(modals_sid, renderer_modal.sid,
RendererOp::ModalRedraw.to_u32().unwrap(), Opcode::ModalRedraw.to_u32().unwrap(),
RendererOp::ModalKeypress.to_u32().unwrap(), Opcode::ModalKeypress.to_u32().unwrap(),
RendererOp::ModalDrop.to_u32().unwrap(), Opcode::ModalDrop.to_u32().unwrap(),
); );
if cfg!(feature = "ux_tests") {
tt.sleep_ms(1000).unwrap();
tests::spawn_test();
}
let mut token_lock: Option<[u32; 4]> = None;
let trng = trng::Trng::new(&xns).unwrap();
// this is a random number that serves as a "default" that cannot be guessed
let default_nonce = [
trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(),
];
let mut work_queue = Vec::<(xous::MessageSender, [u32; 4])>::new();
loop { loop {
let msg = xous::receive_message(renderer_sid).unwrap(); let mut msg = xous::receive_message(modals_sid).unwrap();
log::debug!("renderer message: {:?}", msg); log::debug!("message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(RendererOp::InitiateOp) => { // ------------------ EXTERNAL APIS --------------------
Some(Opcode::GetMutex) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, t3, {
let incoming_token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32];
if token_lock.is_none() {
token_lock = Some(incoming_token);
xous::return_scalar(msg.sender, 1).unwrap();
} else {
work_queue.push((msg.sender, incoming_token));
}
}),
Some(Opcode::PromptWithFixedResponse) => {
let spec = {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let spec = buffer.to_original::<ManagedPromptWithFixedResponse, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
buffer.replace(ItemName::new("internal error")).unwrap();
continue;
}
spec
};
op = RendererState::RunRadio(spec);
dr = Some(msg);
send_message(
renderer_cid,
Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::PromptWithMultiResponse) => {
let spec = {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let spec = buffer.to_original::<ManagedPromptWithFixedResponse, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
buffer.replace(CheckBoxPayload::new()).unwrap();
continue;
}
spec
};
op = RendererState::RunCheckBox(spec);
dr = Some(msg);
send_message(
renderer_cid,
Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::PromptWithTextResponse) => {
let spec = {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let spec = buffer.to_original::<ManagedPromptWithTextResponse, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
buffer.replace(TextEntryPayload::new()).unwrap();
continue;
}
spec
};
op = RendererState::RunText(spec);
dr = Some(msg);
send_message(
renderer_cid,
Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::Notification) => {
let spec = {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
buffer.to_original::<ManagedNotification, _>().unwrap()
};
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
op = RendererState::RunNotification(spec);
dr = Some(msg);
send_message(
renderer_cid,
Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::StartProgress) => {
let spec = {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
buffer.to_original::<ManagedProgress, _>().unwrap()
};
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
op = RendererState::RunProgress(spec);
send_message(
renderer_cid,
Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::UpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, {
send_message(
renderer_cid,
Message::new_scalar(Opcode::DoUpdateProgress.to_usize().unwrap(), current, 0, 0, 0)
).expect("couldn't update progress bar");
}),
Some(Opcode::StopProgress) => msg_scalar_unpack!(msg, t0, t1, t2, t3, {
let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32];
if token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
send_message(
renderer_cid,
Message::new_scalar(Opcode::FinishProgress.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't update progress bar");
}),
Some(Opcode::AddModalItem) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let manageditem = buffer.to_original::<ManagedListItem, _>().unwrap();
if manageditem.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring. got: {:x?} have: {:x?}", manageditem.token, token_lock);
continue;
}
fixed_items.push(manageditem.item);
}
Some(Opcode::DynamicNotification) => {
let spec = {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
buffer.to_original::<DynamicNotification, _>().unwrap()
};
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
op = RendererState::RunDynamicNotification(spec);
send_message(
renderer_cid,
Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::UpdateDynamicNotification) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let spec = buffer.to_original::<DynamicNotification, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
op = RendererState::RunDynamicNotification(spec);
send_message(
renderer_cid,
Message::new_scalar(Opcode::DoUpdateDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::CloseDynamicNotification) => msg_scalar_unpack!(msg, t0, t1, t2, t3, {
let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32];
if token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
send_message(
renderer_cid,
Message::new_scalar(Opcode::DoCloseDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't close dynamic notification");
}),
// ------------------ INTERNAL APIS --------------------
Some(Opcode::InitiateOp) => {
log::debug!("InitiateOp called"); log::debug!("InitiateOp called");
let mutex_op = op.lock().unwrap(); match op {
match *mutex_op {
RendererState::RunText(config) => { RendererState::RunText(config) => {
log::debug!("initiating text entry modal"); log::debug!("initiating text entry modal");
#[cfg(feature="tts")] #[cfg(feature="tts")]
@ -179,7 +321,7 @@ fn xmain() -> ! {
RendererState::RunRadio(config) => { RendererState::RunRadio(config) => {
let mut radiobuttons = gam::modal::RadioButtons::new( let mut radiobuttons = gam::modal::RadioButtons::new(
renderer_cid, renderer_cid,
RendererOp::RadioReturn.to_u32().unwrap() Opcode::RadioReturn.to_u32().unwrap()
); );
for item in fixed_items.iter() { for item in fixed_items.iter() {
radiobuttons.add_item(*item); radiobuttons.add_item(*item);
@ -200,7 +342,7 @@ fn xmain() -> ! {
RendererState::RunCheckBox(config) => { RendererState::RunCheckBox(config) => {
let mut checkbox = gam::modal::CheckBoxes::new( let mut checkbox = gam::modal::CheckBoxes::new(
renderer_cid, renderer_cid,
RendererOp::CheckBoxReturn.to_u32().unwrap() Opcode::CheckBoxReturn.to_u32().unwrap()
); );
for item in fixed_items.iter() { for item in fixed_items.iter() {
checkbox.add_item(*item); checkbox.add_item(*item);
@ -243,13 +385,9 @@ fn xmain() -> ! {
log::error!("Operation initiated with no argument specified. Ignoring request."); log::error!("Operation initiated with no argument specified. Ignoring request.");
continue; continue;
} }
_ => {
log::warn!("unimplemented arm in renderer match");
unimplemented!();
}
} }
}, },
Some(RendererOp::UpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, { Some(Opcode::DoUpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, {
let new_percentage = compute_checked_percentage( let new_percentage = compute_checked_percentage(
current as u32, start_work, end_work); current as u32, start_work, end_work);
log::trace!("percentage: {}, current: {}, start: {}, end: {}", new_percentage, current, start_work, end_work); log::trace!("percentage: {}, current: {}, start: {}, end: {}", new_percentage, current, start_work, end_work);
@ -272,12 +410,21 @@ fn xmain() -> ! {
xous::yield_slice(); // give time for the GAM to redraw xous::yield_slice(); // give time for the GAM to redraw
} }
}), }),
Some(RendererOp::FinishProgress) => { Some(Opcode::FinishProgress) => {
renderer_modal.gam.relinquish_focus().unwrap(); renderer_modal.gam.relinquish_focus().unwrap();
op = RendererState::None;
token_lock = next_lock(&mut work_queue);
/*
if work_queue.len() > 0 {
let (unblock_pid, token) = work_queue.remove(0);
token_lock = Some(token);
xous::return_scalar(unblock_pid, 1).unwrap();
} else {
token_lock = None;
}*/
}, },
Some(RendererOp::UpdateDynamicNotification) => { Some(Opcode::DoUpdateDynamicNotification) => {
let mutex_op = op.lock().unwrap(); match op {
match *mutex_op {
RendererState::RunDynamicNotification(config) => { RendererState::RunDynamicNotification(config) => {
let mut top_text = String::new(); let mut top_text = String::new();
if let Some(title) = config.title { if let Some(title) = config.title {
@ -301,12 +448,13 @@ fn xmain() -> ! {
} }
} }
}, },
Some(RendererOp::CloseDynamicNotification) => { Some(Opcode::DoCloseDynamicNotification) => {
renderer_modal.gam.relinquish_focus().unwrap(); renderer_modal.gam.relinquish_focus().unwrap();
op = RendererState::None;
token_lock = next_lock(&mut work_queue);
}, },
Some(RendererOp::TextEntryReturn) => { Some(Opcode::TextEntryReturn) => {
let mut mutex_op = op.lock().unwrap(); match op {
match *mutex_op {
RendererState::RunText(config) => { RendererState::RunText(config) => {
log::trace!("validating text entry modal"); log::trace!("validating text entry modal");
let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
@ -330,11 +478,26 @@ fn xmain() -> ! {
); );
renderer_modal.activate(); renderer_modal.activate();
} else { } else {
// the change in mutex_op enum type will signal the state change to the caller if let Some(mut origin) = dr.take() {
*mutex_op = RendererState::ResponseText(text); let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) };
response.replace(text).unwrap();
op = RendererState::None;
} else {
log::error!("Ux routine returned but no origin was recorded");
panic!("Ux routine returned but no origin was recorded");
}
token_lock = next_lock(&mut work_queue);
} }
} else { } else {
*mutex_op = RendererState::ResponseText(text); if let Some(mut origin) = dr.take() {
let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) };
response.replace(text).unwrap();
op = RendererState::None;
} else {
log::error!("Ux routine returned but no origin was recorded");
panic!("Ux routine returned but no origin was recorded");
}
token_lock = next_lock(&mut work_queue);
} }
} }
RendererState::None => log::warn!("Text entry detected a fat finger event, ignoring."), RendererState::None => log::warn!("Text entry detected a fat finger event, ignoring."),
@ -344,34 +507,38 @@ fn xmain() -> ! {
} }
} }
} }
Some(RendererOp::NotificationReturn) => { Some(Opcode::NotificationReturn) => {
let mut mutex_op = op.lock().unwrap(); match op {
match *mutex_op { RendererState::RunNotification(_) => {
RendererState::RunNotification(_) => *mutex_op = RendererState::None, op = RendererState::None;
dr.take(); // unblocks the caller, but without any response data
token_lock = next_lock(&mut work_queue);
},
RendererState::None => log::warn!("Notification detected a fat finger event, ignoring."), RendererState::None => log::warn!("Notification detected a fat finger event, ignoring."),
_ => { _ => {
log::error!("UX return opcode does not match our current operation in flight: {:?}", mutex_op); log::error!("UX return opcode does not match our current operation in flight: {:?}", op);
panic!("UX return opcode does not match our current operation in flight. This is a serious internal error."); panic!("UX return opcode does not match our current operation in flight. This is a serious internal error.");
} }
} }
}, },
Some(RendererOp::Gutter) => { Some(Opcode::Gutter) => {
log::info!("gutter op, doing nothing"); log::info!("gutter op, doing nothing");
}, },
Some(RendererOp::AddModalItem) => { Some(Opcode::RadioReturn) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; match op {
let item = buffer.to_original::<ItemName, _>().unwrap();
fixed_items.push(item);
}
Some(RendererOp::RadioReturn) => {
let mut mutex_op = op.lock().unwrap();
match *mutex_op {
RendererState::RunRadio(_config) => { RendererState::RunRadio(_config) => {
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 item = buffer.to_original::<RadioButtonPayload, _>().unwrap(); let item = buffer.to_original::<RadioButtonPayload, _>().unwrap();
*mutex_op = RendererState::ResponseRadio(item.0); if let Some(mut origin) = dr.take() {
let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) };
response.replace(item).unwrap();
op = RendererState::None;
} else {
log::error!("Ux routine returned but no origin was recorded");
panic!("Ux routine returned but no origin was recorded");
}
token_lock = next_lock(&mut work_queue);
} }
RendererState::ResponseRadio(_) => log::warn!("Radio buttons detected a fat finger event, ignoring."),
RendererState::None => log::warn!("Radio buttons detected a fat finger event, ignoring."), RendererState::None => log::warn!("Radio buttons detected a fat finger event, ignoring."),
_ => { _ => {
log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error.");
@ -379,15 +546,21 @@ fn xmain() -> ! {
} }
} }
} }
Some(RendererOp::CheckBoxReturn) => { Some(Opcode::CheckBoxReturn) => {
let mut mutex_op = op.lock().unwrap(); match op {
match *mutex_op {
RendererState::RunCheckBox(_config) => { RendererState::RunCheckBox(_config) => {
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 item = buffer.to_original::<CheckBoxPayload, _>().unwrap(); let item = buffer.to_original::<CheckBoxPayload, _>().unwrap();
*mutex_op = RendererState::ResponseCheckBox(item); if let Some(mut origin) = dr.take() {
let mut response = unsafe { Buffer::from_memory_message_mut(origin.body.memory_message_mut().unwrap()) };
response.replace(item).unwrap();
op = RendererState::None;
} else {
log::error!("Ux routine returned but no origin was recorded");
panic!("Ux routine returned but no origin was recorded");
}
token_lock = next_lock(&mut work_queue);
} }
RendererState::ResponseCheckBox(_) => log::warn!("Check boxes detected a fat finger event, ignoring."),
RendererState::None => log::warn!("Check boxes detected a fat finger event, ignoring."), RendererState::None => log::warn!("Check boxes detected a fat finger event, ignoring."),
_ => { _ => {
log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error."); log::error!("UX return opcode does not match our current operation in flight. This is a serious internal error.");
@ -395,10 +568,10 @@ fn xmain() -> ! {
} }
} }
} }
Some(RendererOp::ModalRedraw) => { Some(Opcode::ModalRedraw) => {
renderer_modal.redraw(); renderer_modal.redraw();
}, },
Some(RendererOp::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { Some(Opcode::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [ let keys = [
if let Some(a) = core::char::from_u32(k1 as u32) {a} else {'\u{0000}'}, if let Some(a) = core::char::from_u32(k1 as u32) {a} else {'\u{0000}'},
if let Some(a) = core::char::from_u32(k2 as u32) {a} else {'\u{0000}'}, if let Some(a) = core::char::from_u32(k2 as u32) {a} else {'\u{0000}'},
@ -407,243 +580,11 @@ fn xmain() -> ! {
]; ];
renderer_modal.key_event(keys); renderer_modal.key_event(keys);
}), }),
Some(RendererOp::ModalDrop) => { // this guy should never quit, it's a core OS service Some(Opcode::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(RendererOp::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();
}
});
if cfg!(feature = "ux_tests") {
tt.sleep_ms(1000).unwrap();
tests::spawn_test();
}
let mut token_lock: Option<[u32; 4]> = None;
let trng = trng::Trng::new(&xns).unwrap();
// this is a random number that serves as a "default" that cannot be guessed
let default_nonce = [
trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(),
];
let mut work_queue = Vec::<(xous::MessageSender, [u32; 4])>::new();
loop {
let mut msg = xous::receive_message(modals_sid).unwrap();
log::debug!("message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::GetMutex) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, t3, {
let incoming_token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32];
if let Some(token) = token_lock {
if token == incoming_token {
xous::return_scalar(msg.sender, 1).unwrap();
} else {
work_queue.push((msg.sender, incoming_token));
}
} else {
token_lock = Some(incoming_token);
xous::return_scalar(msg.sender, 1).unwrap();
}
}),
Some(Opcode::PromptWithFixedResponse) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let spec = buffer.to_original::<ManagedPromptWithFixedResponse, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
buffer.replace(ItemName::new("internal error")).unwrap();
continue;
}
*op.lock().unwrap() = RendererState::RunRadio(spec);
send_message(
renderer_cid,
Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
loop {
match *op.lock().unwrap() {
RendererState::RunRadio(_) => (),
RendererState::ResponseRadio(item) => {
buffer.replace(item).unwrap();
token_lock = next_lock(&mut work_queue);
break;
},
_ => {
log::error!("Illegal state transition in renderer");
panic!("Illegal state transition in renderer");
}
}
tt.sleep_ms(100).unwrap(); // don't put the idle in the match/lock(), it'll prevent the other thread from running!
}
},
Some(Opcode::PromptWithMultiResponse) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let spec = buffer.to_original::<ManagedPromptWithFixedResponse, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
buffer.replace(CheckBoxPayload::new()).unwrap();
continue;
}
*op.lock().unwrap() = RendererState::RunCheckBox(spec);
send_message(
renderer_cid,
Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
loop {
match *op.lock().unwrap() {
RendererState::RunCheckBox(_) => (),
RendererState::ResponseCheckBox(items) => {
buffer.replace(items).unwrap();
token_lock = next_lock(&mut work_queue);
break;
},
_ => {
log::error!("Illegal state transition in renderer");
panic!("Illegal state transition in renderer");
}
}
tt.sleep_ms(100).unwrap(); // don't put the idle in the match/lock(), it'll prevent the other thread from running!
}
},
Some(Opcode::PromptWithTextResponse) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let spec = buffer.to_original::<ManagedPromptWithTextResponse, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
buffer.replace(TextEntryPayload::new()).unwrap();
continue;
}
*op.lock().unwrap() = RendererState::RunText(spec);
send_message(
renderer_cid,
Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
loop {
match *op.lock().unwrap() {
RendererState::RunText(_) => (),
RendererState::ResponseText(text) => {
buffer.replace(text).unwrap();
token_lock = next_lock(&mut work_queue);
break;
},
_ => {
log::error!("Illegal state transition in renderer");
panic!("Illegal state transition in renderer");
}
}
tt.sleep_ms(100).unwrap(); // don't put the idle in the match/lock(), it'll prevent the other thread from running!
}
},
Some(Opcode::Notification) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let spec = buffer.to_original::<ManagedNotification, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
*op.lock().unwrap() = RendererState::RunNotification(spec);
send_message(
renderer_cid,
Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
loop {
match *op.lock().unwrap() {
RendererState::RunNotification(_) => (),
RendererState::None => {token_lock = next_lock(&mut work_queue); break},
_ => {
log::error!("Illegal state transition in renderer");
panic!("Illegal state transition in renderer");
}
}
tt.sleep_ms(100).unwrap(); // don't put the idle in the match/lock(), it'll prevent the other thread from running!
}
},
Some(Opcode::StartProgress) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let spec = buffer.to_original::<ManagedProgress, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
*op.lock().unwrap() = RendererState::RunProgress(spec);
send_message(
renderer_cid,
Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::UpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, {
send_message(
renderer_cid,
Message::new_scalar(RendererOp::UpdateProgress.to_usize().unwrap(), current, 0, 0, 0)
).expect("couldn't update progress bar");
}),
Some(Opcode::StopProgress) => msg_scalar_unpack!(msg, t0, t1, t2, t3, {
let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32];
if token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
send_message(
renderer_cid,
Message::new_scalar(RendererOp::FinishProgress.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't update progress bar");
token_lock = next_lock(&mut work_queue);
}),
Some(Opcode::AddModalItem) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let manageditem = buffer.to_original::<ManagedListItem, _>().unwrap();
if manageditem.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
let fwd_buf = Buffer::into_buf(manageditem.item).unwrap();
fwd_buf.lend(renderer_cid, RendererOp::AddModalItem.to_u32().unwrap()).expect("couldn't add item");
}
Some(Opcode::DynamicNotification) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let spec = buffer.to_original::<DynamicNotification, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
*op.lock().unwrap() = RendererState::RunDynamicNotification(spec);
send_message(
renderer_cid,
Message::new_scalar(RendererOp::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::UpdateDynamicNotification) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let spec = buffer.to_original::<DynamicNotification, _>().unwrap();
if spec.token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
*op.lock().unwrap() = RendererState::RunDynamicNotification(spec);
send_message(
renderer_cid,
Message::new_scalar(RendererOp::UpdateDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate UX op");
},
Some(Opcode::CloseDynamicNotification) => msg_scalar_unpack!(msg, t0, t1, t2, t3, {
let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32];
if token != token_lock.unwrap_or(default_nonce) {
log::warn!("Attempt to access modals without a mutex lock. Ignoring.");
continue;
}
send_message(
renderer_cid,
Message::new_scalar(RendererOp::CloseDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't close dynamic notification");
token_lock = next_lock(&mut work_queue);
}),
Some(Opcode::Quit) => { Some(Opcode::Quit) => {
log::warn!("Shared modal UX handler exiting."); log::warn!("Shared modal UX handler exiting.");
break break
@ -651,14 +592,10 @@ fn xmain() -> ! {
None => { None => {
log::error!("couldn't convert opcode"); log::error!("couldn't convert opcode");
} }
} }
} }
// clean up our program // clean up our program
log::trace!("main loop exit, destroying servers"); log::trace!("main loop exit, destroying servers");
send_message(renderer_cid, Message::new_blocking_scalar(RendererOp::Quit.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
unsafe{xous::disconnect(renderer_cid).unwrap()};
xous::destroy_server(renderer_sid).unwrap();
xns.unregister_server(modals_sid).unwrap(); xns.unregister_server(modals_sid).unwrap();
xous::destroy_server(modals_sid).unwrap(); xous::destroy_server(modals_sid).unwrap();
log::trace!("quitting"); log::trace!("quitting");
@ -682,7 +619,14 @@ fn compute_checked_percentage(current: u32, start: u32, end: u32) -> u32 {
fn next_lock(work_queue: &mut Vec::<(xous::MessageSender, [u32; 4])>) -> Option<[u32; 4]> { fn next_lock(work_queue: &mut Vec::<(xous::MessageSender, [u32; 4])>) -> Option<[u32; 4]> {
if work_queue.len() > 0 { if work_queue.len() > 0 {
/*
log::debug!("pending:");
for (pid, tok) in work_queue.iter() {
log::debug!("pid: {:x?}, tok: {:x?}", pid, tok);
}
*/
let (unblock_pid, token) = work_queue.remove(0); let (unblock_pid, token) = work_queue.remove(0);
log::debug!("next token: {:x?}", token);
xous::return_scalar(unblock_pid, 1).unwrap(); xous::return_scalar(unblock_pid, 1).unwrap();
Some(token) Some(token)
} else { } else {

View file

@ -38,7 +38,7 @@ pub(crate) fn spawn_test() {
// The start and end items are deliberately structured to be not zero-indexed; the use of PDDB_LOC is just a // The start and end items are deliberately structured to be not zero-indexed; the use of PDDB_LOC is just a
// convenient global constant. // convenient global constant.
modals.start_progress("Progress Quest", xous::PDDB_LOC, xous::PDDB_LOC + 64*1024*128, xous::PDDB_LOC).expect("couldn't raise progress bar"); modals.start_progress("Progress Quest", xous::PDDB_LOC, xous::PDDB_LOC + 64*1024*128, xous::PDDB_LOC).expect("couldn't raise progress bar");
for i in (xous::PDDB_LOC..xous::PDDB_LOC + 64*1024*128).step_by(64*1024) { for i in (xous::PDDB_LOC..xous::PDDB_LOC + 64*1024*128).step_by(64*1024*16) {
modals.update_progress(i).expect("couldn't update progress bar"); modals.update_progress(i).expect("couldn't update progress bar");
tt.sleep_ms(100).unwrap(); tt.sleep_ms(100).unwrap();
} }