From 53f35f992898f276b17967117065b7bb6b965fe0 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 26 Jul 2021 00:51:22 +0800 Subject: [PATCH] intermediate work toward getting the password box going lots of changes, maybe finally getting out of the UX rathole now that basic localization is in place --- Cargo.lock | 101 +++++++- kernel/Cargo.lock | 1 + services/gam/Cargo.toml | 1 + services/gam/src/layouts.rs | 2 +- services/gam/src/main.rs | 57 ++++- services/gam/src/modal.rs | 278 ++++++++++++++--------- services/gam/src/tokens.rs | 4 +- services/root-keys/locales/i18n.json | 7 + services/root-keys/src/api.rs | 4 + services/root-keys/src/implementation.rs | 20 +- services/root-keys/src/lib.rs | 8 +- services/root-keys/src/main.rs | 98 +++++++- services/shellchat/Cargo.toml | 4 + services/shellchat/src/cmds/keys.rs | 12 + services/shellchat/src/main.rs | 8 +- xous-rs/Cargo.toml | 2 +- xous-rs/src/locale.rs | 2 +- 17 files changed, 470 insertions(+), 139 deletions(-) create mode 100644 services/root-keys/locales/i18n.json diff --git a/Cargo.lock b/Cargo.lock index 385d46588..d7fc6ee60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "addr2line" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a55f82cfe485775d02112886f4169bde0c5894d75e79ead7eafe7e40a25e45f7" +dependencies = [ + "gimli", +] + [[package]] name = "adler" version = "0.2.3" @@ -93,6 +102,20 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" +[[package]] +name = "backtrace" +version = "0.3.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d117600f438b1707d4e4ae15d3595657288f8235a0eb593e80ecc98ab34e1bc" +dependencies = [ + "addr2line", + "cfg-if 1.0.0", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + [[package]] name = "bare-metal" version = "0.2.5" @@ -162,7 +185,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "which", + "which 3.1.1", ] [[package]] @@ -529,6 +552,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "debug-here" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7791f83f55f330aa6406d71cc29d6d785ea1e2cf326001d7b2b45a5065efb1" +dependencies = [ + "lazy_static", + "which 2.0.1", + "winapi", +] + [[package]] name = "digest" version = "0.9.0" @@ -668,6 +702,15 @@ dependencies = [ "termcolor", ] +[[package]] +name = "failure" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" +dependencies = [ + "backtrace", +] + [[package]] name = "filetime" version = "0.2.14" @@ -707,6 +750,7 @@ dependencies = [ "ime-plugin-shell", "keyboard", "llio", + "locales", "log", "log-server", "num-derive", @@ -761,6 +805,12 @@ dependencies = [ "wasi", ] +[[package]] +name = "gimli" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6503fe142514ca4799d4c26297c4248239fe8838d827db6bd6065c6ed29a6ce" + [[package]] name = "glob" version = "0.3.0" @@ -905,6 +955,7 @@ dependencies = [ "graphics-server", "ime-plugin-api", "keyboard", + "locales", "log", "log-server", "num-derive", @@ -1040,6 +1091,10 @@ dependencies = [ "xous-names", ] +[[package]] +name = "locales" +version = "0.1.0" + [[package]] name = "log" version = "0.4.14" @@ -1189,6 +1244,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9a7ab5d64814df0fe4a4b5ead45ed6c5f181ee3ff04ba344313a6c80446c5d4" + [[package]] name = "once_cell" version = "1.5.2" @@ -1587,6 +1648,12 @@ dependencies = [ "xous-names", ] +[[package]] +name = "rustc-demangle" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dead70b0b5e03e9c814bcb6b01e03e68f7c57a80aa48c72ec92152ab3e818d49" + [[package]] name = "rustc-hash" version = "1.1.0" @@ -1663,6 +1730,17 @@ version = "1.0.123" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d5161132722baa40d802cc70b15262b98258453e85e5d1d365c757c73869ae" +[[package]] +name = "serde_json" +version = "1.0.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79" +dependencies = [ + "itoa", + "ryu", + "serde", +] + [[package]] name = "sha2" version = "0.9.5" @@ -1686,6 +1764,7 @@ dependencies = [ "com", "content-plugin-api", "curve25519-dalek", + "debug-here", "digest", "ed25519-dalek", "engine-25519", @@ -1704,6 +1783,7 @@ dependencies = [ "num-traits", "rand_core 0.5.1", "rkyv 0.4.3", + "root-keys", "rtc", "sha2", "spinor", @@ -2213,6 +2293,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "which" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b57acb10231b9493c8472b20cb57317d0679a49e0bdbee44b3b803a6473af164" +dependencies = [ + "failure", + "libc", +] + [[package]] name = "which" version = "3.1.1" @@ -2337,6 +2427,7 @@ version = "0.8.3" dependencies = [ "bitflags", "compiler_builtins", + "debug-here", "hex", "lazy_static", "log", @@ -2382,6 +2473,14 @@ dependencies = [ [[package]] name = "xtask" version = "0.1.0" +dependencies = [ + "glob", + "lazy_static", + "proc-macro2 1.0.24", + "quote 1.0.8", + "regex", + "serde_json", +] [[package]] name = "zero" diff --git a/kernel/Cargo.lock b/kernel/Cargo.lock index cdb4fec0e..17a4f6657 100644 --- a/kernel/Cargo.lock +++ b/kernel/Cargo.lock @@ -619,6 +619,7 @@ name = "xous" version = "0.8.3" dependencies = [ "bitflags", + "debug-here", "hex", "lazy_static", "xous-macros", diff --git a/services/gam/Cargo.toml b/services/gam/Cargo.toml index 7d2fb1726..7b3e2d5d4 100644 --- a/services/gam/Cargo.toml +++ b/services/gam/Cargo.toml @@ -31,6 +31,7 @@ rkyv = {version = "0.4.3", default-features = false, features = ["const_generics susres = {path = "../susres"} # used for the sleep now menu item enum_dispatch = "0.3.7" # used for trait-based dispatch off of multiple layout objects. +locales = {path = "../../locales"} [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = {path = "../../utralib"} diff --git a/services/gam/src/layouts.rs b/services/gam/src/layouts.rs index 85641a8bd..b9021fc2a 100755 --- a/services/gam/src/layouts.rs +++ b/services/gam/src/layouts.rs @@ -137,7 +137,7 @@ impl LayoutApi for ChatLayout { self.content } fn set_visibility_state(&mut self, onscreen: bool, canvases: &mut FnvIndexMap) { - log::debug!("chatlayout: set_visibility_state onscreen {}, self.visible {}", onscreen, self.visible); + log::debug!("request modal to onscreen {} from self.visible {}", onscreen, self.visible); if onscreen == self.visible { log::trace!("chatlayout: no change to visibility, moving on"); // nothing to do diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index b78eeb046..4431dc346 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -31,6 +31,8 @@ use enum_dispatch::enum_dispatch; use gam::{MenuItem, MenuPayload, Menu, MenuOpcode}; +use locales::t; + //// todo: // - add auth tokens to audio streams, so less trusted processes can make direct connections to the codec and reduce latency @@ -62,6 +64,7 @@ pub(crate) trait LayoutApi { pub(crate) enum UxLayout { ChatLayout, MenuLayout, + ModalLayout, } #[derive(Debug, Copy, Clone)] @@ -91,10 +94,11 @@ pub(crate) struct UxContext { /// opcode ID for AudioFrame pub audioframe_id: Option, } -const MAX_UX_CONTEXTS: usize = 4; +const MAX_UX_CONTEXTS: usize = 5; pub(crate) const MAX_CANVASES: usize = 32; // const BOOT_APP_NAME: &'static str = "shellchat"; // this is the app to display on boot -- we will eventually need this once we have more than one app? pub const MAIN_MENU_NAME: &'static str = "main menu"; +pub const ROOTKEY_MODAL_NAME: &'static str = "rootkeys modal"; const BOOT_CONTEXT_TRUSTLEVEL: u8 = 254; /* @@ -186,7 +190,7 @@ impl ContextManager { trust_level, canvases).expect("couldn't create menu layout"); // default to off-screen for all layouts menulayout.set_visibility_state(false, canvases); - log::debug!("debug layout: {:?}", menulayout); + log::debug!("debug menu layout: {:?}", menulayout); let ux_context = UxContext { layout: UxLayout::MenuLayout(menulayout), predictor: None, @@ -215,7 +219,31 @@ impl ContextManager { } } UxType::Modal => { - // TODO + let mut modallayout = ModalLayout::init(&gfx, &trng, + trust_level, canvases).expect("couldn't create modal layout"); + // default to off-screen for all layouts + modallayout.set_visibility_state(false, canvases); + log::debug!("debug modal layout: {:?}", modallayout); + let ux_context = UxContext { + layout: UxLayout::ModalLayout(modallayout), + predictor: None, + app_token: token, + gam_token: [trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(), ], + trust_level, + listener: xous::connect(xous::SID::from_array(registration.listener)).unwrap(), + redraw_id: registration.redraw_id, + gotinput_id: None, + audioframe_id: None, + rawkeys_id: registration.rawkeys_id, + vibe: false, + }; + for maybe_context in self.contexts.iter_mut() { + if maybe_context.is_none() { + *maybe_context = Some(ux_context); + found_slot = true; + break; + } + } } } } else { @@ -228,6 +256,13 @@ impl ContextManager { if found_slot { maybe_token } else { + // Note: for the most paranoid modes, you probably want exactly as many UX contexts + // as you expect to use. This cap helps prevent rouge processes from registering + // UX contexts that it shouldn't. + // + // That being said, if you are to run "generic apps from the internet" you can't + // put a proper bound on this number. + log::error!("Ran out of UX contexts: try increasing MAX_UX_CONTEXTS in gam.rs"); None } } @@ -556,7 +591,7 @@ fn imef_cb(s: String::<4000>) { #[xous::xous_main] fn xmain() -> ! { log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Info); + log::set_max_level(log::LevelFilter::Debug); info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); @@ -923,6 +958,12 @@ fn xmain() -> ! { context_mgr.activate(&gfx, &mut canvases, new_app_token, false); } } + } else if let Some(modal_token) = context_mgr.find_app_token_by_name(ROOTKEY_MODAL_NAME) { + if modal_token == switchapp.token { + if let Some(new_app_token) = context_mgr.find_app_token_by_name(switchapp.app_name.as_str().unwrap()) { + context_mgr.activate(&gfx, &mut canvases, new_app_token, false); + } + } } }, Some(Opcode::RaiseMenu) => { @@ -962,7 +1003,7 @@ pub fn main_menu_thread() { let com = com::Com::new(&xns).unwrap(); let blon_item = MenuItem { - name: String::<64>::from_str("Backlight on"), + name: String::<64>::from_str(t!("mainmenu.backlighton", xous::LANG)), action_conn: com.conn(), action_opcode: com.getop_backlight(), action_payload: MenuPayload::Scalar([191 >> 3, 191 >> 3, 0, 0]), @@ -971,7 +1012,7 @@ pub fn main_menu_thread() { menu.add_item(blon_item); let bloff_item = MenuItem { - name: String::<64>::from_str("Backlight off"), + name: String::<64>::from_str(t!("mainmenu.backlightoff", xous::LANG)), action_conn: com.conn(), action_opcode: com.getop_backlight(), action_payload: MenuPayload::Scalar([0, 0, 0, 0]), @@ -980,7 +1021,7 @@ pub fn main_menu_thread() { menu.add_item(bloff_item); let sleep_item = MenuItem { - name: String::<64>::from_str("Sleep now"), + name: String::<64>::from_str(t!("mainmenu.sleep", xous::LANG)), action_conn: susres.conn(), action_opcode: susres.getop_suspend(), action_payload: MenuPayload::Scalar([0, 0, 0, 0]), @@ -989,7 +1030,7 @@ pub fn main_menu_thread() { menu.add_item(sleep_item); let close_item = MenuItem { - name: String::<64>::from_str("Close Menu"), + name: String::<64>::from_str(t!("mainmenu.closemenu", xous::LANG)), action_conn: menu.gam.conn(), action_opcode: menu.gam.getop_revert_focus(), action_payload: MenuPayload::Scalar([0, 0, 0, 0]), diff --git a/services/gam/src/modal.rs b/services/gam/src/modal.rs index aa6223f33..56bdfe5a5 100755 --- a/services/gam/src/modal.rs +++ b/services/gam/src/modal.rs @@ -2,6 +2,7 @@ /* design ideas +Modal for password request: --------------------- | Password Type: Updater | Requester: RootKeys @@ -10,15 +11,42 @@ | | *****4f_ | - | [ ] Hide as you type - | [x] Display last chars - | [ ] Show as you type - | + | โ† ๐Ÿ‘๏ธ ๐Ÿ•ถ๏ธ * โ†’ + |-------------------- + +Item primitives: + - text bubble + - text entry field (with confidentiality option) + - left/right radio select + - up/down radio select + +Then simple menu prompt after password entry: + --------------------- | [x] Persist until reboot | [ ] Persist until suspend | [ ] Use once --------------------- + +General form for modals: + + [top text] + + [action form] + + [bottom text] + + - "top text" is an optional TextArea + - "action form" is a mandatory field that handles interactions + - "bottom text" is an optional TextArea + + Action form can be exactly one of the following: + - password text field - enter closes the form, has visibility options as left/right arrows; entered text wraps + - regular text field - enter closes the form, visibility is always visible; entered text wraps + - radio buttons - has an explicit "okay" button to close the modal; up/down arrows + select/enter pick the radio + - check boxes - has an explicit "okay" button to close the modal; up/down arrows + select/enter checks boxes + - slider - left/right moves the slider, enter/select closes the modal */ +use enum_dispatch::enum_dispatch; use crate::api::*; use crate::Gam; @@ -34,24 +62,90 @@ use xous::{send_message, CID, Message}; use xous_ipc::{String, Buffer}; use num_traits::*; -const MAX_ITEMS: usize = 16; +const MAX_ITEMS: usize = 8; -#[allow(dead_code)] // here until Memory types are implemented #[derive(Debug, Copy, Clone)] -pub enum ModalPayload { - /// memorized scalar payload - Scalar([u32; 4]), - /// this a nebulous-but-TBD maybe way of bodging in a more complicated record, which would involve - /// casting this memorized, static payload into a Buffer and passing it on. Let's not worry too much about it for now, it's mostly apirational... - Memory(([u8; 256], usize)), +pub struct ItemName(String::<64>); +#[derive(Debug, Copy, Clone)] +pub struct TextEntryPayload(String::<256>); +#[derive(Debug, Copy, Clone)] +pub struct RadioButtonPayload(ItemName); // returns the name of the item corresponding to the radio button selection +#[derive(Debug, Copy, Clone)] +pub struct CheckBoxPayload([Option; MAX_ITEMS]); // returns a list of potential items that could be selected + +#[derive(Debug, Copy, Clone)] +pub enum TextEntryVisibility { + /// text is fully visible + Visible, + /// only last chars are shown of text entry, the rest obscured with * + LastChars, + /// all chars hidden as * + Hidden, } #[derive(Debug, Copy, Clone)] -pub struct ModalItem { - pub name: String::<64>, +pub struct TextEntry { + pub is_password: bool, + pub visibility: TextEntryVisibility, pub action_conn: xous::CID, pub action_opcode: u32, - pub action_payload: ModalPayload, - pub close_on_select: bool, + pub action_payload: Option, +} +impl ActionApi for TextEntry { + fn height(&self) -> i16 { + 16 // placeholder + } +} +#[derive(Debug, Copy, Clone)] +pub struct RadioButtons { + pub items: [Option; MAX_ITEMS], + pub action_conn: xous::CID, + pub action_opcode: u32, + pub action_payload: Option, +} +impl ActionApi for RadioButtons { + fn height(&self) -> i16 { + 16 // placeholder + } +} +#[derive(Debug, Copy, Clone)] +pub struct CheckBoxes { + pub items: [Option; MAX_ITEMS], + pub action_conn: xous::CID, + pub action_opcode: u32, + pub action_payload: Option, +} +impl ActionApi for CheckBoxes { + fn height(&self) -> i16 { + 16 // placeholder + } +} +#[derive(Debug, Copy, Clone)] +pub struct Slider { + pub min: u32, + pub max: u32, + pub step: u32, + pub action_conn: xous::CID, + pub action_opcode: u32, + pub action_payload: u32, +} +impl ActionApi for Slider { + fn height(&self) -> i16 { + 16 // placeholder + } +} + +#[enum_dispatch] +trait ActionApi { + fn height(&self) -> i16 {16} // get the computed height for an action +} + +#[enum_dispatch(ActionApi)] +#[derive(Debug, Copy, Clone)] +pub enum ActionType { + TextEntry, + RadioButtons, + CheckBoxes, + Slider } #[derive(Debug)] @@ -59,12 +153,14 @@ pub struct Modal { pub sid: xous::SID, pub gam: Gam, pub xns: xous_names::XousNames, - pub items: [Option; MAX_ITEMS], - pub index: usize, // currently selected item + pub top_text: Option, + pub bot_text: Option, + pub action: ActionType, + + //pub index: usize, // currently selected item pub canvas: Gid, pub authtoken: [u32; 4], pub margin: i16, - pub divider_margin: i16, pub line_height: i16, pub canvas_width: Option, } @@ -77,7 +173,7 @@ pub enum ModalOpcode { } impl Modal { - pub fn new(name: &str) -> Modal { + pub fn new(name: &str, action: ActionType, top_text: Option, bot_text: Option) -> Modal { let xns = xous_names::XousNames::new().unwrap(); let sid = xous::create_server().expect("can't create private modal message server"); let gam = Gam::new(&xns).expect("can't connect to GAM"); @@ -97,56 +193,65 @@ impl Modal { log::debug!("requesting content canvas for modal"); let canvas = gam.request_content_canvas(authtoken.unwrap()).expect("couldn't get my content canvas from GAM"); let line_height = gam.glyph_height_hint(GlyphStyle::Regular).expect("couldn't get glyph height hint") as i16; - Modal { + + // we now have a canvas that is some minimal height, but with the final width as allowed by the GAM. + // compute the final height based upon the contents within. + let mut modal = Modal { sid, gam, xns, - items: [None; MAX_ITEMS], - index: 0, + top_text, + bot_text, + action, canvas, authtoken: authtoken.unwrap(), margin: 4, - divider_margin: 20, line_height, canvas_width: None, - } - } - // if successful, returns None, otherwise, the modal item - pub fn add_item(&mut self, new_item: ModalItem) -> Option { - // first, do the insertion. - // add the modal item to the first free slot - // any modifications to the modal structure should guarantee that the list is compacted - // and has no holes, in order for the "selected index" logic to work - let mut success = false; - for item in self.items.iter_mut() { - if item.is_none() { - *item = Some(new_item); - success = true; - break; + }; + + let mut total_height = modal.margin * 2; + // compute height of top_text, if any + if let Some(mut text) = modal.top_text { + text.dry_run = true; + modal.gam.post_textview(&mut text).expect("couldn't simulate top text size"); + if let Some(bounds) = text.bounds_computed { + total_height += bounds.br.y - bounds.tl.y; + } else { + log::error!("couldn't compute height for modal top_text: {:?}", text); + panic!("couldn't compute height for modal top_text"); } } - if success { - // now, recompute the height - let mut total_items = self.num_items(); - if total_items == 0 { - total_items = 1; // just so we see a blank modal at least, and have a clue how to debug - } - let current_bounds = self.gam.get_canvas_bounds(self.canvas).expect("couldn't get current bounds"); - let mut new_bounds = SetCanvasBoundsRequest { - requested: Point::new(current_bounds.x, total_items as i16 * self.line_height + self.margin * 2), - granted: None, - token_type: TokenType::App, - token: self.authtoken, - }; - log::debug!("add_item requesting bounds of {:?}", new_bounds); - self.gam.set_canvas_bounds_request(&mut new_bounds).expect("couldn't call set bounds"); + // compute height of action item + total_height += modal.action.height(); - None - } else { - Some(new_item) + // compute height of bot_text, if any + if let Some(mut text) = modal.bot_text { + text.dry_run = true; + modal.gam.post_textview(&mut text).expect("couldn't simulate bot text size"); + if let Some(bounds) = text.bounds_computed { + total_height += bounds.br.y - bounds.tl.y; + } else { + log::error!("couldn't compute height for modal bot_text: {:?}", text); + panic!("couldn't compute height for modal bot_text"); + } } + + let current_bounds = modal.gam.get_canvas_bounds(modal.canvas).expect("couldn't get current bounds"); + let mut new_bounds = SetCanvasBoundsRequest { + requested: Point::new(current_bounds.x, total_height), + granted: None, + token_type: TokenType::App, + token: modal.authtoken, + }; + log::debug!("modal requesting bounds of {:?}", new_bounds); + modal.gam.set_canvas_bounds_request(&mut new_bounds).expect("couldn't call set bounds"); + + modal } + + /* pub fn draw_item(&self, index: i16, with_marker: bool) { use core::fmt::Write; let canvas_size = self.gam.get_canvas_bounds(self.canvas).unwrap(); @@ -185,45 +290,11 @@ impl Modal { log::debug!("cant draw divider because our canvas width was not initialized. Ignoring request."); } } - pub fn prev_item(&mut self) { - if self.index > 0 { - // wipe out the current marker - self.draw_item(self.index as i16, false); - self.index -= 1; - // add the marker to the pervious item - self.draw_item(self.index as i16, true); + */ - if self.index != 0 { - self.draw_divider(self.index as i16); - } - if self.index < self.num_items() - 1 { - self.draw_divider(self.index as i16 + 1); - } - if self.index < self.num_items() - 2 { - self.draw_divider(self.index as i16 + 2); - } - } - } - pub fn next_item(&mut self) { - if self.index < (self.num_items() - 1) { - // wipe out the current marker - self.draw_item(self.index as i16, false); - self.index += 1; - // add the marker to the pervious item - self.draw_item(self.index as i16, true); - - if self.index != 1 { - self.draw_divider(self.index as i16 - 1); - } - self.draw_divider(self.index as i16); - if self.index < self.num_items() - 1 { - self.draw_divider(self.index as i16 + 1); - } - } - } pub fn redraw(&mut self) { // for now, just draw a black rectangle - log::trace!("modal redraw"); + log::debug!("modal redraw"); let canvas_size = self.gam.get_canvas_bounds(self.canvas).unwrap(); self.canvas_width = Some(canvas_size.x); @@ -231,10 +302,10 @@ impl Modal { self.gam.draw_rounded_rectangle(self.canvas, RoundedRectangle::new( Rectangle::new_with_style(Point::new(0, 0), canvas_size, - DrawStyle::new(PixelColor::Light, PixelColor::Dark, 3) + DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 3) ), 5 )).unwrap(); - + /* // draw the line items // we require that the items list be in index-order, with no holes: we abort at the first None item let mut cur_index: i16 = 0; @@ -254,24 +325,16 @@ impl Modal { break; } } + */ self.gam.redraw().unwrap(); } - fn num_items(&self) -> usize { - let mut items = 0; - for maybe_item in self.items.iter() { - if maybe_item.is_some() { - items += 1; - } else { - break; - } - } - items - } + pub fn key_event(&mut self, keys: [char; 4]) { for &k in keys.iter() { log::debug!("got key '{}'", k); match k { 'โˆด' => { + /* if let Some(mi) = self.items[self.index] { // give up focus before issuing the command, as some commands conflict with loss of focus... if mi.close_on_select { @@ -291,6 +354,7 @@ impl Modal { } self.index = 0; // reset the index to 0 } + */ self.gam.redraw().unwrap(); }, 'โ†' => { @@ -302,11 +366,11 @@ impl Modal { log::trace!("got right arrow"); } 'โ†‘' => { - self.prev_item(); + //self.prev_item(); self.gam.redraw().unwrap(); } 'โ†“' => { - self.next_item(); + //self.next_item(); self.gam.redraw().unwrap(); } _ => {} diff --git a/services/gam/src/tokens.rs b/services/gam/src/tokens.rs index f8aa72125..74fec84b0 100755 --- a/services/gam/src/tokens.rs +++ b/services/gam/src/tokens.rs @@ -12,8 +12,8 @@ use xous_ipc::String; */ // if you add more UxContexts, and you want them authorized by the GAM, add their names here. -const TOKEN_SLOTS: usize = 4; -const EXPECTED_BOOT_CONTEXTS: [&'static str; TOKEN_SLOTS] = ["shellchat", "main menu", "status", "emoji menu"]; +const TOKEN_SLOTS: usize = 5; +const EXPECTED_BOOT_CONTEXTS: [&'static str; TOKEN_SLOTS] = ["shellchat", "main menu", "status", "emoji menu", "rootkeys modal"]; #[derive(Copy, Clone, Debug)] pub(crate) struct NamedToken { diff --git a/services/root-keys/locales/i18n.json b/services/root-keys/locales/i18n.json new file mode 100644 index 000000000..b9053560f --- /dev/null +++ b/services/root-keys/locales/i18n.json @@ -0,0 +1,7 @@ +{ + "rootpass.top": { + "en": "Root password box", + "zh": "็ก็œ ๆจกๅผ", + "en-audio": "Root password box" + } +} \ No newline at end of file diff --git a/services/root-keys/src/api.rs b/services/root-keys/src/api.rs index ee94ef7b1..899923f4d 100644 --- a/services/root-keys/src/api.rs +++ b/services/root-keys/src/api.rs @@ -1,4 +1,6 @@ pub(crate) const SERVER_NAME_KEYS: &str = "_Root key server and update manager_"; +pub(crate) const ROOTKEY_MODAL_NAME: &'static str = "rootkeys modal"; + #[allow(dead_code)] #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] @@ -11,6 +13,8 @@ pub(crate) enum Opcode { /// Suspend/resume callback SuspendResume, + + Quit } #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index c7d56cf2e..2eda6eb78 100755 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -43,19 +43,25 @@ pub(crate) mod keyrom_config { pub const INITIALIZED: KeyField = KeyField::new(4, 27); } +#[repr(C)] +struct PasswordCache { + // this structure is mapped into the password cache page and can be zero-ized at any time + canary: u32, // this is 0 if the page was cleared; it is set immediately upon allocation/initialization/update +} + pub(crate) struct RootKeys { keyrom: utralib::CSR, gateware: xous::MemoryRange, staging: xous::MemoryRange, loader_code: xous::MemoryRange, kernel: xous::MemoryRange, - /// region of RAM that holds all plaintext passwords and keys. stuck in one well-defined page so we can + /// regions of RAM that holds all plaintext passwords, keys, and temp data. stuck in two well-defined page so we can /// zero-ize it upon demand, without guessing about stack frames and/or Rust optimizers removing writes sensitive_data: xous::MemoryRange, + pass_cache: xous::MemoryRange, password_policy: PasswordRetentionPolicy, susres: susres::Susres, // for disabling suspend/resume trng: trng::Trng, - password_modal: gam::Modal, } impl RootKeys { @@ -100,6 +106,12 @@ impl RootKeys { 0x1000, xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map sensitive data page"); + let pass_cache = xous::syscall::map_memory( + None, + None, + 0x1000, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map sensitive data page"); let mut keys = RootKeys { keyrom: CSR::new(keyrom.as_mut_ptr() as *mut u32), @@ -108,10 +120,10 @@ impl RootKeys { loader_code, kernel, sensitive_data, + pass_cache, password_policy: PasswordRetentionPolicy::AlwaysKeep, susres: susres::Susres::new_without_hook(&xns).expect("couldn't connect to susres without hook"), trng: trng::Trng::new(&xns).expect("couldn't connect to TRNG server"), - password_modal: gam::Modal::new("RootKeys password dialog box"), }; keys @@ -212,7 +224,7 @@ impl RootKeys { self.susres.set_suspendable(true).expect("couldn't re-allow suspend/resume"); } - pub fn test_ux(&mut self) { + pub fn test_ux(&mut self, _arg: usize) { } } diff --git a/services/root-keys/src/lib.rs b/services/root-keys/src/lib.rs index 837b3ebc9..832bf8983 100644 --- a/services/root-keys/src/lib.rs +++ b/services/root-keys/src/lib.rs @@ -25,6 +25,7 @@ pub enum ImageType { Kernel, } +#[derive(Debug)] // there is no confidential information in the external structure; it's safe to Debug it pub struct RootKeys { conn: CID, progress_sid: Option, @@ -116,10 +117,10 @@ impl RootKeys { unimplemented!(); } - pub fn test_ux(&mut self) { + pub fn test_ux(&mut self, arg: usize) { send_message(self.conn, - Message::new_scalar(Opcode::TestUx.to_usize().unwrap(), - 0, 0, 0, 0) + Message::new_blocking_scalar(Opcode::TestUx.to_usize().unwrap(), + arg, 0, 0, 0) ).expect("couldn't send test message"); } } @@ -128,6 +129,7 @@ use core::sync::atomic::{AtomicU32, Ordering}; static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for RootKeys { fn drop(&mut self) { + log::debug!("dropping rootkeys object"); // 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". diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index 3008eb9df..e9785398e 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -3,10 +3,13 @@ mod api; use api::*; -use xous::{CID, msg_scalar_unpack, send_message, Message}; +use xous::{CID, msg_scalar_unpack, send_message, Message, msg_blocking_scalar_unpack}; +use xous_ipc::{String, Buffer}; use num_traits::*; +use gam::modal::*; + #[cfg(target_os = "none")] mod implementation; #[cfg(target_os = "none")] @@ -15,28 +18,102 @@ use implementation::*; // a stub to try to avoid breaking hosted mode for as long as possible. #[cfg(not(target_os = "none"))] mod implementation { + use crate::ROOTKEY_MODAL_NAME; + use gam::modal::*; + use xous_ipc::String; + pub struct RootKeys { + gam: gam::Gam, + ticktimer: ticktimer_server::Ticktimer, } impl RootKeys { - pub fn new() -> RootKeys { + pub fn new(xns: &xous_names::XousNames) -> RootKeys { RootKeys { + gam: gam::Gam::new(&xns).expect("couldn't allocate GAM for testing"), + ticktimer: ticktimer_server::Ticktimer::new().expect("couldn't get ticktimer"), } } pub fn suspend(&self) { } pub fn resume(&self) { } + + pub fn try_init_keys(&mut self, _maybe_progress: Option) { + } + + pub fn test_ux(&mut self, arg: usize) { + match arg { + 0 => self.gam.raise_modal(ROOTKEY_MODAL_NAME).expect("couldn't raise modal"), + 1 => self.gam.relinquish_focus().expect("couldn't hide modal"), + _ => log::info!("test_ux got unrecognized arg: {}", arg), + }; + } } } +pub(crate) fn rootkeys_ux_thread() { + let password_action = gam::modal::TextEntry { + is_password: true, + visibility: gam::modal::TextEntryVisibility::LastChars, + action_conn: 0, //place holder + action_opcode: 0, // placeholder + action_payload: None, //placeholder + }; + let mut modal = gam::Modal::new(crate::ROOTKEY_MODAL_NAME, gam::ActionType::TextEntry(password_action), None, None); + log::trace!("ux thread modal: {:?}", modal); + + loop { + let msg = xous::receive_message(modal.sid).unwrap(); + log::trace!("ux message: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(ModalOpcode::Redraw) => { + modal.redraw(); + }, + Some(ModalOpcode::Rawkeys) => 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}' + }, + ]; + modal.key_event(keys); + }), + Some(ModalOpcode::Quit) => { + break; + }, + None => { + log::error!("unknown opcode {:?}", msg.body.id()); + } + } + } + log::trace!("password modal thread exit, destroying servers"); + // do we want to add a deregister_ux call to the system? + xous::destroy_server(modal.sid).unwrap(); +} #[xous::xous_main] fn xmain() -> ! { use crate::implementation::RootKeys; log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Info); + log::set_max_level(log::LevelFilter::Trace); log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); @@ -56,8 +133,11 @@ fn xmain() -> ! { let sr_cid = xous::connect(keys_sid).expect("couldn't create suspend callback connection"); let mut susres = susres::Susres::new(&xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); + xous::create_thread_0(rootkeys_ux_thread).expect("couldn't start rootkeys UX thread"); + loop { let msg = xous::receive_message(keys_sid).unwrap(); + log::trace!("message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, { keys.suspend(); @@ -71,12 +151,16 @@ fn xmain() -> ! { let sid = xous::SID::from_u32(s0 as u32, s1 as u32, s2 as u32, s3 as u32); keys.try_init_keys(Some(sid)); }), - Some(Opcode::TestUx) => { - keys.test_ux(); - }, + Some(Opcode::TestUx) => msg_blocking_scalar_unpack!(msg, arg, _, _, _, { + keys.test_ux(arg); + xous::return_scalar(msg.sender, 0).expect("couldn't unblock sender"); + }), + Some(Opcode::Quit) => { + log::warn!("password thread received quit, exiting."); + break + } None => { log::error!("couldn't convert opcode"); - break } } } diff --git a/services/shellchat/Cargo.toml b/services/shellchat/Cargo.toml index 8eedd4006..7310994da 100644 --- a/services/shellchat/Cargo.toml +++ b/services/shellchat/Cargo.toml @@ -29,6 +29,7 @@ aes-xous={path="../aes"} cipher = "0.3" engine-25519 = {path="../engine-25519"} spinor = {path="../spinor"} +root-keys = {path="../root-keys"} heapless = "0.7" trng = {path = "../trng"} @@ -64,3 +65,6 @@ utralib = {path = "../../utralib"} [features] debugprint = [] default = [] # "debugprint" + +[target.'cfg(any(windows,unix))'.dependencies] +debug-here = "*" diff --git a/services/shellchat/src/cmds/keys.rs b/services/shellchat/src/cmds/keys.rs index b2bc19223..d88d71633 100644 --- a/services/shellchat/src/cmds/keys.rs +++ b/services/shellchat/src/cmds/keys.rs @@ -5,6 +5,7 @@ use xous_ipc::String; pub struct Keys { testing_range: xous::MemoryRange, spinor: spinor::Spinor, + rootkeys: root_keys::RootKeys, } const TEST_SIZE: usize = 0x4000; const TEST_BASE: usize = 0x608_0000; @@ -32,6 +33,7 @@ impl Keys { Keys { testing_range, spinor, + rootkeys: root_keys::RootKeys::new(&xns).expect("couldn't allocate rootkeys API"), } } } @@ -48,6 +50,16 @@ impl<'a> ShellCmdApi<'a> for Keys { if let Some(sub_cmd) = tokens.next() { match sub_cmd { + "ux0" => { + self.rootkeys.test_ux(0); + //debug_here::debug_here!(); + write!(ret, "show UX").unwrap(); + } + "ux1" => { + self.rootkeys.test_ux(1); + //debug_here::debug_here!(); + write!(ret, "hide UX").unwrap(); + } "usblock" => { env.llio.debug_usb(Some(true)).unwrap(); write!(ret, "USB debug port locked out; one word at 0x80000000 is disclosable via USB.").unwrap(); diff --git a/services/shellchat/src/main.rs b/services/shellchat/src/main.rs index dd485ec84..79f6c2f2b 100644 --- a/services/shellchat/src/main.rs +++ b/services/shellchat/src/main.rs @@ -279,7 +279,7 @@ fn xmain() -> ! { log::trace!("starting main loop"); loop { let msg = xous::receive_message(shch_sid).unwrap(); - log::trace!("got message {:?}", msg); + log::debug!("got message {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(ShellOpcode::Line) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; @@ -294,7 +294,7 @@ fn xmain() -> ! { repl.redraw().expect("REPL couldn't redraw"); } Some(ShellOpcode::Quit) => { - log::trace!("got Quit"); + log::error!("got Quit"); break; } _ => { @@ -308,10 +308,10 @@ fn xmain() -> ! { repl.update(was_callback).expect("REPL had problems updating"); update_repl = false; } - log::trace!("reached bottom of main loop"); + log::debug!("reached bottom of main loop"); } // clean up our program - log::trace!("main loop exit, destroying servers"); + log::error!("main loop exit, destroying servers"); xns.unregister_server(shch_sid).unwrap(); xous::destroy_server(shch_sid).unwrap(); log::trace!("quitting"); diff --git a/xous-rs/Cargo.toml b/xous-rs/Cargo.toml index c1a211689..5f5f36918 100644 --- a/xous-rs/Cargo.toml +++ b/xous-rs/Cargo.toml @@ -36,4 +36,4 @@ default = ["bit-flags", "xous-macros"] [target.'cfg(any(windows,unix))'.dependencies] lazy_static = "1.4" hex = "0.4" -# debug-here = "*" +debug-here = "*" diff --git a/xous-rs/src/locale.rs b/xous-rs/src/locale.rs index 34399dbdb..5b61e9874 100644 --- a/xous-rs/src/locale.rs +++ b/xous-rs/src/locale.rs @@ -1 +1 @@ -pub const LANG: &'static str = "zh"; +pub const LANG: &'static str = "en";