From e48c472b324bc8adbec4276276384be5d701c92b Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 15 Dec 2021 13:46:43 +0800 Subject: [PATCH] helps to add the code for the new service --- services/modals/Cargo.toml | 25 +++ services/modals/locales/i18n.json | 7 + services/modals/src/api.rs | 85 ++++++++++ services/modals/src/lib.rs | 94 +++++++++++ services/modals/src/main.rs | 269 ++++++++++++++++++++++++++++++ 5 files changed, 480 insertions(+) create mode 100644 services/modals/Cargo.toml create mode 100644 services/modals/locales/i18n.json create mode 100644 services/modals/src/api.rs create mode 100644 services/modals/src/lib.rs create mode 100644 services/modals/src/main.rs diff --git a/services/modals/Cargo.toml b/services/modals/Cargo.toml new file mode 100644 index 000000000..75e4fa5be --- /dev/null +++ b/services/modals/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "modals" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "Ux modals server" + +[dependencies] +xous = { path = "../../xous-rs" } +log-server = { path = "../log-server" } +ticktimer-server = { path = "../ticktimer-server" } +xous-names = { path = "../xous-names" } +log = "0.4" +num-derive = {version = "0.3", default-features = false} +num-traits = {version = "0.2", default-features = false} +xous-ipc = { path = "../../xous-ipc" } +rkyv = {version = "0.4.3", features = ["const_generics"], default-features = false} +gam = {path="../gam"} +locales = {path = "../../locales"} + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +default = [] diff --git a/services/modals/locales/i18n.json b/services/modals/locales/i18n.json new file mode 100644 index 000000000..794d0bb0d --- /dev/null +++ b/services/modals/locales/i18n.json @@ -0,0 +1,7 @@ +{ + "modals.invalid_text": { + "en": "Invalid input", + "zh": "输入无效", + "en-audio": "Invalid input" + } +} \ No newline at end of file diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs new file mode 100644 index 000000000..04f57c22c --- /dev/null +++ b/services/modals/src/api.rs @@ -0,0 +1,85 @@ +use gam::modal::*; + +pub(crate) const SERVER_NAME_MODALS: &str = "_Modal Dialog Server_"; +pub const SHARED_MODAL_NAME: &str = "shared modal"; + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct Validation { + pub text: TextEntryPayload, + pub opcode: u32, +} +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum ValidationOp { + Validate, + Quit, +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct ManagedPromptWithFixedResponse { + pub prompt: xous_ipc::String::<1024>, + pub items: [Option; MAX_ITEMS], +} +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct ManagedPromptWithTextResponse { + 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 { + pub message: xous_ipc::String::<1024>, +} +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct ManagedProgress { + pub title: xous_ipc::String::<1024>, + // these are automatcally turned into percentages on a scale of 0->100% + /// starting quanta to track (e.g. starting sector for erase). + pub start_work: u32, + /// end quanta to track (e.g. ending sector for erase). end is by definition the larger number than start. + pub end_work: u32, + /// current quanta of work. Used to int the bar, updates are just a scalar with the same value. + pub current_work: u32, +} + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum Opcode { + // these are blocking calls + /// ask a question, get a single response from a list of defined items + PromptWithFixedResponse, + /// ask a question, get multiple responses from a list of defined items + PromptWithMultiResponse, + /// ask a question, get a free-form answer back + PromptWithTextResponse, + /// simple notification + Notification, + + // these are non-blocking calls + /// raise a progress bar + StartProgress, + /// update the progress bar + UpdateProgress, + /// lower a progress bar + StopProgress, + Quit, +} + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum UxOpcode { + // add UX opcodes here, separate from the main loop's + Format, + OkCancelNotice, + OkNotice, + UnlockBasis, + LockBasis, + LockAllBasis, + Scuttle, + + PasswordReturn, + ModalRedraw, + ModalKeys, + ModalDrop, + Gutter, + Quit, +} diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs new file mode 100644 index 000000000..062fd5179 --- /dev/null +++ b/services/modals/src/lib.rs @@ -0,0 +1,94 @@ +#![cfg_attr(target_os = "none", no_std)] + +pub mod api; +use api::*; + +use gam::TextEntryPayload; +use xous::{CID, SID, send_message, Message}; +use num_traits::{ToPrimitive, FromPrimitive}; +use xous_ipc::Buffer; +use std::thread; + +pub struct Modals { + conn: CID, +} +impl Modals { + pub fn new(xns: &xous_names::XousNames) -> Result { + REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + let conn = xns.request_connection_blocking(api::SERVER_NAME_MODALS).expect("Can't connect to Modals server"); + Ok(Modals { + conn + }) + } + + pub fn get_text_input(&self, + prompt: &str, + maybe_validator: Option Option> >, + maybe_validator_op: Option, + ) -> Result { + 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 { + prompt: xous_ipc::String::<1024>::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"); + } + match buf.to_original::() { + Ok(response) => Ok(response), + _ => Err(xous::Error::InternalError) + } + } +} + +use core::sync::atomic::{AtomicU32, Ordering}; +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for Modals { + fn drop(&mut self) { + // the connection to the server side must be reference counted, so that multiple instances of this object within + // a single process do not end up de-allocating the CID on other threads before they go out of scope. + // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". + if REFCOUNT.load(Ordering::Relaxed) == 0 { + unsafe{xous::disconnect(self.conn).unwrap();} + } + // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), + // de-allocate those items here. They don't need a reference count because they are object-specific + } +} \ No newline at end of file diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs new file mode 100644 index 000000000..9487eca60 --- /dev/null +++ b/services/modals/src/main.rs @@ -0,0 +1,269 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +mod api; +use api::*; + +use xous::{SID, CID}; + +use xous::{msg_scalar_unpack, send_message, Message}; +use xous_ipc::Buffer; + +use std::sync::{Arc, Mutex}; +use std::thread; +use core::sync::atomic::{AtomicBool, Ordering}; + +use gam::modal::*; +use locales::t; + +use num_traits::*; + +enum RendererState { + /// idle state + None, + /// running state + RunFixed(ManagedPromptWithFixedResponse), + RunText(ManagedPromptWithTextResponse), + RunProgress(ManagedProgress), + RunNotification(ManagedNotification), + /// response ready state + ResponseText(TextEntryPayload), + ResponseFixed([Option; MAX_ITEMS]), +} + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum RendererOp { + InitiateOp, + + TextEntryReturn, + RadioReturn, + NotificationReturn, + + ModalRedraw, + ModalKeypress, + ModalDrop, + Quit, +} + +#[xous::xous_main] +fn xmain() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Trace); + log::info!("my PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + let modals_sid = xns.register_name(api::SERVER_NAME_MODALS, None).expect("can't register server"); + log::trace!("registered with NS -- {:?}", modals_sid); + + let tt = ticktimer_server::Ticktimer::new().unwrap(); + + let renderer_sid = xous::create_server().expect("couldn't create a server for the modal UX renderer"); + let renderer_cid = xous::connect(renderer_sid).expect("couldn't connect to the modal UX renderer"); + + let op = Arc::new(Mutex::new(RendererState::None)); + // create a thread that just handles the redrawing requests + let redraw_handle = thread::spawn({ + let op = Arc::clone(&op); + move || { + // build the core data structure here + let mut text_action = TextEntry { + is_password: false, + visibility: TextEntryVisibility::Visible, + action_conn: renderer_cid, + action_opcode: RendererOp::TextEntryReturn.to_u32().unwrap(), + action_payload: TextEntryPayload::new(), + validator: None, + }; + let mut radiobox = gam::modal::RadioButtons::new( + renderer_cid, + RendererOp::RadioReturn.to_u32().unwrap() + ); + let mut notification = gam::modal::Notification::new( + renderer_cid, + RendererOp::NotificationReturn.to_u32().unwrap() + ); + let mut progress_action = Slider::new(renderer_cid, RendererOp::NotificationReturn.to_u32().unwrap(), + 0, 100, 10, Some("%"), 0, true, true + ); + let mut renderer_modal = + Modal::new( + crate::api::SHARED_MODAL_NAME, + ActionType::TextEntry(text_action), + Some("Placeholder"), + None, + GlyphStyle::Small, + 8 + ); + let mut progressbar = ProgressBar::new(&mut renderer_modal, &mut progress_action); + renderer_modal.spawn_helper(renderer_sid, renderer_modal.sid, + RendererOp::ModalRedraw.to_u32().unwrap(), + RendererOp::ModalKeypress.to_u32().unwrap(), + RendererOp::ModalDrop.to_u32().unwrap(), + ); + + loop { + let msg = xous::receive_message(renderer_sid).unwrap(); + log::debug!("renderer message: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(RendererOp::InitiateOp) => { + log::info!("InitiateOp called"); + let mutex_op = op.lock().unwrap(); + match *mutex_op { + RendererState::RunText(config) => { + log::info!("initiating text entry modal"); + renderer_modal.modify( + Some(ActionType::TextEntry(text_action)), + Some(config.prompt.as_str().unwrap()), false, + None, false, None + ); + renderer_modal.activate(); + log::info!("should be active!"); + }, + RendererState::None => { + log::error!("Operation initiated with no argument specified. Ignoring request."); + continue; + } + _ => { + log::warn!("unimplemented arm in renderer match"); + unimplemented!(); + } + } + }, + Some(RendererOp::TextEntryReturn) => { + let mut mutex_op = op.lock().unwrap(); + match *mutex_op { + RendererState::RunText(config) => { + log::info!("validating text entry modale"); + 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 { + // the change in mutex_op enum type will signal the state change to the caller + *mutex_op = RendererState::ResponseText(text); + } + } else { + *mutex_op = RendererState::ResponseText(text); + } + } + _ => { + log::error!("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::ModalRedraw) => { + renderer_modal.redraw(); + }, + Some(RendererOp::ModalKeypress) => msg_scalar_unpack!(msg, k1, k2, k3, k4, { + 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(k2 as u32) {a} else {'\u{0000}'}, + if let Some(a) = core::char::from_u32(k3 as u32) {a} else {'\u{0000}'}, + if let Some(a) = core::char::from_u32(k4 as u32) {a} else {'\u{0000}'}, + ]; + renderer_modal.key_event(keys); + }), + Some(RendererOp::ModalDrop) => { // this guy should never quit, it's a core OS service + 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); + } + _ => { + unimplemented!(); + } + } + } + xous::destroy_server(renderer_sid).unwrap(); + } + }); + + loop { + let mut msg = xous::receive_message(modals_sid).unwrap(); + log::debug!("message: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::PromptWithFixedResponse) => { + + }, + Some(Opcode::PromptWithMultiResponse) => { + + }, + Some(Opcode::PromptWithTextResponse) => { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let spec = buffer.to_original::().unwrap(); + { + *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(); + 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) => { + + }, + Some(Opcode::StartProgress) => { + + }, + Some(Opcode::UpdateProgress) => { + + }, + Some(Opcode::StopProgress) => { + + }, + Some(Opcode::Quit) => { + log::warn!("Shared modal UX handler exiting."); + break + } + None => { + log::error!("couldn't convert opcode"); + } + + } + } + // clean up our program + 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(); + xous::destroy_server(modals_sid).unwrap(); + log::trace!("quitting"); + xous::terminate_process(0) +}