From 0fb1bea42886ddc014c2a14cfdbd6a4313a7b15b Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 17 Dec 2021 00:32:44 +0800 Subject: [PATCH] add radio buttons and checkboxes to the modals meta-handler --- services/gam/src/modal.rs | 4 +- services/gam/src/modal/checkboxes.rs | 4 +- services/gam/src/modal/radiobuttons.rs | 6 +- services/modals/src/api.rs | 9 +- services/modals/src/lib.rs | 35 ++++++- services/modals/src/main.rs | 138 +++++++++++++++++++++---- services/modals/src/tests.rs | 42 +++++++- 7 files changed, 204 insertions(+), 34 deletions(-) diff --git a/services/gam/src/modal.rs b/services/gam/src/modal.rs index 9c241e120..cf17c6ebe 100644 --- a/services/gam/src/modal.rs +++ b/services/gam/src/modal.rs @@ -86,7 +86,7 @@ impl TextEntryPayload { } #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub struct RadioButtonPayload(ItemName); // returns the name of the item corresponding to the radio button selection +pub struct RadioButtonPayload(pub ItemName); // returns the name of the item corresponding to the radio button selection impl RadioButtonPayload { pub fn new(name: &str) -> Self { RadioButtonPayload(ItemName::new(name)) @@ -99,7 +99,7 @@ impl RadioButtonPayload { } } #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] -pub struct CheckBoxPayload([Option; MAX_ITEMS]); // returns a list of potential items that could be selected +pub struct CheckBoxPayload(pub [Option; MAX_ITEMS]); // returns a list of potential items that could be selected impl CheckBoxPayload { pub fn new() -> Self { CheckBoxPayload([None; MAX_ITEMS]) diff --git a/services/gam/src/modal/checkboxes.rs b/services/gam/src/modal/checkboxes.rs index 52ddbb362..fbf89ac4d 100644 --- a/services/gam/src/modal/checkboxes.rs +++ b/services/gam/src/modal/checkboxes.rs @@ -13,7 +13,6 @@ pub struct CheckBoxes { pub action_conn: xous::CID, pub action_opcode: u32, pub action_payload: CheckBoxPayload, - pub max_items: i16, pub select_index: i16, } impl CheckBoxes { @@ -23,7 +22,6 @@ impl CheckBoxes { action_conn, action_opcode, action_payload: CheckBoxPayload::new(), - max_items: 0, select_index: 0, } } @@ -134,7 +132,7 @@ impl ActionApi for CheckBoxes { } } '↓' => { - if self.select_index < self.max_items + 1 { // +1 is the "OK" button + if self.select_index < self.items.len() as i16 + 1 { // +1 is the "OK" button self.select_index += 1; } } diff --git a/services/gam/src/modal/radiobuttons.rs b/services/gam/src/modal/radiobuttons.rs index 18e038742..3b5a9ad5d 100644 --- a/services/gam/src/modal/radiobuttons.rs +++ b/services/gam/src/modal/radiobuttons.rs @@ -14,7 +14,6 @@ pub struct RadioButtons { pub action_opcode: u32, pub action_payload: RadioButtonPayload, // the current "radio button" selection pub select_index: i16, // the current candidate to be selected - pub max_items: i16, pub is_password: bool, } impl RadioButtons { @@ -25,7 +24,6 @@ impl RadioButtons { action_opcode, action_payload: RadioButtonPayload::new(""), select_index: 0, - max_items: 0, is_password: false, } } @@ -149,12 +147,12 @@ impl ActionApi for RadioButtons { } } '↓' => { - if self.select_index < self.max_items + 1 { // +1 is the "OK" button + if self.select_index < self.items.len() as i16 + 1 { // +1 is the "OK" button self.select_index += 1; } } '∴' | '\u{d}' => { - if self.select_index < self.max_items { + if self.select_index < self.items.len() as i16 { self.action_payload = RadioButtonPayload::new(self.items[self.select_index as usize].as_str()); } else { // the OK button select let buf = Buffer::into_buf(self.action_payload).expect("couldn't convert message to payload"); diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs index 2e024f2df..8a8123aff 100644 --- a/services/modals/src/api.rs +++ b/services/modals/src/api.rs @@ -17,8 +17,6 @@ pub(crate) enum ValidationOp { #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct ManagedPromptWithFixedResponse { pub prompt: xous_ipc::String::<1024>, - pub items: [Option; MAX_ITEMS], - pub single_item: bool, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct ManagedPromptWithTextResponse { @@ -47,9 +45,9 @@ pub struct ManagedProgress { #[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 + /// ask a question, get a single response from a list of defined items (radio box) PromptWithFixedResponse, - /// ask a question, get multiple responses from a list of defined items + /// 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, @@ -57,6 +55,9 @@ pub(crate) enum Opcode { Notification, // 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 (PrmoptWith[Fixed,Multi]Response) + AddModalItem, /// raise a progress bar StartProgress, /// update the progress bar diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 6998184e7..71ddaa27c 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -21,7 +21,7 @@ impl Modals { }) } - pub fn get_text_input(&self, + pub fn get_text(&self, prompt: &str, maybe_validator: Option Option>, maybe_validator_op: Option, @@ -113,6 +113,39 @@ impl Modals { ).expect("couldn't stop progress"); Ok(()) } + + pub fn add_list_item(&self, item: &str) -> Result<(), xous::Error> { + let itemname = ItemName::new(item); + let buf = Buffer::into_buf(itemname).or(Err(xous::Error::InternalError))?; + buf.lend(self.conn, Opcode::AddModalItem.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + Ok(()) + } + + pub fn get_radiobutton(&self, prompt: &str) -> Result { + let spec = ManagedPromptWithFixedResponse { + prompt: xous_ipc::String::from_str(prompt), + }; + 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))?; + let itemname = buf.to_original::().unwrap(); + Ok(String::from(itemname.as_str())) + } + + pub fn get_checkbox(&self, prompt: &str) -> Result, xous::Error> { + let spec = ManagedPromptWithFixedResponse { + prompt: xous_ipc::String::from_str(prompt), + }; + let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::PromptWithMultiResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + let selected_items = buf.to_original::().unwrap(); + let mut ret = Vec::::new(); + for maybe_item in selected_items.payload() { + if let Some(item) = maybe_item { + ret.push(String::from(item.as_str())); + } + } + Ok(ret) + } } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index 017691f0b..fd34ce6ef 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -4,16 +4,14 @@ mod api; use api::*; mod tests; -use tests::*; -use xous::{SID, CID}; +use xous::SID; 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; @@ -24,13 +22,15 @@ enum RendererState { /// idle state None, /// running state - RunFixed(ManagedPromptWithFixedResponse), + RunRadio(ManagedPromptWithFixedResponse), + RunCheckBox(ManagedPromptWithFixedResponse), RunText(ManagedPromptWithTextResponse), RunProgress(ManagedProgress), RunNotification(ManagedNotification), /// response ready state ResponseText(TextEntryPayload), - ResponseFixed([Option; MAX_ITEMS]), + ResponseRadio(ItemName), + ResponseCheckBox(CheckBoxPayload), } #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] @@ -41,8 +41,11 @@ pub(crate) enum RendererOp { TextEntryReturn, RadioReturn, + CheckBoxReturn, NotificationReturn, + AddModalItem, + ModalRedraw, ModalKeypress, ModalDrop, @@ -70,7 +73,7 @@ fn xmain() -> ! { let op = Arc::clone(&op); move || { // build the core data structure here - let mut text_action = TextEntry { + let text_action = TextEntry { is_password: false, visibility: TextEntryVisibility::Visible, action_conn: renderer_cid, @@ -78,10 +81,7 @@ fn xmain() -> ! { action_payload: TextEntryPayload::new(), validator: None, }; - let mut radiobox = gam::modal::RadioButtons::new( - renderer_cid, - RendererOp::RadioReturn.to_u32().unwrap() - ); + let mut fixed_items = Vec::::new(); let notification = gam::modal::Notification::new( renderer_cid, RendererOp::NotificationReturn.to_u32().unwrap() @@ -147,9 +147,37 @@ fn xmain() -> ! { ); renderer_modal.activate(); }, - RendererState::RunFixed(config) => { - // going back to modify the GAM to use a smarter heap allocated struct for radio list - //radiobox.add_item(); + RendererState::RunRadio(config) => { + let mut radiobuttons = gam::modal::RadioButtons::new( + renderer_cid, + RendererOp::RadioReturn.to_u32().unwrap() + ); + for item in fixed_items.iter() { + radiobuttons.add_item(*item); + } + fixed_items.clear(); + renderer_modal.modify( + Some(ActionType::RadioButtons(radiobuttons)), + Some(config.prompt.as_str().unwrap()), false, + None, true, None + ); + renderer_modal.activate(); + }, + RendererState::RunCheckBox(config) => { + let mut checkbox = gam::modal::CheckBoxes::new( + renderer_cid, + RendererOp::CheckBoxReturn.to_u32().unwrap() + ); + for item in fixed_items.iter() { + checkbox.add_item(*item); + } + fixed_items.clear(); + renderer_modal.modify( + Some(ActionType::CheckBoxes(checkbox)), + Some(config.prompt.as_str().unwrap()), false, + None, true, None + ); + renderer_modal.activate(); }, RendererState::None => { log::error!("Operation initiated with no argument specified. Ignoring request."); @@ -229,6 +257,39 @@ fn xmain() -> ! { } } }, + Some(RendererOp::AddModalItem) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let item = buffer.to_original::().unwrap(); + fixed_items.push(item); + } + Some(RendererOp::RadioReturn) => { + let mut mutex_op = op.lock().unwrap(); + match *mutex_op { + RendererState::RunRadio(_config) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let item = buffer.to_original::().unwrap(); + *mutex_op = RendererState::ResponseRadio(item.0); + } + _ => { + 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::CheckBoxReturn) => { + let mut mutex_op = op.lock().unwrap(); + match *mutex_op { + RendererState::RunCheckBox(_config) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let item = buffer.to_original::().unwrap(); + *mutex_op = RendererState::ResponseCheckBox(item); + } + _ => { + 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(); }, @@ -252,9 +313,6 @@ fn xmain() -> ! { None => { log::error!("Couldn't convert opcode: {:?}", msg); } - _ => { - unimplemented!(); - } } } xous::destroy_server(renderer_sid).unwrap(); @@ -270,10 +328,50 @@ fn xmain() -> ! { log::debug!("message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(Opcode::PromptWithFixedResponse) => { - + 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::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(); + 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::().unwrap(); + *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(); + 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()) }; @@ -339,6 +437,10 @@ fn xmain() -> ! { Message::new_scalar(RendererOp::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()) }; + buffer.lend(renderer_cid, RendererOp::AddModalItem.to_u32().unwrap()).expect("couldn't add item"); + } Some(Opcode::Quit) => { log::warn!("Shared modal UX handler exiting."); break diff --git a/services/modals/src/tests.rs b/services/modals/src/tests.rs index e3246e813..254275890 100644 --- a/services/modals/src/tests.rs +++ b/services/modals/src/tests.rs @@ -4,6 +4,21 @@ use gam::*; use xous_names::XousNames; +const RADIO_TEST: [&'static str; 4] = [ + "zebra", + "cow", + "horse", + "cat", +]; + +const CHECKBOX_TEST: [&'static str; 5] = [ + "happy", + "😃", + "安", + "peaceful", + "...something else!", +]; + pub(crate) fn spawn_test() { thread::spawn({ move || { @@ -19,14 +34,37 @@ pub(crate) fn spawn_test() { } modals.finish_progress().expect("couldn't dismiss progress bar"); + // test radio box + for item in RADIO_TEST { + modals.add_list_item(item).expect("couldn't build radio item list"); + } + match modals.get_radiobutton("Pick an animal") { + Ok(animal) => log::info!("{} was picked", animal), + _ => log::error!("get_radiobutton failed"), + } + + // test check box + for item in CHECKBOX_TEST { + modals.add_list_item(item).expect("couldn't build checkbox list"); + } + match modals.get_checkbox("You can have it all:") { + Ok(things) => { + log::info!("The user picked {} things:", things.len()); + for thing in things { + log::info!("{}", thing); + } + }, + _ => log::error!("get_checkbox failed"), + } + // test the modal dialog box function log::info!("test text input"); - match modals.get_text_input("Test input", Some(test_validator), None) { + match modals.get_text("Test input", Some(test_validator), None) { Ok(text) => { log::info!("Input: {}", text.0); } _ => { - log::error!("get_text_input failed"); + log::error!("get_text failed"); } } log::info!("text input test done");