mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
helps to add the code for the new service
This commit is contained in:
parent
60d6d08933
commit
e48c472b32
5 changed files with 480 additions and 0 deletions
25
services/modals/Cargo.toml
Normal file
25
services/modals/Cargo.toml
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
[package]
|
||||
name = "modals"
|
||||
version = "0.1.0"
|
||||
authors = ["bunnie <bunnie@kosagi.com>"]
|
||||
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 = []
|
||||
7
services/modals/locales/i18n.json
Normal file
7
services/modals/locales/i18n.json
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"modals.invalid_text": {
|
||||
"en": "Invalid input",
|
||||
"zh": "输入无效",
|
||||
"en-audio": "Invalid input"
|
||||
}
|
||||
}
|
||||
85
services/modals/src/api.rs
Normal file
85
services/modals/src/api.rs
Normal file
|
|
@ -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<ItemName>; 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,
|
||||
}
|
||||
94
services/modals/src/lib.rs
Normal file
94
services/modals/src/lib.rs
Normal file
|
|
@ -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<Self, xous::Error> {
|
||||
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<fn(TextEntryPayload, u32) -> Option<xous_ipc::String::<256>> >,
|
||||
maybe_validator_op: Option<u32>,
|
||||
) -> Result<TextEntryPayload, xous::Error> {
|
||||
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::<Validation, _>().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::<TextEntryPayload, _>() {
|
||||
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
|
||||
}
|
||||
}
|
||||
269
services/modals/src/main.rs
Normal file
269
services/modals/src/main.rs
Normal file
|
|
@ -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<ItemName>; 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::<gam::modal::TextEntryPayload, _>().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::<Option<xous_ipc::String::<256>>, _>().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::<ManagedPromptWithTextResponse, _>().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)
|
||||
}
|
||||
Loading…
Reference in a new issue