add radio buttons and checkboxes to the modals meta-handler

This commit is contained in:
bunnie 2021-12-17 00:32:44 +08:00
parent 91836e5574
commit 0fb1bea428
7 changed files with 204 additions and 34 deletions

View file

@ -86,7 +86,7 @@ impl TextEntryPayload {
} }
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[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 { impl RadioButtonPayload {
pub fn new(name: &str) -> Self { pub fn new(name: &str) -> Self {
RadioButtonPayload(ItemName::new(name)) RadioButtonPayload(ItemName::new(name))
@ -99,7 +99,7 @@ impl RadioButtonPayload {
} }
} }
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct CheckBoxPayload([Option<ItemName>; MAX_ITEMS]); // returns a list of potential items that could be selected pub struct CheckBoxPayload(pub [Option<ItemName>; MAX_ITEMS]); // returns a list of potential items that could be selected
impl CheckBoxPayload { impl CheckBoxPayload {
pub fn new() -> Self { pub fn new() -> Self {
CheckBoxPayload([None; MAX_ITEMS]) CheckBoxPayload([None; MAX_ITEMS])

View file

@ -13,7 +13,6 @@ pub struct CheckBoxes {
pub action_conn: xous::CID, pub action_conn: xous::CID,
pub action_opcode: u32, pub action_opcode: u32,
pub action_payload: CheckBoxPayload, pub action_payload: CheckBoxPayload,
pub max_items: i16,
pub select_index: i16, pub select_index: i16,
} }
impl CheckBoxes { impl CheckBoxes {
@ -23,7 +22,6 @@ impl CheckBoxes {
action_conn, action_conn,
action_opcode, action_opcode,
action_payload: CheckBoxPayload::new(), action_payload: CheckBoxPayload::new(),
max_items: 0,
select_index: 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; self.select_index += 1;
} }
} }

View file

@ -14,7 +14,6 @@ pub struct RadioButtons {
pub action_opcode: u32, pub action_opcode: u32,
pub action_payload: RadioButtonPayload, // the current "radio button" selection pub action_payload: RadioButtonPayload, // the current "radio button" selection
pub select_index: i16, // the current candidate to be selected pub select_index: i16, // the current candidate to be selected
pub max_items: i16,
pub is_password: bool, pub is_password: bool,
} }
impl RadioButtons { impl RadioButtons {
@ -25,7 +24,6 @@ impl RadioButtons {
action_opcode, action_opcode,
action_payload: RadioButtonPayload::new(""), action_payload: RadioButtonPayload::new(""),
select_index: 0, select_index: 0,
max_items: 0,
is_password: false, 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; self.select_index += 1;
} }
} }
'∴' | '\u{d}' => { '∴' | '\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()); self.action_payload = RadioButtonPayload::new(self.items[self.select_index as usize].as_str());
} else { // the OK button select } else { // the OK button select
let buf = Buffer::into_buf(self.action_payload).expect("couldn't convert message to payload"); let buf = Buffer::into_buf(self.action_payload).expect("couldn't convert message to payload");

View file

@ -17,8 +17,6 @@ pub(crate) enum ValidationOp {
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct ManagedPromptWithFixedResponse { pub struct ManagedPromptWithFixedResponse {
pub prompt: xous_ipc::String::<1024>, pub prompt: xous_ipc::String::<1024>,
pub items: [Option<ItemName>; MAX_ITEMS],
pub single_item: bool,
} }
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct ManagedPromptWithTextResponse { pub struct ManagedPromptWithTextResponse {
@ -47,9 +45,9 @@ pub struct ManagedProgress {
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum Opcode { pub(crate) enum Opcode {
// these are blocking calls // 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, 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, PromptWithMultiResponse,
/// ask a question, get a free-form answer back /// ask a question, get a free-form answer back
PromptWithTextResponse, PromptWithTextResponse,
@ -57,6 +55,9 @@ pub(crate) enum Opcode {
Notification, Notification,
// these are non-blocking calls // 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 /// raise a progress bar
StartProgress, StartProgress,
/// update the progress bar /// update the progress bar

View file

@ -21,7 +21,7 @@ impl Modals {
}) })
} }
pub fn get_text_input(&self, pub fn get_text(&self,
prompt: &str, prompt: &str,
maybe_validator: Option<fn(TextEntryPayload, u32) -> Option<ValidatorErr>>, maybe_validator: Option<fn(TextEntryPayload, u32) -> Option<ValidatorErr>>,
maybe_validator_op: Option<u32>, maybe_validator_op: Option<u32>,
@ -113,6 +113,39 @@ impl Modals {
).expect("couldn't stop progress"); ).expect("couldn't stop progress");
Ok(()) 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<String, 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::PromptWithFixedResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let itemname = buf.to_original::<ItemName, _>().unwrap();
Ok(String::from(itemname.as_str()))
}
pub fn get_checkbox(&self, prompt: &str) -> Result<Vec::<String>, 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::<CheckBoxPayload, _>().unwrap();
let mut ret = Vec::<String>::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}; use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -4,16 +4,14 @@
mod api; mod api;
use api::*; use api::*;
mod tests; mod tests;
use tests::*;
use xous::{SID, CID}; use xous::SID;
use xous::{msg_scalar_unpack, send_message, Message}; use xous::{msg_scalar_unpack, send_message, Message};
use xous_ipc::Buffer; use xous_ipc::Buffer;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::thread; use std::thread;
use core::sync::atomic::{AtomicBool, Ordering};
use gam::modal::*; use gam::modal::*;
use locales::t; use locales::t;
@ -24,13 +22,15 @@ enum RendererState {
/// idle state /// idle state
None, None,
/// running state /// running state
RunFixed(ManagedPromptWithFixedResponse), RunRadio(ManagedPromptWithFixedResponse),
RunCheckBox(ManagedPromptWithFixedResponse),
RunText(ManagedPromptWithTextResponse), RunText(ManagedPromptWithTextResponse),
RunProgress(ManagedProgress), RunProgress(ManagedProgress),
RunNotification(ManagedNotification), RunNotification(ManagedNotification),
/// response ready state /// response ready state
ResponseText(TextEntryPayload), ResponseText(TextEntryPayload),
ResponseFixed([Option<ItemName>; MAX_ITEMS]), ResponseRadio(ItemName),
ResponseCheckBox(CheckBoxPayload),
} }
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
@ -41,8 +41,11 @@ pub(crate) enum RendererOp {
TextEntryReturn, TextEntryReturn,
RadioReturn, RadioReturn,
CheckBoxReturn,
NotificationReturn, NotificationReturn,
AddModalItem,
ModalRedraw, ModalRedraw,
ModalKeypress, ModalKeypress,
ModalDrop, ModalDrop,
@ -70,7 +73,7 @@ fn xmain() -> ! {
let op = Arc::clone(&op); let op = Arc::clone(&op);
move || { move || {
// build the core data structure here // build the core data structure here
let mut 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,
@ -78,10 +81,7 @@ fn xmain() -> ! {
action_payload: TextEntryPayload::new(), action_payload: TextEntryPayload::new(),
validator: None, validator: None,
}; };
let mut radiobox = gam::modal::RadioButtons::new( let mut fixed_items = Vec::<ItemName>::new();
renderer_cid,
RendererOp::RadioReturn.to_u32().unwrap()
);
let notification = gam::modal::Notification::new( let notification = gam::modal::Notification::new(
renderer_cid, renderer_cid,
RendererOp::NotificationReturn.to_u32().unwrap() RendererOp::NotificationReturn.to_u32().unwrap()
@ -147,9 +147,37 @@ fn xmain() -> ! {
); );
renderer_modal.activate(); renderer_modal.activate();
}, },
RendererState::RunFixed(config) => { RendererState::RunRadio(config) => {
// going back to modify the GAM to use a smarter heap allocated struct for radio list let mut radiobuttons = gam::modal::RadioButtons::new(
//radiobox.add_item(); 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 => { RendererState::None => {
log::error!("Operation initiated with no argument specified. Ignoring request."); 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::<ItemName, _>().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::<RadioButtonPayload, _>().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::<CheckBoxPayload, _>().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) => { Some(RendererOp::ModalRedraw) => {
renderer_modal.redraw(); renderer_modal.redraw();
}, },
@ -252,9 +313,6 @@ fn xmain() -> ! {
None => { None => {
log::error!("Couldn't convert opcode: {:?}", msg); log::error!("Couldn't convert opcode: {:?}", msg);
} }
_ => {
unimplemented!();
}
} }
} }
xous::destroy_server(renderer_sid).unwrap(); xous::destroy_server(renderer_sid).unwrap();
@ -270,10 +328,50 @@ fn xmain() -> ! {
log::debug!("message: {:?}", msg); log::debug!("message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::PromptWithFixedResponse) => { 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();
*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) => { 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();
*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) => { Some(Opcode::PromptWithTextResponse) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; 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) Message::new_scalar(RendererOp::FinishProgress.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't update progress bar"); ).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) => { Some(Opcode::Quit) => {
log::warn!("Shared modal UX handler exiting."); log::warn!("Shared modal UX handler exiting.");
break break

View file

@ -4,6 +4,21 @@ use gam::*;
use xous_names::XousNames; 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() { pub(crate) fn spawn_test() {
thread::spawn({ thread::spawn({
move || { move || {
@ -19,14 +34,37 @@ pub(crate) fn spawn_test() {
} }
modals.finish_progress().expect("couldn't dismiss progress bar"); 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 // test the modal dialog box function
log::info!("test text input"); 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) => { Ok(text) => {
log::info!("Input: {}", text.0); log::info!("Input: {}", text.0);
} }
_ => { _ => {
log::error!("get_text_input failed"); log::error!("get_text failed");
} }
} }
log::info!("text input test done"); log::info!("text input test done");