mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
add repl and status functionality to cram-console
This commit is contained in:
parent
d3ad1f11bf
commit
1d01521c38
14 changed files with 2853 additions and 38 deletions
|
|
@ -7,9 +7,10 @@ edition = "2021"
|
|||
|
||||
[dependencies]
|
||||
utralib = { version = "0.1.24", optional = true, default-features = false }
|
||||
xous-api-names = "0.9.60"
|
||||
xous-api-ticktimer = "0.9.58"
|
||||
xous-names = { package = "xous-api-names", version = "0.9.60" }
|
||||
ticktimer = { package = "xous-api-ticktimer", version = "0.9.58" }
|
||||
xous = "0.9.62"
|
||||
xous-ipc = "0.9.62"
|
||||
log-server = { package = "xous-api-log", version = "0.1.58" }
|
||||
log = "0.4.14"
|
||||
num-derive = { version = "0.3.3", default-features = false }
|
||||
|
|
@ -25,6 +26,7 @@ locales = { path = "../../locales" }
|
|||
usb-device-xous = { path = "../usb-device-xous" }
|
||||
cramium-hal = { path = "../../libs/cramium-hal", features = ["std"] }
|
||||
cram-hal-service = { path = "../cram-hal-service" }
|
||||
ime-plugin-shell = { path = "../ime-plugin-shell" }
|
||||
|
||||
[features]
|
||||
"cramium-fpga" = ["utralib/cramium-fpga", "xous-pl230/cramium-fpga"]
|
||||
|
|
@ -33,4 +35,5 @@ cram-hal-service = { path = "../cram-hal-service" }
|
|||
"pio-test" = ["xous-pio"]
|
||||
"pl230-test" = ["xous-pl230"]
|
||||
"hwtest" = []
|
||||
"pddb" = []
|
||||
default = []
|
||||
|
|
|
|||
29
services/cram-console/src/appmenu.rs
Normal file
29
services/cram-console/src/appmenu.rs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
use gam::*;
|
||||
use locales::t;
|
||||
use num_traits::*;
|
||||
|
||||
use crate::{app_autogen, StatusOpcode};
|
||||
|
||||
pub fn create_app_menu(status_conn: xous::CID) {
|
||||
let mut menu_items = Vec::<MenuItem>::new();
|
||||
|
||||
menu_items.push(MenuItem {
|
||||
name: xous_ipc::String::from_str(t!("appmenu.shellchat", locales::LANG)),
|
||||
action_conn: Some(status_conn),
|
||||
action_opcode: StatusOpcode::SwitchToShellchat.to_u32().unwrap(),
|
||||
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
|
||||
close_on_select: true,
|
||||
});
|
||||
|
||||
// insert the application menu items
|
||||
app_autogen::app_menu_items(&mut menu_items, status_conn);
|
||||
|
||||
menu_items.push(MenuItem {
|
||||
name: xous_ipc::String::from_str(t!("mainmenu.closemenu", locales::LANG)),
|
||||
action_conn: None,
|
||||
action_opcode: 0,
|
||||
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
|
||||
close_on_select: true,
|
||||
});
|
||||
menu_matic(menu_items, gam::APP_MENU_NAME, None);
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
const BALL_RADIUS: i16 = 10;
|
||||
const MOMENTUM_LIMIT: i32 = 8;
|
||||
const BORDER_WIDTH: i16 = 5;
|
||||
use cram_hal_service::trng;
|
||||
use graphics_server::{Circle, ClipObjectList, ClipObjectType, DrawStyle, PixelColor, Point, Rectangle};
|
||||
|
||||
pub struct Ball {
|
||||
|
|
@ -12,7 +13,7 @@ pub struct Ball {
|
|||
trng: trng::Trng,
|
||||
}
|
||||
impl Ball {
|
||||
pub fn new(xns: &xous_api_names::XousNames) -> Ball {
|
||||
pub fn new(xns: &xous_names::XousNames) -> Ball {
|
||||
let gfx = graphics_server::Gfx::new(xns).unwrap();
|
||||
gfx.draw_boot_logo().unwrap();
|
||||
|
||||
|
|
@ -21,7 +22,7 @@ impl Ball {
|
|||
ball.style = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1);
|
||||
let clip = Rectangle::new(Point::new(0, 0), screensize);
|
||||
gfx.draw_circle(ball).unwrap();
|
||||
let mut trng = trng::Trng::new(&xns).unwrap();
|
||||
let trng = trng::Trng::new(&xns).unwrap();
|
||||
let x = ((trng.get_u32().unwrap() / 2) as i32) % (MOMENTUM_LIMIT * 2) - MOMENTUM_LIMIT;
|
||||
let y = ((trng.get_u32().unwrap() / 2) as i32) % (MOMENTUM_LIMIT * 2) - MOMENTUM_LIMIT;
|
||||
Ball { gfx, screensize, ball, momentum: Point::new(x as i16, y as i16), clip, trng }
|
||||
|
|
|
|||
245
services/cram-console/src/cmds.rs
Normal file
245
services/cram-console/src/cmds.rs
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
use core::fmt::Write;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cram_hal_service::trng;
|
||||
#[cfg(feature = "shellperf")]
|
||||
use utralib::generated::*;
|
||||
use xous::MessageEnvelope;
|
||||
use xous_ipc::String;
|
||||
|
||||
/////////////////////////// Common items to all commands
|
||||
pub trait ShellCmdApi<'a> {
|
||||
// user implemented:
|
||||
// called to process the command with the remainder of the string attached
|
||||
fn process(
|
||||
&mut self,
|
||||
args: String<1024>,
|
||||
env: &mut CommonEnv,
|
||||
) -> Result<Option<String<1024>>, xous::Error>;
|
||||
// called to process incoming messages that may have been origniated by the most recently issued command
|
||||
fn callback(
|
||||
&mut self,
|
||||
msg: &MessageEnvelope,
|
||||
_env: &mut CommonEnv,
|
||||
) -> Result<Option<String<1024>>, xous::Error> {
|
||||
log::info!("received unhandled message {:?}", msg);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// created with cmd_api! macro
|
||||
// checks if the command matches the current verb in question
|
||||
fn matches(&self, verb: &str) -> bool;
|
||||
// returns my verb
|
||||
fn verb(&self) -> &'static str;
|
||||
}
|
||||
// the argument to this macro is the command verb
|
||||
macro_rules! cmd_api {
|
||||
($verb:expr) => {
|
||||
fn verb(&self) -> &'static str { stringify!($verb) }
|
||||
fn matches(&self, verb: &str) -> bool { if verb == stringify!($verb) { true } else { false } }
|
||||
};
|
||||
}
|
||||
|
||||
/////////////////////////// Command shell integration
|
||||
pub struct CommonEnv {
|
||||
ticktimer: ticktimer::Ticktimer,
|
||||
cb_registrations: HashMap<u32, String<256>>,
|
||||
trng: trng::Trng,
|
||||
#[allow(dead_code)]
|
||||
xns: xous_names::XousNames,
|
||||
}
|
||||
impl CommonEnv {
|
||||
#[allow(dead_code)]
|
||||
pub fn register_handler(&mut self, verb: String<256>) -> u32 {
|
||||
let mut key: u32;
|
||||
loop {
|
||||
key = self.trng.get_u32().unwrap();
|
||||
// reserve the bottom 1000 IDs for the main loop enums.
|
||||
if !self.cb_registrations.contains_key(&key) && (key > 1000) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.cb_registrations.insert(key, verb);
|
||||
key
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
To add a new command:
|
||||
0. ensure that the command implements the ShellCmdApi (above)
|
||||
1. mod/use the new command
|
||||
2. create an entry for the command's storage in the CmdEnv structure
|
||||
3. initialize the persistant storage here
|
||||
4. add it to the "commands" array in the dispatch() routine below
|
||||
|
||||
Side note: if your command doesn't require persistent storage, you could,
|
||||
technically, generate the command dynamically every time it's called. Echo
|
||||
demonstrates this.
|
||||
*/
|
||||
|
||||
///// 1. add your module here, and pull its namespace into the local crate
|
||||
mod echo;
|
||||
use echo::*;
|
||||
mod ver;
|
||||
use ver::*;
|
||||
mod trng_cmd;
|
||||
use trng_cmd::*;
|
||||
mod test;
|
||||
use test::*;
|
||||
#[cfg(feature = "pddb")]
|
||||
mod pddb_cmd;
|
||||
#[cfg(feature = "pddb")]
|
||||
use pddb_cmd::*;
|
||||
mod usb;
|
||||
use usb::*;
|
||||
|
||||
pub struct CmdEnv {
|
||||
common_env: CommonEnv,
|
||||
lastverb: String<256>,
|
||||
///// 2. declare storage for your command here.
|
||||
trng_cmd: TrngCmd,
|
||||
#[cfg(feature = "pddb")]
|
||||
pddb_cmd: PddbCmd,
|
||||
usb_cmd: Usb,
|
||||
}
|
||||
impl CmdEnv {
|
||||
pub fn new(xns: &xous_names::XousNames) -> CmdEnv {
|
||||
let ticktimer = ticktimer::Ticktimer::new().expect("Couldn't connect to Ticktimer");
|
||||
// _ prefix allows us to leave the `mut` here without creating a warning.
|
||||
// the `mut` option is needed for some features.
|
||||
let mut _common = CommonEnv {
|
||||
ticktimer,
|
||||
cb_registrations: HashMap::new(),
|
||||
trng: trng::Trng::new(&xns).unwrap(),
|
||||
xns: xous_names::XousNames::new().unwrap(),
|
||||
};
|
||||
CmdEnv {
|
||||
common_env: _common,
|
||||
lastverb: String::<256>::new(),
|
||||
///// 3. initialize your storage, by calling new()
|
||||
trng_cmd: {
|
||||
log::debug!("trng");
|
||||
TrngCmd::new()
|
||||
},
|
||||
#[cfg(feature = "pddb")]
|
||||
pddb_cmd: {
|
||||
log::debug!("pddb");
|
||||
PddbCmd::new(&xns)
|
||||
},
|
||||
usb_cmd: {
|
||||
log::debug!("usb");
|
||||
Usb::new()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dispatch(
|
||||
&mut self,
|
||||
maybe_cmdline: Option<&mut String<1024>>,
|
||||
maybe_callback: Option<&MessageEnvelope>,
|
||||
) -> Result<Option<String<1024>>, xous::Error> {
|
||||
let mut ret = String::<1024>::new();
|
||||
|
||||
let mut echo_cmd = Echo {}; // this command has no persistent storage, so we can "create" it every time we call dispatch (but it's a zero-cost absraction so this doesn't actually create any instructions)
|
||||
let mut ver_cmd = Ver {};
|
||||
let mut console_cmd = Test {};
|
||||
let commands: &mut [&mut dyn ShellCmdApi] = &mut [
|
||||
///// 4. add your command to this array, so that it can be looked up and dispatched
|
||||
&mut echo_cmd,
|
||||
&mut ver_cmd,
|
||||
&mut self.trng_cmd,
|
||||
&mut console_cmd,
|
||||
#[cfg(feature = "pddb")]
|
||||
&mut self.pddb_cmd,
|
||||
&mut self.usb_cmd,
|
||||
];
|
||||
|
||||
if let Some(cmdline) = maybe_cmdline {
|
||||
let maybe_verb = tokenize(cmdline);
|
||||
|
||||
let mut cmd_ret: Result<Option<String<1024>>, xous::Error> = Ok(None);
|
||||
if let Some(verb_string) = maybe_verb {
|
||||
let verb = verb_string.to_str();
|
||||
|
||||
// search through the list of commands linearly until one matches,
|
||||
// then run it.
|
||||
let mut match_found = false;
|
||||
for cmd in commands.iter_mut() {
|
||||
if cmd.matches(verb) {
|
||||
match_found = true;
|
||||
cmd_ret = cmd.process(*cmdline, &mut self.common_env);
|
||||
self.lastverb.clear();
|
||||
write!(self.lastverb, "{}", verb).expect("SHCH: couldn't record last verb");
|
||||
};
|
||||
}
|
||||
|
||||
// if none match, create a list of available commands
|
||||
if !match_found {
|
||||
let mut first = true;
|
||||
write!(ret, "Commands: ").unwrap();
|
||||
for cmd in commands.iter() {
|
||||
if !first {
|
||||
ret.append(", ")?;
|
||||
}
|
||||
ret.append(cmd.verb())?;
|
||||
first = false;
|
||||
}
|
||||
Ok(Some(ret))
|
||||
} else {
|
||||
cmd_ret
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
} else if let Some(callback) = maybe_callback {
|
||||
let mut cmd_ret: Result<Option<String<1024>>, xous::Error> = Ok(None);
|
||||
// first check and see if we have a callback registration; if not, just map to the last verb
|
||||
let verb = match self.common_env.cb_registrations.get(&(callback.body.id() as u32)) {
|
||||
Some(verb) => verb.to_str(),
|
||||
None => self.lastverb.to_str(),
|
||||
};
|
||||
// now dispatch
|
||||
let mut verbfound = false;
|
||||
for cmd in commands.iter_mut() {
|
||||
if cmd.matches(verb) {
|
||||
cmd_ret = cmd.callback(callback, &mut self.common_env);
|
||||
verbfound = true;
|
||||
break;
|
||||
};
|
||||
}
|
||||
if verbfound { cmd_ret } else { Ok(None) }
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// extract the first token, as delimited by spaces
|
||||
/// modifies the incoming line by removing the token and returning the remainder
|
||||
/// returns the found token
|
||||
/// note: we don't have split() because of nostd
|
||||
pub fn tokenize(line: &mut String<1024>) -> Option<String<1024>> {
|
||||
let mut token = String::<1024>::new();
|
||||
let mut retline = String::<1024>::new();
|
||||
|
||||
let lineiter = line.as_str().unwrap().chars();
|
||||
let mut foundspace = false;
|
||||
let mut foundrest = false;
|
||||
for ch in lineiter {
|
||||
if ch != ' ' && !foundspace {
|
||||
token.push(ch).unwrap();
|
||||
} else if foundspace && foundrest {
|
||||
retline.push(ch).unwrap();
|
||||
} else if foundspace && ch != ' ' {
|
||||
// handle case of multiple spaces in a row
|
||||
foundrest = true;
|
||||
retline.push(ch).unwrap();
|
||||
} else {
|
||||
foundspace = true;
|
||||
// consume the space
|
||||
}
|
||||
}
|
||||
line.clear();
|
||||
write!(line, "{}", retline.as_str().unwrap()).unwrap();
|
||||
if token.len() > 0 { Some(token) } else { None }
|
||||
}
|
||||
20
services/cram-console/src/cmds/echo.rs
Normal file
20
services/cram-console/src/cmds/echo.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
use xous_ipc::String;
|
||||
|
||||
use crate::{CommonEnv, ShellCmdApi};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Echo {}
|
||||
|
||||
impl<'a> ShellCmdApi<'a> for Echo {
|
||||
cmd_api!(echo);
|
||||
|
||||
// inserts boilerplate for command API
|
||||
|
||||
fn process(
|
||||
&mut self,
|
||||
args: String<1024>,
|
||||
_env: &mut CommonEnv,
|
||||
) -> Result<Option<String<1024>>, xous::Error> {
|
||||
Ok(Some(args))
|
||||
}
|
||||
}
|
||||
1604
services/cram-console/src/cmds/pddb_cmd.rs
Normal file
1604
services/cram-console/src/cmds/pddb_cmd.rs
Normal file
File diff suppressed because it is too large
Load diff
45
services/cram-console/src/cmds/test.rs
Normal file
45
services/cram-console/src/cmds/test.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
use xous_ipc::String;
|
||||
|
||||
use crate::{CommonEnv, ShellCmdApi};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Test {}
|
||||
|
||||
impl<'a> ShellCmdApi<'a> for Test {
|
||||
cmd_api!(test);
|
||||
|
||||
// inserts boilerplate for command API
|
||||
|
||||
fn process(
|
||||
&mut self,
|
||||
args: String<1024>,
|
||||
_env: &mut CommonEnv,
|
||||
) -> Result<Option<String<1024>>, xous::Error> {
|
||||
use core::fmt::Write;
|
||||
let mut ret = String::<1024>::new();
|
||||
let helpstring = "Test commands. See code for options.";
|
||||
|
||||
let mut tokens = args.as_str().unwrap().split(' ');
|
||||
|
||||
if let Some(sub_cmd) = tokens.next() {
|
||||
match sub_cmd {
|
||||
"ball" => {
|
||||
let _ = std::thread::spawn(move || {
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
let mut ball = crate::ball::Ball::new(&xns);
|
||||
log::info!("starting ball");
|
||||
loop {
|
||||
ball.update();
|
||||
}
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
write!(ret, "{}", helpstring).unwrap();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
write!(ret, "{}", helpstring).unwrap();
|
||||
}
|
||||
Ok(Some(ret))
|
||||
}
|
||||
}
|
||||
46
services/cram-console/src/cmds/trng_cmd.rs
Normal file
46
services/cram-console/src/cmds/trng_cmd.rs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
use xous_ipc::String;
|
||||
|
||||
use crate::{CommonEnv, ShellCmdApi};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TrngCmd {}
|
||||
impl TrngCmd {
|
||||
pub fn new() -> Self { TrngCmd {} }
|
||||
}
|
||||
|
||||
impl<'a> ShellCmdApi<'a> for TrngCmd {
|
||||
cmd_api!(trng);
|
||||
|
||||
fn process(
|
||||
&mut self,
|
||||
args: String<1024>,
|
||||
env: &mut CommonEnv,
|
||||
) -> Result<Option<String<1024>>, xous::Error> {
|
||||
use core::fmt::Write;
|
||||
let mut ret = String::<1024>::new();
|
||||
let helpstring = "trng [pump]";
|
||||
|
||||
let mut tokens = args.as_str().unwrap().split(' ');
|
||||
|
||||
if let Some(sub_cmd) = tokens.next() {
|
||||
match sub_cmd {
|
||||
"pump" => {
|
||||
const ROUNDS: usize = 16;
|
||||
for i in 0..ROUNDS {
|
||||
log::debug!("pump round {}", i);
|
||||
let mut buf: [u32; 1024] = [0; 1024];
|
||||
env.trng.fill_buf(&mut buf).unwrap();
|
||||
log::debug!("pump samples: {:x}, {:x}, {:x}", buf[0], buf[512], buf[1023]);
|
||||
}
|
||||
write!(ret, "Pumped {}x1k values out of the engine", ROUNDS).unwrap();
|
||||
}
|
||||
_ => {
|
||||
write!(ret, "{}", helpstring).unwrap();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
write!(ret, "{}", helpstring).unwrap();
|
||||
}
|
||||
Ok(Some(ret))
|
||||
}
|
||||
}
|
||||
155
services/cram-console/src/cmds/usb.rs
Normal file
155
services/cram-console/src/cmds/usb.rs
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
use std::fmt::Write;
|
||||
|
||||
use cram_hal_service::trng;
|
||||
use usb_device_xous::{UsbDeviceState, UsbDeviceType, UsbHid};
|
||||
|
||||
use crate::{CommonEnv, ShellCmdApi};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Usb {
|
||||
usb_dev: UsbHid,
|
||||
}
|
||||
impl Usb {
|
||||
pub fn new() -> Usb { Usb { usb_dev: UsbHid::new() } }
|
||||
}
|
||||
|
||||
impl<'a> ShellCmdApi<'a> for Usb {
|
||||
cmd_api!(usb);
|
||||
|
||||
// inserts boilerplate for command API
|
||||
|
||||
fn process(
|
||||
&mut self,
|
||||
args: xous_ipc::String<1024>,
|
||||
_env: &mut CommonEnv,
|
||||
) -> Result<Option<xous_ipc::String<1024>>, xous::Error> {
|
||||
let mut ret = xous_ipc::String::<1024>::new();
|
||||
#[cfg(not(feature = "mass-storage"))]
|
||||
let helpstring = "usb [hid] [fido] [debug] [send <string>] [status] [leds] [lock] [unlock] [kbdtest]";
|
||||
#[cfg(feature = "mass-storage")]
|
||||
let helpstring = "usb [hid] [fido] [ms] [debug] [send <string>] [status] [leds] [lock] [unlock] [kbdtest] [console] [noconsole]";
|
||||
|
||||
let mut tokens = args.as_str().unwrap().split(' ');
|
||||
|
||||
if let Some(sub_cmd) = tokens.next() {
|
||||
match sub_cmd {
|
||||
"hid" => {
|
||||
self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::FidoKbd).unwrap();
|
||||
write!(ret, "USB connected to HID (FIDO + keyboard) core").unwrap();
|
||||
}
|
||||
#[cfg(feature = "mass-storage")]
|
||||
"ms" => {
|
||||
self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::MassStorage).unwrap();
|
||||
write!(ret, "USB connected to mass storage core").unwrap();
|
||||
}
|
||||
"fido" => {
|
||||
self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::Fido).unwrap();
|
||||
write!(ret, "USB connected to FIDO-only core").unwrap();
|
||||
}
|
||||
"serial" => {
|
||||
self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::Serial).unwrap();
|
||||
write!(ret, "USB connected to serial core").unwrap();
|
||||
}
|
||||
"console" => {
|
||||
self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::Serial).unwrap();
|
||||
// this will enable input injection mode
|
||||
self.usb_dev.serial_console_input_injection();
|
||||
write!(ret, "USB console connected.").ok();
|
||||
}
|
||||
"noconsole" => {
|
||||
// this will disable any hooks (including the console input hook)
|
||||
self.usb_dev.serial_clear_input_hooks();
|
||||
write!(ret, "USB console disconnected.").ok();
|
||||
}
|
||||
"trng" => {
|
||||
self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::Serial).unwrap();
|
||||
let mode = if let Some(sub_cmd) = tokens.next() {
|
||||
match sub_cmd {
|
||||
"raw" => trng::api::TrngTestMode::Raw,
|
||||
_ => trng::api::TrngTestMode::None, // this is the "normal" mode of operation
|
||||
}
|
||||
} else {
|
||||
trng::api::TrngTestMode::None
|
||||
};
|
||||
self.usb_dev.serial_set_trng_mode(mode);
|
||||
write!(ret, "USB TRNG serial sending requested").ok();
|
||||
}
|
||||
"notrng" => {
|
||||
self.usb_dev.serial_clear_input_hooks();
|
||||
write!(ret, "USB TRNG serial sending should be stopped.").ok();
|
||||
}
|
||||
"send" => match self.usb_dev.get_current_core() {
|
||||
Ok(UsbDeviceType::FidoKbd) | Ok(UsbDeviceType::Serial) => {
|
||||
let mut val = String::new();
|
||||
join_tokens(&mut val, &mut tokens);
|
||||
match self.usb_dev.send_str(&val) {
|
||||
Ok(n) => write!(ret, "Sent {} chars", n).unwrap(),
|
||||
Err(_e) => write!(ret, "Can't send: are we connected to a host?").unwrap(),
|
||||
}
|
||||
}
|
||||
Ok(UsbDeviceType::Debug) => {
|
||||
write!(ret, "HID core not connected: please issue 'usb hid' first").unwrap();
|
||||
}
|
||||
_ => write!(ret, "Invalid response checking status").unwrap(),
|
||||
},
|
||||
"kbdtest" => {
|
||||
let mut test_str = String::new();
|
||||
for c in 0x20..0x7F {
|
||||
// includes a space as the first character
|
||||
// safety - the bounds are checked above in the loop to be the printable ASCII
|
||||
// character range.
|
||||
test_str.push(unsafe { char::from_u32_unchecked(c as u32) });
|
||||
}
|
||||
test_str.push('\n');
|
||||
match self.usb_dev.get_current_core() {
|
||||
Ok(UsbDeviceType::FidoKbd) => match self.usb_dev.send_str(&test_str) {
|
||||
Ok(n) => write!(ret, "Sent {} test string", n).unwrap(),
|
||||
Err(_e) => write!(ret, "Can't send: are we connected to a host?").unwrap(),
|
||||
},
|
||||
Ok(UsbDeviceType::Debug) => {
|
||||
write!(ret, "HID core not connected: please issue 'usb hid' first").unwrap();
|
||||
}
|
||||
_ => write!(ret, "Invalid response checking status").unwrap(),
|
||||
}
|
||||
}
|
||||
"status" => match self.usb_dev.get_current_core() {
|
||||
Ok(UsbDeviceType::Debug) => write!(ret, "Debug core connected").unwrap(),
|
||||
Ok(UsbDeviceType::FidoKbd) => match self.usb_dev.status() {
|
||||
UsbDeviceState::Configured => write!(ret, "HID core connected to host").unwrap(),
|
||||
UsbDeviceState::Suspend => write!(ret, "HID in suspend").unwrap(),
|
||||
_ => write!(ret, "HID not connected to USB host").unwrap(),
|
||||
},
|
||||
#[cfg(feature = "mass-storage")]
|
||||
Ok(UsbDeviceType::MassStorage) => write!(ret, "USB mass storage connected").unwrap(),
|
||||
_ => write!(ret, "Invalid response checking status").unwrap(),
|
||||
},
|
||||
"leds" => match self.usb_dev.get_current_core() {
|
||||
Ok(UsbDeviceType::FidoKbd) => match self.usb_dev.get_led_state() {
|
||||
Ok(leds) => write!(ret, "LEDs: {:?}", leds).unwrap(),
|
||||
_ => write!(ret, "Not connected to USB host or other error").unwrap(),
|
||||
},
|
||||
Ok(UsbDeviceType::Debug) => {
|
||||
write!(ret, "HID core not connected: please issue 'usb hid' first").unwrap();
|
||||
}
|
||||
_ => write!(ret, "Invalid response checking status").unwrap(),
|
||||
},
|
||||
_ => {
|
||||
write!(ret, "{}", helpstring).unwrap();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
write!(ret, "{}", helpstring).unwrap();
|
||||
}
|
||||
Ok(Some(ret))
|
||||
}
|
||||
}
|
||||
|
||||
fn join_tokens<'a>(buf: &mut String, tokens: impl Iterator<Item = &'a str>) {
|
||||
for (i, tok) in tokens.enumerate() {
|
||||
if i == 0 {
|
||||
write!(buf, "{}", tok).unwrap();
|
||||
} else {
|
||||
write!(buf, " {}", tok).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
44
services/cram-console/src/cmds/ver.rs
Normal file
44
services/cram-console/src/cmds/ver.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use xous_ipc::String;
|
||||
|
||||
use crate::{CommonEnv, ShellCmdApi};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Ver {}
|
||||
|
||||
impl<'a> ShellCmdApi<'a> for Ver {
|
||||
cmd_api!(ver);
|
||||
|
||||
// inserts boilerplate for command API
|
||||
|
||||
fn process(
|
||||
&mut self,
|
||||
args: String<1024>,
|
||||
env: &mut CommonEnv,
|
||||
) -> Result<Option<String<1024>>, xous::Error> {
|
||||
use core::fmt::Write;
|
||||
let mut ret = String::<1024>::new();
|
||||
let helpstring = "ver [xous]";
|
||||
|
||||
let mut tokens = args.as_str().unwrap().split(' ');
|
||||
|
||||
if let Some(sub_cmd) = tokens.next() {
|
||||
match sub_cmd {
|
||||
"xous" => {
|
||||
write!(ret, "Xous version: {}", env.ticktimer.get_version()).unwrap();
|
||||
log::info!(
|
||||
"{}VER.XOUS,{},{}",
|
||||
xous::BOOKEND_START,
|
||||
env.ticktimer.get_version(),
|
||||
xous::BOOKEND_END
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
write!(ret, "{}", helpstring).unwrap();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
write!(ret, "{}", helpstring).unwrap();
|
||||
}
|
||||
Ok(Some(ret))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +1,74 @@
|
|||
#[cfg(feature = "hwtest")]
|
||||
mod hwtest;
|
||||
|
||||
mod app_autogen;
|
||||
mod appmenu;
|
||||
mod ball;
|
||||
mod cmds;
|
||||
mod mainmenu;
|
||||
mod repl;
|
||||
mod shell;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc, Mutex,
|
||||
};
|
||||
use std::thread;
|
||||
|
||||
use cram_hal_service::trng;
|
||||
use cmds::*;
|
||||
use cram_hal_service::keyboard;
|
||||
use graphics_server::api::GlyphStyle;
|
||||
use graphics_server::Gid;
|
||||
use graphics_server::*;
|
||||
use locales::t;
|
||||
use num_traits::*;
|
||||
use xous::{msg_scalar_unpack, send_message, Message, CID};
|
||||
|
||||
const SERVER_NAME_STATUS_GID: &str = "_Status bar GID receiver_";
|
||||
const SERVER_NAME_STATUS: &str = "_Status_";
|
||||
|
||||
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||
pub(crate) enum StatusOpcode {
|
||||
/// indicates time for periodic update of the status bar
|
||||
Pump,
|
||||
|
||||
/// Raise the PDDB menu
|
||||
SubmenuPddb,
|
||||
/// Raise the App menu
|
||||
SubmenuApp,
|
||||
|
||||
/// Tells keyboard watching thread that a new keypress happened.
|
||||
Keypress,
|
||||
|
||||
/// Raise the Shellchat app
|
||||
SwitchToShellchat,
|
||||
/// Switch to an app
|
||||
SwitchToApp,
|
||||
|
||||
Quit,
|
||||
}
|
||||
|
||||
static mut CB_TO_MAIN_CONN: Option<CID> = None;
|
||||
|
||||
pub fn pump_thread(conn: usize, pump_run: Arc<AtomicBool>) {
|
||||
let ticktimer = ticktimer::Ticktimer::new().unwrap();
|
||||
loop {
|
||||
if pump_run.load(Ordering::Relaxed) {
|
||||
match send_message(
|
||||
conn as u32,
|
||||
Message::new_scalar(StatusOpcode::Pump.to_usize().unwrap(), 0, 0, 0, 0),
|
||||
) {
|
||||
Err(xous::Error::ServerNotFound) => break,
|
||||
Ok(xous::Result::Ok) => {}
|
||||
_ => panic!("unhandled error in status pump thread"),
|
||||
}
|
||||
}
|
||||
ticktimer.sleep_ms(1000).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
log_server::init_wait().unwrap();
|
||||
log::set_max_level(log::LevelFilter::Info);
|
||||
|
|
@ -40,7 +88,7 @@ fn main() {
|
|||
|
||||
#[cfg(feature = "early-ball")]
|
||||
thread::spawn(move || {
|
||||
let xns = xous_api_names::XousNames::new().unwrap();
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
let mut ball = ball::Ball::new(&xns);
|
||||
log::info!("starting ball");
|
||||
loop {
|
||||
|
|
@ -48,10 +96,8 @@ fn main() {
|
|||
}
|
||||
});
|
||||
|
||||
let tt = xous_api_ticktimer::Ticktimer::new().unwrap();
|
||||
let xns = xous_api_names::XousNames::new().unwrap();
|
||||
|
||||
let usb = usb_device_xous::UsbHid::new();
|
||||
let tt = ticktimer::Ticktimer::new().unwrap();
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
|
||||
let status_gam_getter =
|
||||
xns.register_name(SERVER_NAME_STATUS_GID, Some(1)).expect("can't register server");
|
||||
|
|
@ -81,10 +127,34 @@ fn main() {
|
|||
// create a connection for callback hooks
|
||||
let cb_cid = xous::connect(status_sid).unwrap();
|
||||
|
||||
// --------------------------- graphical loop timing
|
||||
let mut stats_phase: usize = 0;
|
||||
let mut secnotes_force_redraw = false;
|
||||
let secnotes_interval = 4;
|
||||
|
||||
let gam = gam::Gam::new(&xns).expect("|status: can't connect to GAM");
|
||||
// screensize is controlled by the GAM, it's set in main.rs near the top
|
||||
let screensize = gam.get_canvas_bounds(status_gid).expect("|status: Couldn't get canvas size");
|
||||
|
||||
// ------------------ render initial graphical display, so we don't seem broken on boot
|
||||
const CPU_BAR_WIDTH: i16 = 46;
|
||||
const CPU_BAR_OFFSET: i16 = 8;
|
||||
let time_rect = Rectangle::new_with_style(
|
||||
Point::new(0, 0),
|
||||
Point::new(screensize.x / 2 - CPU_BAR_WIDTH / 2 - 1 + CPU_BAR_OFFSET, screensize.y / 2 - 1),
|
||||
DrawStyle::new(PixelColor::Light, PixelColor::Light, 0),
|
||||
);
|
||||
// build uptime text view: left half of status bar
|
||||
let mut uptime_tv =
|
||||
TextView::new(status_gid, TextBounds::GrowableFromTl(time_rect.tl(), time_rect.width() as _));
|
||||
uptime_tv.untrusted = false;
|
||||
uptime_tv.style = GlyphStyle::Tall;
|
||||
uptime_tv.draw_border = false;
|
||||
uptime_tv.margin = Point::new(3, 0);
|
||||
write!(uptime_tv, "{}", t!("secnote.startup", locales::LANG))
|
||||
.expect("|status: couldn't init uptime text");
|
||||
gam.post_textview(&mut uptime_tv).expect("|status: can't draw battery stats");
|
||||
|
||||
// build security status textview
|
||||
let mut security_tv = TextView::new(
|
||||
status_gid,
|
||||
|
|
@ -93,7 +163,6 @@ fn main() {
|
|||
Point::new(screensize.x, screensize.y),
|
||||
)),
|
||||
);
|
||||
|
||||
security_tv.style = GlyphStyle::Tall; // was: Regular, but not available on this target
|
||||
security_tv.draw_border = false;
|
||||
security_tv.margin = Point::new(0, 0);
|
||||
|
|
@ -113,37 +182,187 @@ fn main() {
|
|||
.unwrap();
|
||||
gam.redraw().unwrap(); // initial boot redraw
|
||||
|
||||
// ------------------ start a 'gutter' thread to handle incoming events while we go through the
|
||||
// boot/autoupdate process
|
||||
let gutter = thread::spawn({
|
||||
let gutter_sid = status_sid.clone();
|
||||
// ------------------------ measure current security state and adjust messaging
|
||||
let sec_notes = Arc::new(Mutex::new(HashMap::<String, String>::new()));
|
||||
let mut last_sec_note_index = 0;
|
||||
let mut last_sec_note_size = 0;
|
||||
|
||||
// ---------------------------- build menus
|
||||
// used to hide time when the PDDB is not mounted
|
||||
#[cfg(feature = "pddb")]
|
||||
let pddb_poller = pddb::PddbMountPoller::new();
|
||||
#[cfg(not(feature = "pddb"))]
|
||||
gam.allow_mainmenu().ok();
|
||||
|
||||
// these menus stake a claim on some security-sensitive connections; occupy them upstream of trying to do
|
||||
// an update
|
||||
log::debug!("starting main menu thread");
|
||||
let main_menu_sid = xous::create_server().unwrap();
|
||||
let status_cid = xous::connect(status_sid).unwrap();
|
||||
let _menu_manager = mainmenu::create_main_menu(main_menu_sid, status_cid);
|
||||
appmenu::create_app_menu(xous::connect(status_sid).unwrap());
|
||||
let kbd = Arc::new(Mutex::new(keyboard::Keyboard::new(&xns).unwrap()));
|
||||
|
||||
// ---------------------------- Background processes that claim contexts
|
||||
// must be upstream of the update check, because we need to occupy the keyboard
|
||||
// server slot to prevent e.g. a keyboard logger from taking our passwords!
|
||||
kbd.lock()
|
||||
.unwrap()
|
||||
.register_observer(SERVER_NAME_STATUS, StatusOpcode::Keypress.to_u32().unwrap() as usize);
|
||||
|
||||
let _modals = modals::Modals::new(&xns).unwrap();
|
||||
|
||||
shell::start_shell();
|
||||
|
||||
let pump_run = Arc::new(AtomicBool::new(false));
|
||||
let pump_conn = xous::connect(status_sid).unwrap();
|
||||
let _ = thread::spawn({
|
||||
let pump_run = pump_run.clone();
|
||||
move || {
|
||||
loop {
|
||||
let msg = xous::receive_message(gutter_sid).unwrap();
|
||||
let opcode: Option<StatusOpcode> = FromPrimitive::from_usize(msg.body.id());
|
||||
log::info!("Guttering {:?}", opcode);
|
||||
match opcode {
|
||||
Some(StatusOpcode::Quit) => {
|
||||
xous::return_scalar(msg.sender, 1).ok();
|
||||
break;
|
||||
}
|
||||
_ => (), // ignore everything else.
|
||||
}
|
||||
}
|
||||
pump_thread(pump_conn as _, pump_run);
|
||||
}
|
||||
});
|
||||
|
||||
let modals = modals::Modals::new(&xns).unwrap();
|
||||
xous::send_message(
|
||||
cb_cid,
|
||||
xous::Message::new_blocking_scalar(StatusOpcode::Quit.to_usize().unwrap(), 0, 0, 0, 0),
|
||||
)
|
||||
.expect("couldn't exit the gutter server");
|
||||
gutter.join().expect("status boot gutter server did not exit gracefully");
|
||||
|
||||
let mut ball = ball::Ball::new(&xns);
|
||||
log::info!("starting ball");
|
||||
pump_run.store(true, Ordering::Relaxed); // start status thread updating
|
||||
loop {
|
||||
ball.update();
|
||||
let msg = xous::receive_message(status_sid).unwrap();
|
||||
let opcode: Option<StatusOpcode> = FromPrimitive::from_usize(msg.body.id());
|
||||
log::debug!("{:?}", opcode);
|
||||
match opcode {
|
||||
Some(StatusOpcode::Pump) => {
|
||||
let elapsed_time = tt.elapsed_ms();
|
||||
{
|
||||
// update the time field
|
||||
// have to clear the entire rectangle area, because the text has a variable width and
|
||||
// dirty text will remain if the text is shortened
|
||||
gam.draw_rectangle(status_gid, time_rect).ok();
|
||||
uptime_tv.clear_str();
|
||||
|
||||
write!(
|
||||
&mut uptime_tv,
|
||||
" {}{}:{:02}:{:02}",
|
||||
t!("stats.uptime", locales::LANG),
|
||||
(elapsed_time / 3_600_000),
|
||||
(elapsed_time / 60_000) % 60,
|
||||
(elapsed_time / 1000) % 60,
|
||||
)
|
||||
.expect("|status: can't write string");
|
||||
gam.post_textview(&mut uptime_tv).expect("|status: can't draw uptime");
|
||||
if let Some(bounds) = uptime_tv.bounds_computed {
|
||||
if bounds.height() as i16 > screensize.y / 2 + 1 {
|
||||
// the clipping rectangle limits the bounds to the overall height of the status
|
||||
// area, so the overlap between status and secnotes
|
||||
// must be managed within this server
|
||||
log::info!(
|
||||
"Status text overstepped its intended bound. Forcing secnotes redraw."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// update the security status, if any
|
||||
if secnotes_force_redraw
|
||||
|| sec_notes.lock().unwrap().len() != last_sec_note_size
|
||||
|| ((stats_phase % secnotes_interval) == 0)
|
||||
{
|
||||
log::debug!("updating lock state text");
|
||||
if sec_notes.lock().unwrap().len() != last_sec_note_size {
|
||||
last_sec_note_size = sec_notes.lock().unwrap().len();
|
||||
if last_sec_note_size > 0 {
|
||||
last_sec_note_index = last_sec_note_size - 1;
|
||||
}
|
||||
}
|
||||
|
||||
security_tv.clear_str();
|
||||
if last_sec_note_size > 0 {
|
||||
for (index, v) in sec_notes.lock().unwrap().values().enumerate() {
|
||||
if index == last_sec_note_index {
|
||||
write!(&mut security_tv, "{}", v.as_str()).unwrap();
|
||||
last_sec_note_index = (last_sec_note_index + 1) % last_sec_note_size;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
write!(&mut security_tv, "{}", t!("secnote.allclear", locales::LANG)).unwrap();
|
||||
}
|
||||
|
||||
secnotes_force_redraw = false;
|
||||
gam.post_textview(&mut security_tv).unwrap();
|
||||
gam.draw_line(
|
||||
status_gid,
|
||||
Line::new_with_style(
|
||||
Point::new(0, screensize.y),
|
||||
screensize,
|
||||
DrawStyle::new(PixelColor::Light, PixelColor::Light, 1),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
log::trace!("status redraw## update");
|
||||
gam.redraw().expect("|status: couldn't redraw");
|
||||
|
||||
stats_phase = stats_phase.wrapping_add(1);
|
||||
}
|
||||
Some(StatusOpcode::SubmenuPddb) => {
|
||||
tt.sleep_ms(100).ok(); // yield for a moment to allow the previous menu to close
|
||||
gam.raise_menu(gam::PDDB_MENU_NAME).expect("couldn't raise PDDB submenu");
|
||||
}
|
||||
Some(StatusOpcode::SubmenuApp) => {
|
||||
tt.sleep_ms(100).ok(); // yield for a moment to allow the previous menu to close
|
||||
gam.raise_menu(gam::APP_MENU_NAME).expect("couldn't raise App submenu");
|
||||
}
|
||||
Some(StatusOpcode::SwitchToShellchat) => {
|
||||
tt.sleep_ms(100).ok();
|
||||
sec_notes.lock().unwrap().remove(&"current_app".to_string());
|
||||
sec_notes
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert("current_app".to_string(), format!("Running: Shellchat").to_string());
|
||||
gam.switch_to_app(gam::APP_NAME_SHELLCHAT, security_tv.token.unwrap())
|
||||
.expect("couldn't raise shellchat");
|
||||
secnotes_force_redraw = true;
|
||||
send_message(cb_cid, Message::new_scalar(StatusOpcode::Pump.to_usize().unwrap(), 0, 0, 0, 0))
|
||||
.expect("couldn't trigger status update");
|
||||
}
|
||||
Some(StatusOpcode::SwitchToApp) => msg_scalar_unpack!(msg, index, _, _, _, {
|
||||
tt.sleep_ms(100).ok();
|
||||
let app_name = app_autogen::app_index_to_name(index).expect("app index not found");
|
||||
app_autogen::app_dispatch(&gam, security_tv.token.unwrap(), index)
|
||||
.expect("cannot switch to app");
|
||||
sec_notes.lock().unwrap().remove(&"current_app".to_string());
|
||||
sec_notes
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert("current_app".to_string(), format!("Running: {}", app_name).to_string());
|
||||
secnotes_force_redraw = true;
|
||||
send_message(cb_cid, Message::new_scalar(StatusOpcode::Pump.to_usize().unwrap(), 0, 0, 0, 0))
|
||||
.expect("couldn't trigger status update");
|
||||
}),
|
||||
Some(StatusOpcode::Keypress) => {
|
||||
// placeholder
|
||||
}
|
||||
|
||||
Some(StatusOpcode::Quit) => {
|
||||
xous::return_scalar(msg.sender, 1).ok();
|
||||
break;
|
||||
}
|
||||
None => {
|
||||
log::error!("|status: received unknown Opcode");
|
||||
}
|
||||
}
|
||||
}
|
||||
log::trace!("status thread exit, destroying servers");
|
||||
unsafe {
|
||||
if let Some(cb) = CB_TO_MAIN_CONN {
|
||||
xous::disconnect(cb).unwrap();
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
xous::disconnect(pump_conn).unwrap();
|
||||
}
|
||||
xns.unregister_server(status_sid).unwrap();
|
||||
xous::destroy_server(status_sid).unwrap();
|
||||
log::trace!("status thread quitting");
|
||||
xous::terminate_process(0)
|
||||
}
|
||||
|
|
|
|||
38
services/cram-console/src/mainmenu.rs
Normal file
38
services/cram-console/src/mainmenu.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
use gam::*;
|
||||
use locales::t;
|
||||
use num_traits::*;
|
||||
use xous_ipc::String;
|
||||
|
||||
use crate::StatusOpcode;
|
||||
|
||||
#[allow(unused_variables)] // quiets a warning about unused com that is emitted in tts config. Would be nice to make this more targeted...
|
||||
pub fn create_main_menu(menu_management_sid: xous::SID, status_conn: xous::CID) -> MenuMatic {
|
||||
let mut menuitems = Vec::<MenuItem>::new();
|
||||
|
||||
menuitems.push(MenuItem {
|
||||
name: String::from_str(t!("mainmenu.app", locales::LANG)),
|
||||
action_conn: Some(status_conn),
|
||||
action_opcode: StatusOpcode::SubmenuApp.to_u32().unwrap(),
|
||||
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
|
||||
close_on_select: true,
|
||||
});
|
||||
|
||||
#[cfg(feature = "pddb")]
|
||||
menuitems.push(MenuItem {
|
||||
name: String::from_str(t!("mainmenu.pddb", locales::LANG)),
|
||||
action_conn: Some(status_conn),
|
||||
action_opcode: StatusOpcode::SubmenuPddb.to_u32().unwrap(),
|
||||
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
|
||||
close_on_select: true,
|
||||
});
|
||||
|
||||
menuitems.push(MenuItem {
|
||||
name: String::from_str(t!("mainmenu.closemenu", locales::LANG)),
|
||||
action_conn: None,
|
||||
action_opcode: 0,
|
||||
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
|
||||
close_on_select: true,
|
||||
});
|
||||
|
||||
menu_matic(menuitems, MAIN_MENU_NAME, Some(menu_management_sid)).unwrap()
|
||||
}
|
||||
251
services/cram-console/src/repl.rs
Normal file
251
services/cram-console/src/repl.rs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
use core::fmt::Write;
|
||||
|
||||
use gam::UxRegistration;
|
||||
use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView};
|
||||
use num_traits::*;
|
||||
use xous::MessageEnvelope;
|
||||
|
||||
use crate::CmdEnv;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct History {
|
||||
// the history record
|
||||
pub text: String,
|
||||
// if true, this was input from the user; if false, it's a response from the shell
|
||||
pub is_input: bool,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) struct Repl {
|
||||
// optional structures that indicate new input to the Repl loop per iteration
|
||||
// an input string
|
||||
input: Option<String>,
|
||||
// messages from other servers
|
||||
msg: Option<MessageEnvelope>,
|
||||
|
||||
// record our input history
|
||||
history: Vec<History>,
|
||||
history_len: usize,
|
||||
content: Gid,
|
||||
gam: gam::Gam,
|
||||
|
||||
// variables that define our graphical attributes
|
||||
screensize: Point,
|
||||
bubble_width: u16,
|
||||
margin: Point, // margin to edge of canvas
|
||||
bubble_margin: Point, // margin of text in bubbles
|
||||
bubble_radius: u16,
|
||||
bubble_space: i16, // spacing between text bubbles
|
||||
|
||||
// command environment
|
||||
env: CmdEnv,
|
||||
|
||||
// our security token for making changes to our record on the GAM
|
||||
token: [u32; 4],
|
||||
}
|
||||
impl Repl {
|
||||
pub(crate) fn new(xns: &xous_names::XousNames, sid: xous::SID) -> Self {
|
||||
let gam = gam::Gam::new(xns).expect("can't connect to GAM");
|
||||
|
||||
let token = gam
|
||||
.register_ux(UxRegistration {
|
||||
app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_SHELLCHAT),
|
||||
ux_type: gam::UxType::Chat,
|
||||
predictor: Some(xous_ipc::String::<64>::from_str(
|
||||
ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL,
|
||||
)),
|
||||
listener: sid.to_array(), /* note disclosure of our SID to the GAM -- the secret is now
|
||||
* shared with the GAM! */
|
||||
redraw_id: ShellOpcode::Redraw.to_u32().unwrap(),
|
||||
gotinput_id: Some(ShellOpcode::Line.to_u32().unwrap()),
|
||||
audioframe_id: None,
|
||||
rawkeys_id: None,
|
||||
focuschange_id: Some(ShellOpcode::ChangeFocus.to_u32().unwrap()),
|
||||
})
|
||||
.expect("couldn't register Ux context for shellchat");
|
||||
|
||||
let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas");
|
||||
log::trace!("content canvas {:?}", content);
|
||||
let screensize = gam.get_canvas_bounds(content).expect("couldn't get dimensions of content canvas");
|
||||
log::trace!("size {:?}", screensize);
|
||||
Repl {
|
||||
input: None,
|
||||
msg: None,
|
||||
history: Vec::new(),
|
||||
history_len: 10,
|
||||
content,
|
||||
gam,
|
||||
screensize,
|
||||
bubble_width: ((screensize.x / 5) * 4) as u16, // 80% width for the text bubbles
|
||||
margin: Point::new(4, 4),
|
||||
bubble_margin: Point::new(4, 4),
|
||||
bubble_radius: 4,
|
||||
bubble_space: 4,
|
||||
env: CmdEnv::new(xns),
|
||||
token: token.unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
/// accept a new input string
|
||||
pub(crate) fn input(&mut self, line: &str) -> Result<(), xous::Error> {
|
||||
self.input = Some(String::from(line));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn msg(&mut self, message: MessageEnvelope) { self.msg = Some(message); }
|
||||
|
||||
pub(crate) fn circular_push(&mut self, item: History) {
|
||||
if self.history.len() >= self.history_len {
|
||||
self.history.remove(0);
|
||||
}
|
||||
self.history.push(item);
|
||||
}
|
||||
|
||||
/// update the loop, in response to various inputs
|
||||
pub(crate) fn update(&mut self, was_callback: bool, init_done: bool) -> Result<(), xous::Error> {
|
||||
let debug1 = false;
|
||||
// if we had an input string, do something
|
||||
if let Some(local) = &self.input {
|
||||
let input_history = History { text: local.to_string(), is_input: true };
|
||||
self.circular_push(input_history);
|
||||
}
|
||||
|
||||
// AT THIS POINT: if we have other inputs, update accordingly
|
||||
// other inputs might be, for example, events that came in from other servers that would
|
||||
// side effect our commands
|
||||
|
||||
// redraw UI once upon accepting all input
|
||||
if !was_callback {
|
||||
// don't need to redraw on a callback, save some cycles
|
||||
self.redraw(init_done).expect("can't redraw");
|
||||
}
|
||||
|
||||
let mut dirty = true;
|
||||
// take the input and pass it on to the various command parsers, and attach result
|
||||
if let Some(local) = &self.input {
|
||||
log::trace!("processing line: {}", local);
|
||||
if let Some(res) = self
|
||||
.env
|
||||
.dispatch(Some(&mut xous_ipc::String::<1024>::from_str(&local)), None)
|
||||
.expect("command dispatch failed")
|
||||
{
|
||||
let output_history =
|
||||
History { text: String::from(res.as_str().unwrap_or("UTF-8 Error")), is_input: false };
|
||||
self.circular_push(output_history);
|
||||
} else {
|
||||
dirty = false;
|
||||
}
|
||||
} else if let Some(msg) = &self.msg {
|
||||
log::trace!("processing callback msg: {:?}", msg);
|
||||
if let Some(res) = self.env.dispatch(None, Some(msg)).expect("callback failed") {
|
||||
let output_history =
|
||||
History { text: String::from(res.as_str().unwrap_or("UTF-8 Error")), is_input: false };
|
||||
self.circular_push(output_history);
|
||||
} else {
|
||||
dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
// clear all the inputs to the loop, so we don't process them twice
|
||||
self.input = None;
|
||||
self.msg = None;
|
||||
// redraw UI now that we've responded
|
||||
if dirty {
|
||||
self.redraw(init_done).expect("can't redraw");
|
||||
}
|
||||
|
||||
if debug1 {
|
||||
for h in self.history.iter() {
|
||||
log::info!("command history is_input: {}, text:{}", h.is_input, h.text);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn clear_area(&self) {
|
||||
self.gam
|
||||
.draw_rectangle(
|
||||
self.content,
|
||||
Rectangle::new_with_style(
|
||||
Point::new(0, 0),
|
||||
self.screensize,
|
||||
DrawStyle { fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0 },
|
||||
),
|
||||
)
|
||||
.expect("can't clear content area");
|
||||
}
|
||||
|
||||
pub(crate) fn redraw(&mut self, _init_done: bool) -> Result<(), xous::Error> {
|
||||
log::trace!("going into redraw");
|
||||
self.clear_area();
|
||||
|
||||
// this defines the bottom border of the text bubbles as they stack up wards
|
||||
let mut bubble_baseline = self.screensize.y - self.margin.y;
|
||||
|
||||
log::trace!("drawing chat history");
|
||||
// iterator returns from oldest to newest
|
||||
// .rev() iterator is from newest to oldest
|
||||
for h in self.history.iter().rev() {
|
||||
let mut bubble_tv = if h.is_input {
|
||||
TextView::new(
|
||||
self.content,
|
||||
TextBounds::GrowableFromBr(
|
||||
Point::new(self.screensize.x - self.margin.x, bubble_baseline),
|
||||
self.bubble_width,
|
||||
),
|
||||
)
|
||||
} else {
|
||||
TextView::new(
|
||||
self.content,
|
||||
TextBounds::GrowableFromBl(Point::new(self.margin.x, bubble_baseline), self.bubble_width),
|
||||
)
|
||||
};
|
||||
if h.is_input {
|
||||
bubble_tv.border_width = 1;
|
||||
} else {
|
||||
bubble_tv.border_width = 2;
|
||||
}
|
||||
bubble_tv.draw_border = true;
|
||||
bubble_tv.clear_area = true;
|
||||
bubble_tv.rounded_border = Some(self.bubble_radius);
|
||||
bubble_tv.style = gam::SYSTEM_STYLE;
|
||||
bubble_tv.margin = self.bubble_margin;
|
||||
bubble_tv.ellipsis = false;
|
||||
bubble_tv.insertion = None;
|
||||
write!(bubble_tv.text, "{}", h.text.as_str()).expect("couldn't write history text to TextView");
|
||||
log::trace!("posting {}", bubble_tv.text);
|
||||
self.gam.post_textview(&mut bubble_tv).expect("couldn't render bubble textview");
|
||||
|
||||
if let Some(bounds) = bubble_tv.bounds_computed {
|
||||
// we only subtract 1x of the margin because the bounds were computed from a "bottom right"
|
||||
// that already counted the margin once.
|
||||
bubble_baseline -= (bounds.br.y - bounds.tl.y) + self.bubble_space + self.bubble_margin.y;
|
||||
if bubble_baseline <= 0 {
|
||||
// don't draw history that overflows the top of the screen
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break; // we get None on the bounds computed if the text view fell off the top of the screen
|
||||
}
|
||||
}
|
||||
log::trace!("shellchat redraw##");
|
||||
self.gam.redraw().expect("couldn't redraw screen");
|
||||
// self.gam.request_ime_redraw().expect("couldn't redraw the IME area");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
////////////////// local message passing from Ux Callback
|
||||
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||
enum ShellOpcode {
|
||||
/// a line of text has arrived
|
||||
Line = 0, // make sure we occupy opcodes with discriminants < 1000, as the rest are used for callbacks
|
||||
/// redraw our UI
|
||||
Redraw,
|
||||
/// change focus
|
||||
ChangeFocus,
|
||||
/// exit the application
|
||||
Quit,
|
||||
}
|
||||
115
services/cram-console/src/shell.rs
Normal file
115
services/cram-console/src/shell.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc};
|
||||
|
||||
use xous_ipc::Buffer;
|
||||
|
||||
pub fn start_shell() {
|
||||
std::thread::spawn(move || {
|
||||
shell();
|
||||
});
|
||||
}
|
||||
|
||||
////////////////// local message passing from Ux Callback
|
||||
use num_traits::*;
|
||||
|
||||
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||
enum ShellOpcode {
|
||||
/// a line of text has arrived
|
||||
Line = 0, // make sure we occupy opcodes with discriminants < 1000, as the rest are used for callbacks
|
||||
/// redraw our UI
|
||||
Redraw,
|
||||
/// change focus
|
||||
ChangeFocus,
|
||||
/// exit the application
|
||||
Quit,
|
||||
}
|
||||
|
||||
pub(crate) const SERVER_NAME_SHELLCHAT: &str = "_Shell chat application_"; // used internally by xous-names
|
||||
|
||||
fn shell() {
|
||||
let xns = xous_names::XousNames::new().unwrap();
|
||||
// unlimited connections allowed, this is a user app and it's up to the app to decide its policy
|
||||
let shch_sid = xns.register_name(SERVER_NAME_SHELLCHAT, None).expect("can't register server");
|
||||
|
||||
let mut repl = crate::repl::Repl::new(&xns, shch_sid);
|
||||
let mut update_repl = false;
|
||||
let mut was_callback = false;
|
||||
|
||||
let mut allow_redraw = true;
|
||||
let pddb_init_done = Arc::new(AtomicBool::new(false));
|
||||
repl.redraw(pddb_init_done.load(Ordering::SeqCst)).ok();
|
||||
|
||||
// until PDDB is ready
|
||||
#[cfg(feature = "pddb")]
|
||||
thread::spawn({
|
||||
let pddb_init_done = pddb_init_done.clone();
|
||||
let main_conn = xous::connect(shch_sid).unwrap();
|
||||
move || {
|
||||
let pddb = pddb::Pddb::new();
|
||||
pddb.mount_attempted_blocking();
|
||||
pddb_init_done.store(true, Ordering::SeqCst);
|
||||
xous::send_message(
|
||||
main_conn,
|
||||
xous::Message::new_scalar(ShellOpcode::Redraw.to_usize().unwrap(), 0, 0, 0, 0),
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
});
|
||||
|
||||
loop {
|
||||
let msg = xous::receive_message(shch_sid).unwrap();
|
||||
let shell_op: Option<ShellOpcode> = FromPrimitive::from_usize(msg.body.id());
|
||||
log::debug!("Shellchat got message {:?}", msg);
|
||||
match shell_op {
|
||||
Some(ShellOpcode::Line) => {
|
||||
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
|
||||
let s = buffer.as_flat::<xous_ipc::String<4000>, _>().unwrap();
|
||||
log::trace!("shell got input line: {}", s.as_str());
|
||||
#[cfg(feature = "tts")]
|
||||
{
|
||||
let mut input = t!("shellchat.input-tts", locales::LANG).to_string();
|
||||
input.push_str(s.as_str());
|
||||
tts.tts_simple(&input).unwrap();
|
||||
}
|
||||
repl.input(s.as_str()).expect("REPL couldn't accept input string");
|
||||
update_repl = true; // set a flag, instead of calling here, so message can drop and calling server is released
|
||||
was_callback = false;
|
||||
}
|
||||
Some(ShellOpcode::Redraw) => {
|
||||
if allow_redraw {
|
||||
repl.redraw(pddb_init_done.load(Ordering::SeqCst)).expect("REPL couldn't redraw");
|
||||
}
|
||||
}
|
||||
Some(ShellOpcode::ChangeFocus) => xous::msg_scalar_unpack!(msg, new_state_code, _, _, _, {
|
||||
let new_state = gam::FocusState::convert_focus_change(new_state_code);
|
||||
match new_state {
|
||||
gam::FocusState::Background => {
|
||||
allow_redraw = false;
|
||||
}
|
||||
gam::FocusState::Foreground => {
|
||||
allow_redraw = true;
|
||||
}
|
||||
}
|
||||
}),
|
||||
Some(ShellOpcode::Quit) => {
|
||||
log::error!("got Quit");
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
log::trace!("got unknown message, treating as callback");
|
||||
repl.msg(msg);
|
||||
update_repl = true;
|
||||
was_callback = true;
|
||||
}
|
||||
}
|
||||
if update_repl {
|
||||
repl.update(was_callback, pddb_init_done.load(Ordering::SeqCst))
|
||||
.expect("REPL had problems updating");
|
||||
update_repl = false;
|
||||
}
|
||||
}
|
||||
|
||||
// clean up our program
|
||||
log::error!("shell loop exit, destroying servers");
|
||||
xns.unregister_server(shch_sid).unwrap();
|
||||
xous::destroy_server(shch_sid).unwrap();
|
||||
}
|
||||
Loading…
Reference in a new issue