From c97a00ed1f67a519f0478e73b17a0777a7d2e563 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 7 Apr 2022 04:38:38 +0800 Subject: [PATCH] refactor validator to not create a new single-use server --- services/modals/src/api.rs | 11 ++--- services/modals/src/lib.rs | 91 +++++++++++++++++-------------------- services/modals/src/main.rs | 57 +++++++---------------- 3 files changed, 62 insertions(+), 97 deletions(-) diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs index 3e9f53759..9ff28188b 100644 --- a/services/modals/src/api.rs +++ b/services/modals/src/api.rs @@ -27,10 +27,6 @@ pub struct ManagedListItem { pub struct ManagedPromptWithTextResponse { pub token: [u32; 4], pub prompt: xous_ipc::String::<1024>, - /// SID of a validator - pub validator: Option<[u32; 4]>, - /// the opcode to pass the validator - pub validator_op: u32, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct ManagedNotification { @@ -67,13 +63,16 @@ pub(crate) enum Opcode { PromptWithFixedResponse, /// ask a question, get multiple responses from a list of defined items (check box) PromptWithMultiResponse, - /// ask a question, get a free-form answer back - PromptWithTextResponse, /// simple notification Notification, /// dynamic notification - a simple non-interactive notification that allows its text to be dynamically updated DynamicNotification, + /// ask a question, get a free-form answer back + PromptWithTextResponse, + /// must be used by the PromptWithTextResponse caller to acknowledge correct input + TextResponseValid, + // these are non-blocking calls /// add an item to the radio box or check box. Note that all added items /// are cleared after the relevant "action" call happens (PromptWith[Fixed,Multi]Response) diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 648e62f4e..cc20929f0 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -4,10 +4,9 @@ pub mod api; use api::*; use gam::*; -use xous::{CID, SID, send_message, Message}; -use num_traits::{ToPrimitive, FromPrimitive}; +use xous::{CID, send_message, Message}; +use num_traits::*; use xous_ipc::Buffer; -use std::thread; use core::cell::Cell; pub struct Modals { @@ -35,56 +34,48 @@ impl Modals { maybe_validator_op: Option, ) -> Result { self.lock(); - let validator = if let Some(validator) = maybe_validator { - // create a one-time use server - let validator_server = xous::create_server().unwrap(); - thread::spawn({ - let vsid = validator_server.to_array(); - move || { - loop { - let mut msg = xous::receive_message(SID::from_array(vsid)).unwrap(); - log::debug!("validator message: {:?}", msg); - match FromPrimitive::from_usize(msg.body.id()) { - Some(ValidationOp::Validate) => { - let mut buffer = unsafe{Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())}; - let validation = buffer.to_original::().unwrap(); - let result = validator(validation.text, validation.opcode); - buffer.replace(result).expect("couldn't place validation result"); - } - Some(ValidationOp::Quit) => { - // this is a blocking scalar, have to return a dummy value to unblock the caller - xous::return_scalar(msg.sender, 0).unwrap(); - break; - } - _ => { - log::error!("received unknown message: {:?}", msg); - } - } - } - } - }); - Some(validator_server.to_array()) - } else { - None - }; - let spec = ManagedPromptWithTextResponse { + + let mut spec = ManagedPromptWithTextResponse { token: self.token, prompt: xous_ipc::String::from_str(prompt), - validator, - validator_op: maybe_validator_op.unwrap_or(0) }; - let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; - buf.lend_mut(self.conn, Opcode::PromptWithTextResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; - if let Some(server) = validator { - let cid = xous::connect(SID::from_array(server)).unwrap(); - send_message(cid, Message::new_blocking_scalar(ValidationOp::Quit.to_usize().unwrap(), 0, 0, 0, 0)).unwrap(); - 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"); - } - self.unlock(); - match buf.to_original::() { - Ok(response) => Ok(response), - _ => Err(xous::Error::InternalError) + // question: do we want to add a retry limit? + loop { + let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::PromptWithTextResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + match buf.to_original::() { + Ok(response) => { + if let Some(validator) = maybe_validator { + if let Some(err_msg) = validator(response, maybe_validator_op.unwrap_or(0)) { + spec.prompt.clear(); + spec.prompt.append(err_msg.as_str().unwrap_or("UTF-8 error")).ok(); + } else { + send_message(self.conn, + Message::new_blocking_scalar(Opcode::TextResponseValid.to_usize().unwrap(), + self.token[0] as _, self.token[1] as _, self.token[2] as _, self.token[3] as _, + )).expect("couldn't acknowledge text entry"); + self.unlock(); + return Ok(response) + } + } else { + send_message(self.conn, + Message::new_blocking_scalar(Opcode::TextResponseValid.to_usize().unwrap(), + self.token[0] as _, self.token[1] as _, self.token[2] as _, self.token[3] as _, + )).expect("couldn't acknowledge text entry"); + self.unlock(); + return Ok(response) + } + }, + _ => { + // we send the valid response token even in this case because we want the modals server to move on and not get stuck on this error. + send_message(self.conn, + Message::new_blocking_scalar(Opcode::TextResponseValid.to_usize().unwrap(), + self.token[0] as _, self.token[1] as _, self.token[2] as _, self.token[3] as _, + )).expect("couldn't acknowledge text entry"); + self.unlock(); + return Err(xous::Error::InternalError); + } + } } } diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index ec791836a..8d4cca1b3 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -5,8 +5,6 @@ mod api; use api::*; mod tests; -use xous::SID; - use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack, send_message, Message}; use xous_ipc::Buffer; @@ -455,49 +453,17 @@ fn xmain() -> ! { }, Some(Opcode::TextEntryReturn) => { match op { - RendererState::RunText(config) => { + RendererState::RunText(_config) => { log::trace!("validating text entry modal"); let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let text = buf.to_original::().unwrap(); - if let Some(validator_sid) = config.validator { - let cid = xous::connect(SID::from_array(validator_sid)).unwrap(); - let validation = Validation { - text, - opcode: config.validator_op, - }; - let mut buf = Buffer::into_buf(validation).expect("couldn't convert validator structure"); - buf.lend_mut(cid, ValidationOp::Validate.to_u32().unwrap()).expect("validation call failed"); - let response = buf.to_original::>, _>().expect("couldn't unpack validation response"); - unsafe{xous::disconnect(cid).unwrap();} - if let Some(err) = response { - // try again - renderer_modal.modify( - Some(ActionType::TextEntry(text_action)), - Some(config.prompt.as_str().unwrap()), false, - Some(err.as_str().unwrap()), false, None - ); - renderer_modal.activate(); - } else { - 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); - } + 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 { - 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); + log::error!("Ux routine returned but no origin was recorded"); + panic!("Ux routine returned but no origin was recorded"); } } RendererState::None => log::warn!("Text entry detected a fat finger event, ignoring."), @@ -507,6 +473,15 @@ fn xmain() -> ! { } } } + Some(Opcode::TextResponseValid) => 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 incoming_token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + } else { + token_lock = next_lock(&mut work_queue); + } + xous::return_scalar(msg.sender, 1).unwrap(); + }), Some(Opcode::NotificationReturn) => { match op { RendererState::RunNotification(_) => {