From 89c768625dc0f32da36868720e335284ca394be5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Wed, 13 Apr 2022 15:49:31 +0200 Subject: [PATCH] modals: add builder-based interface to present alerts with text fields inside --- services/modals/src/lib.rs | 196 +++++++++++++++++++---------------- services/modals/src/tests.rs | 9 +- 2 files changed, 110 insertions(+), 95 deletions(-) diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index fb9ed5203..b9991bff5 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -9,6 +9,103 @@ use num_traits::*; use xous_ipc::Buffer; use core::cell::Cell; +pub type TextValidationFn = fn(TextEntryPayload) -> Option; + +pub struct AlertModalBuilder<'a> { + prompt: String, + validators: Vec>, + placeholders: Vec>, + fields_amt: u8, // TODO: this can go away, len(validators) and len(placeholders) are equal, which means + // fields_amt == len(validators) || len(placeholders) + modals: &'a Modals, +} + +impl<'a> AlertModalBuilder<'a> { + pub fn field(&'a mut self, placeholder: Option, validator: Option) -> &'a mut Self { + self.validators.push(validator); + self.placeholders.push(placeholder); + self.fields_amt += 1; + self + } + + pub fn build(&self) -> Result { + self.modals.lock(); + let mut final_placeholders: Option<[Option>; 10]> = None; + + match self.placeholders.len() { + 1.. => { + let mut pl:[Option>; 10] = Default::default(); + + if self.fields_amt != self.placeholders.len() as u8 { + log::warn!("can't have more fields than placeholders"); + return Err(xous::Error::UnknownError); + } + + for (index, placeholder) in self.placeholders.iter().enumerate() { + if let Some(string) = placeholder { + pl[index] = Some(xous_ipc::String::from_str(&string)) + } else { + pl[index] = None + } + } + + final_placeholders = Some(pl) + } + 0 => (), + _ => panic!("somehow len of placeholders was neither zero or >= 1...?") + } + + let mut spec = ManagedPromptWithTextResponse { + token: self.modals.token, + prompt: xous_ipc::String::from_str(&self.prompt), + fields: self.fields_amt as u32, + placeholders: final_placeholders, + }; + + // 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.modals.conn, Opcode::PromptWithTextResponse.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + match buf.to_original::() { + Ok(response) => { + let mut form_validation_failed = false; + for (index, validator) in self.validators.iter().enumerate() { + if let Some(validator) = validator { + if let Some(err_msg) = validator(response.content()[index]) { + spec.prompt.clear(); + spec.prompt.append(err_msg.as_str().unwrap_or("UTF-8 error")).ok(); + form_validation_failed = true; + break; // one of the validator failed + } + } + } + + if form_validation_failed { + continue; // leave the modal as it is + } + + // If we're here all non-None validators returned okay, or no validators were specified in the first place at all. + send_message(self.modals.conn, + Message::new_blocking_scalar(Opcode::TextResponseValid.to_usize().unwrap(), + self.modals.token[0] as _, self.modals.token[1] as _, self.modals.token[2] as _, self.modals.token[3] as _, + )).expect("couldn't acknowledge text entry"); + self.modals.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.modals.conn, + Message::new_blocking_scalar(Opcode::TextResponseValid.to_usize().unwrap(), + self.modals.token[0] as _, self.modals.token[1] as _, self.modals.token[2] as _, self.modals.token[3] as _, + )).expect("couldn't acknowledge text entry"); + self.modals.unlock(); + return Err(xous::Error::InternalError); + } + } + } + } +} + pub struct Modals { conn: CID, token: [u32; 4], @@ -28,98 +125,13 @@ impl Modals { }) } - pub fn get_text(&self, - prompt: &str, - maybe_validator: Option Option>, - maybe_validator_op: Option, - placeholder: Option - ) -> Result { - match self.get_text_multi(prompt, maybe_validator, maybe_validator_op, 1, Some(vec![placeholder])) { - Ok(res) => { - return Ok(res.first()) - }, - Err(error) => return Err(error), - } - } - - pub fn get_text_multi(&self, - prompt: &str, - maybe_validator: Option Option>, - maybe_validator_op: Option, - fields: u32, - placeholders: Option>>, - ) -> Result { - self.lock(); - let mut final_placeholders: Option<[Option>; 10]> = None; - - match placeholders { - Some(placeholders) => { - let mut pl:[Option>; 10] = Default::default(); - //final_placeholders = Some(Default::default()); - - if fields != placeholders.len() as u32 { - log::warn!("can't have more fields than placeholders"); - return Err(xous::Error::UnknownError); - } - - for (index, placeholder) in placeholders.iter().enumerate() { - match placeholder { - Some(string) => { - pl[index] = Some(xous_ipc::String::from_str(&string)) - }, - None => pl[index] = None, - } - } - - final_placeholders = Some(pl) - } - None => (), - } - - let mut spec = ManagedPromptWithTextResponse { - token: self.token, - prompt: xous_ipc::String::from_str(prompt), - fields: fields, - placeholders: final_placeholders, - }; - - // 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.first(), 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); - } - } + pub fn alert_builder(&self, prompt: &str) -> AlertModalBuilder { + AlertModalBuilder { + prompt: String::from(prompt), + validators: vec![], + placeholders: vec![], + fields_amt: 0, + modals: self } } diff --git a/services/modals/src/tests.rs b/services/modals/src/tests.rs index 10b83abda..602ae1618 100644 --- a/services/modals/src/tests.rs +++ b/services/modals/src/tests.rs @@ -81,9 +81,12 @@ pub(crate) fn spawn_test() { // 2. test the modal dialog box function log::info!("test text input"); - match modals.get_text("Test input", Some(test_validator), None, None) { + match modals + .alert_builder("Test input") + .field(None, Some(test_validator)) + .build() { Ok(text) => { - log::info!("Input: {}", text.content); + log::info!("Input: {}", text.content()[0].content); } _ => { log::error!("get_text failed"); @@ -99,7 +102,7 @@ pub(crate) fn spawn_test() { }); } -fn test_validator(input: TextEntryPayload, _opcode: u32) -> Option> { +fn test_validator(input: TextEntryPayload) -> Option> { let text_str = input.as_str(); match text_str.parse::() { Ok(_input_int) => None,