From 30910dbd4fe73268e4c44f673cf52a32d07a9cb9 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 3 Feb 2022 02:46:37 +0800 Subject: [PATCH] add keyboard layout setting and retention Keyboard setting is "the one and only" exception to user settings that are saved without encryption. This is because you need your keyboard layout to be set in order for you to type your password. Thus, this needed a bit of a special-case to handle its storage record. We decided to lop off 1 page from the loader and have it store the keyboard layout code. Let's hope we can have the discipline to really just store that one word of information and not later be like "gee wally, you have a whoooole 4092 unused bytes of space we can cram unencrypted user settings in, sure would be a waste to not put those use those". --- Cargo.lock | 2 ++ services/gam/src/api.rs | 1 + services/gam/src/lib.rs | 2 ++ services/gam/src/menu.rs | 28 ++++++++++++++++- services/keyboard/Cargo.toml | 1 + services/keyboard/src/api.rs | 8 +++-- services/keyboard/src/lib.rs | 19 +++++++++++ services/keyboard/src/main.rs | 52 ++++++++++++++++++++++++++++--- services/spinor/src/main.rs | 3 +- services/status/Cargo.toml | 1 + services/status/locales/i18n.json | 8 ++++- services/status/src/kbdmenu.rs | 49 +++++++++++++++++++++++++++++ services/status/src/main.rs | 23 ++++++++++++++ services/status/src/mainmenu.rs | 8 +++++ xous-rs/src/definitions.rs | 4 ++- 15 files changed, 197 insertions(+), 12 deletions(-) create mode 100644 services/status/src/kbdmenu.rs diff --git a/Cargo.lock b/Cargo.lock index 4dda59662..b7184adba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1163,6 +1163,7 @@ dependencies = [ "num-derive", "num-traits", "rkyv", + "spinor", "susres", "ticktimer-server", "utralib", @@ -2241,6 +2242,7 @@ dependencies = [ "content-plugin-api", "gam", "graphics-server", + "keyboard", "llio", "locales", "log", diff --git a/services/gam/src/api.rs b/services/gam/src/api.rs index 7e3176037..7a618142d 100644 --- a/services/gam/src/api.rs +++ b/services/gam/src/api.rs @@ -201,6 +201,7 @@ pub(crate) enum MenuMgrOp { // incoming is one of these ops AddItem, DeleteItem, + SetIndex(usize), Quit, // response must be one of these Ok, diff --git a/services/gam/src/lib.rs b/services/gam/src/lib.rs index 86c9250d0..39c2225d5 100644 --- a/services/gam/src/lib.rs +++ b/services/gam/src/lib.rs @@ -34,6 +34,7 @@ pub const SHARED_MODAL_NAME: &'static str = "shared modal"; pub const STATUS_BAR_NAME: &'static str = "status"; pub const APP_NAME_SHELLCHAT: &'static str = "shellchat"; pub const APP_MENU_NAME: &'static str = "app menu"; +pub const KBD_MENU_NAME: &'static str = "keyboard menu"; /// UX context registry. Names here are authorized by the GAM to have Canvases. pub const EXPECTED_BOOT_CONTEXTS: &[&'static str] = &[ @@ -46,6 +47,7 @@ pub const EXPECTED_BOOT_CONTEXTS: &[&'static str] = &[ SHARED_MODAL_NAME, PDDB_MENU_NAME, APP_MENU_NAME, + KBD_MENU_NAME, ]; #[derive(Copy, Clone, PartialEq, Eq, Debug)] diff --git a/services/gam/src/menu.rs b/services/gam/src/menu.rs index 55ccdd8fc..7273d38f1 100644 --- a/services/gam/src/menu.rs +++ b/services/gam/src/menu.rs @@ -76,6 +76,9 @@ impl<'a> Menu<'a> { pub fn activate(&self) { self.gam.raise_menu(self.name.as_str()).expect("couldn't raise menu"); } + pub fn set_index(&mut self, index: usize) { + self.index = index; + } /// this function spawns a client-side thread to forward redraw and key event /// messages on to a local server. The goal is to keep the local server's SID @@ -357,6 +360,21 @@ impl MenuMatic { false } } + pub fn set_index(&self, index: usize) { + let op = MenuManagement { + item: MenuItem { // dummy item, not used + name: xous_ipc::String::<64>::new(), + action_conn: None, + action_opcode: 0, + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: false, + }, + op: MenuMgrOp::SetIndex(index), + }; + let mut buf = xous_ipc::Buffer::into_buf(op).expect("couldn't transform to memory"); + buf.lend_mut(self.cid, 0).expect("couldn't set menu index"); + // do nothing with the return code + } pub fn quit(&self) { let mm = MenuManagement { item: MenuItem { @@ -385,9 +403,10 @@ pub fn menu_matic(items: Vec::, menu_name: &'static str, maybe_manager } let _ = thread::spawn({ let menu = menu.clone(); + let sid = menu.lock().unwrap().sid.clone(); move || { loop { - let msg = xous::receive_message(menu.lock().unwrap().sid).unwrap(); + let msg = xous::receive_message(sid).unwrap(); log::trace!("message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(MenuOpcode::Redraw) => { @@ -455,6 +474,13 @@ pub fn menu_matic(items: Vec::, menu_name: &'static str, maybe_manager } buffer.replace(mgmt).unwrap(); } + MenuMgrOp::SetIndex(index) => { + log::info!("setting menu index {}", index); + menu.lock().unwrap().set_index(index); + log::info!("index is set"); + mgmt.op = MenuMgrOp::Ok; + buffer.replace(mgmt).unwrap(); + }, MenuMgrOp::Quit => { mgmt.op = MenuMgrOp::Ok; buffer.replace(mgmt).unwrap(); diff --git a/services/keyboard/Cargo.toml b/services/keyboard/Cargo.toml index 665573127..ca2b90b71 100644 --- a/services/keyboard/Cargo.toml +++ b/services/keyboard/Cargo.toml @@ -15,6 +15,7 @@ xous-ipc = {path = "../../xous-ipc"} xous-names = {path = "../xous-names"} llio = {path = "../llio"} susres = {path = "../susres"} +spinor = {path = "../spinor"} num-derive = {version = "0.3.3", default-features = false} num-traits = {version = "0.2.14", default-features = false} diff --git a/services/keyboard/src/api.rs b/services/keyboard/src/api.rs index 32a1e577a..cdf4abeb9 100644 --- a/services/keyboard/src/api.rs +++ b/services/keyboard/src/api.rs @@ -28,19 +28,20 @@ impl From for KeyMap { 1 => KeyMap::Azerty, 2 => KeyMap::Qwertz, 3 => KeyMap::Dvorak, - 4 => KeyMap::Braille, - _ => KeyMap::Undefined, + 254 => KeyMap::Braille, // braille has only one mapping available + _ => KeyMap::Qwerty, } } } impl Into for KeyMap { fn into(self) -> usize { match self { + // note: these indicese correspond to the position on the keyboard menu KeyMap::Qwerty => 0, KeyMap::Azerty => 1, KeyMap::Qwertz => 2, KeyMap::Dvorak => 3, - KeyMap::Braille => 4, + KeyMap::Braille => 254, KeyMap::Undefined => 255, } } @@ -50,6 +51,7 @@ impl Into for KeyMap { pub(crate) enum Opcode { /// set which keyboard mapping is present SelectKeyMap, //(KeyMap), + GetKeyMap, /// request for ScanCodes RegisterListener, diff --git a/services/keyboard/src/lib.rs b/services/keyboard/src/lib.rs index 3b69d8306..de17d8ba3 100644 --- a/services/keyboard/src/lib.rs +++ b/services/keyboard/src/lib.rs @@ -51,6 +51,25 @@ impl Keyboard { ).map(|_| ()) } + pub fn set_keymap(&self, map: KeyMap) -> Result<(), xous::Error> { + send_message(self.conn, + Message::new_scalar(Opcode::SelectKeyMap.to_usize().unwrap(), + map.into(), + 0, 0, 0) + ).map(|_| ()) + } + pub fn get_keymap(&self) -> Result { + match send_message(self.conn, + Message::new_blocking_scalar(Opcode::GetKeyMap.to_usize().unwrap(), + 0, 0, 0, 0) + ) { + Ok(xous::Result::Scalar1(code)) => { + Ok(code.into()) + } + _ => Err(xous::Error::InternalError) + } + } + #[cfg(not(any(target_os = "none", target_os = "xous")))] pub fn hostmode_inject_key(&self, c: char) { send_message(self.conn, diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index aa9f1ed4c..c0780d804 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -8,7 +8,7 @@ use log::info; use num_traits::*; use xous_ipc::Buffer; -use xous::{CID, msg_scalar_unpack}; +use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack}; /// Compute the dvorak key mapping of row/col to key tuples #[allow(dead_code)] @@ -167,6 +167,7 @@ mod implementation { use num_traits::ToPrimitive; use susres::{RegManager, RegOrField, SuspendResume}; use std::collections::HashSet; + use std::convert::TryInto; /// note: the code is structured to use at most 16 rows or 16 cols const KBD_ROWS: usize = 9; @@ -208,7 +209,12 @@ mod implementation { /// indicate if the chord has been captured. Once captured, further presses are ignored, until all keys are let up. chord_captured: bool, susres: RegManager::<{utra::keyboard::KEYBOARD_NUMREGS}>, + /// a field used for debugging various keyboard issues, especially with the interrupt handler pub debug: usize, + /// a slice that contains the location of the early-boot keyboard settings + settings: xous::MemoryRange, + /// a handle to the spinor block so we can update our settings + spinor: spinor::Spinor, } fn handle_kbd(_irq_no: usize, arg: *mut usize) { @@ -275,15 +281,31 @@ mod implementation { xous::MemoryFlags::R | xous::MemoryFlags::W, ) .expect("couldn't map Keyboard CSR range"); + let setting_page = xous::syscall::map_memory( + xous::MemoryAddress::new((xous::EARLY_SETTINGS + xous::FLASH_PHYS_BASE) as usize), + None, + 4096, + xous::MemoryFlags::R, + ) + .expect("couldn't map Keyboard pre-boot setting"); let ticktimer = ticktimer_server::Ticktimer::new().expect("couldn't connect to ticktimer"); let timestamp = ticktimer.elapsed_ms(); + let settings: &[u8] = setting_page.as_slice(); let default_map = if cfg!(feature = "braille") { KeyMap::Braille } else { - KeyMap::Qwerty + // the boot setting is intended to only contain the keyboard mapping...soooooooo.....we manage it as such + // if feature creep causes more stuff to end up here this should be made into something more generic. + // But! If you think you need to slap something in the boot setting, think again. This is an unverified, + // unencrypted and plaintext bit of memory that anyone can read or mess with. The only reason the keyboard + // layout is kept here is because you want your keyboard to be in the right language before typing in the + // password to unlock the PDDB, which is *actually* where all the user settings should be located. + let code = u32::from_le_bytes(settings[..4].try_into().unwrap()); + KeyMap::from(code as usize) }; + let xns = xous_names::XousNames::new().unwrap(); let mut kbd = Keyboard { conn: xous::connect(sid).unwrap(), @@ -307,6 +329,8 @@ mod implementation { chord_captured: false, susres: RegManager::new(csr.as_mut_ptr() as *mut u32), debug: 0, + settings: setting_page, + spinor: spinor::Spinor::new(&xns).unwrap(), }; xous::claim_interrupt( @@ -357,9 +381,21 @@ mod implementation { } pub(crate) fn set_map(&mut self, map: KeyMap) { + let code_usize: usize = map.into(); + let code = (code_usize as u32).to_le_bytes(); + let settings: &[u8] = self.settings.as_slice(); + self.spinor.patch(settings, xous::EARLY_SETTINGS, + &code, 0 + ).expect("couldn't patch our keyboard code"); self.map = map; } - pub(crate) fn get_map(&self) -> KeyMap {self.map} + pub(crate) fn get_map(&mut self) -> KeyMap { + // refresh the map from the setting in the FLASH + let settings: &[u8] = self.settings.as_slice(); + let code = u32::from_le_bytes(settings[..4].try_into().unwrap()); + self.map = KeyMap::from(code as usize); + self.map + } pub(crate) fn set_repeat(&mut self, rate: u32, delay: u32) { self.rate = rate; self.delay = delay; @@ -831,10 +867,11 @@ fn xmain() -> ! { // - GAM // - graphics (if building for hosted mode) // - oqc (for factory test) + // - status sub system (for setting the layout) #[cfg(any(target_os = "none", target_os = "xous"))] - let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(2)).expect("can't register server"); - #[cfg(not(any(target_os = "none", target_os = "xous")))] let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(3)).expect("can't register server"); + #[cfg(not(any(target_os = "none", target_os = "xous")))] + let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(4)).expect("can't register server"); log::trace!("registered with NS -- {:?}", kbd_sid); // Create a new kbd object @@ -908,6 +945,11 @@ fn xmain() -> ! { Some(Opcode::SelectKeyMap) => msg_scalar_unpack!(msg, km, _, _, _, { kbd.set_map(KeyMap::from(km)) }), + Some(Opcode::GetKeyMap) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + xous::return_scalar(msg.sender, + kbd.get_map().into() + ).expect("can't retrieve keymap"); + }), Some(Opcode::SetRepeat) => msg_scalar_unpack!(msg, rate, delay, _, _, { kbd.set_repeat(rate as u32, delay as u32); }), diff --git a/services/spinor/src/main.rs b/services/spinor/src/main.rs index 601b21ac5..2eac0c8a7 100644 --- a/services/spinor/src/main.rs +++ b/services/spinor/src/main.rs @@ -608,8 +608,9 @@ fn xmain() -> ! { - suspend/resume (for suspend locking/unlocking calls) - keystore - PDDB + - keyboard (for updating the key map setting, which needs to be loaded upstream of the PDDB) */ - let spinor_sid = xns.register_name(api::SERVER_NAME_SPINOR, Some(4)).expect("can't register server"); + let spinor_sid = xns.register_name(api::SERVER_NAME_SPINOR, Some(5)).expect("can't register server"); log::trace!("registered with NS -- {:?}", spinor_sid); let handler_conn = xous::connect(spinor_sid).expect("couldn't create interrupt handler callback connection"); diff --git a/services/status/Cargo.toml b/services/status/Cargo.toml index 0f752d837..9620dfb01 100644 --- a/services/status/Cargo.toml +++ b/services/status/Cargo.toml @@ -25,6 +25,7 @@ root-keys = {path = "../root-keys"} modals = {path = "../modals"} pddb = {path = "../pddb"} net = {path = "../net"} +keyboard = {path = "../keyboard"} num-derive = {version = "0.3.3", default-features = false} num-traits = {version = "0.2.14", default-features = false} diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index 6c31a0039..5c143a488 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -106,7 +106,13 @@ "en": "Switch to App...", "ja": "アプリに切り替わる...", "zh": "APP子菜单", - "en-audio": "Switch to app" + "en-audio": "Switch to app submenu" + }, + "mainmenu.kbd": { + "en": "Keyboard layout...", + "ja": "キーボード・レイアウト...", + "zh": "键盘布局...", + "en-audio": "Keyboard layout submenu" }, "mainmenu.reboot": { "en": "Reboot", diff --git a/services/status/src/kbdmenu.rs b/services/status/src/kbdmenu.rs new file mode 100644 index 000000000..d2178a8dd --- /dev/null +++ b/services/status/src/kbdmenu.rs @@ -0,0 +1,49 @@ +use gam::*; +use num_traits::*; +use keyboard::KeyMap; + +use crate::StatusOpcode; + +pub fn create_kbd_menu(status_conn: xous::CID, kbd_mgr: xous::SID) -> MenuMatic { + let mut menu_items = Vec::::new(); + + // what the Rust: I have a into trait for usize on KeyMap. I want to go to a u32 in a single line of code. + // you would think you could do... `KeyMap::Qwerty.into::() as u32`. But no, you can't. Into doesn't + // take a generic. But if I just did .into() with a u32 Rust isn't careless enough to assume I want to go to a usize + // then a u32. But I really don't want to implement a second set of into() traits just for u32. So ugh, now I + // create a typed binding and then cast that binding to a u32 to work around this. idk. + let code: usize = KeyMap::Qwerty.into(); + menu_items.push(MenuItem { + name: xous_ipc::String::from_str("QWERTY"), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::SetKeyboard.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([code as u32, 0, 0, 0]), + close_on_select: true, + }); + let code: usize = KeyMap::Azerty.into(); + menu_items.push(MenuItem { + name: xous_ipc::String::from_str("AZERTY"), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::SetKeyboard.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([code as u32, 0, 0, 0]), + close_on_select: true, + }); + let code: usize = KeyMap::Qwertz.into(); + menu_items.push(MenuItem { + name: xous_ipc::String::from_str("QWERTZ"), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::SetKeyboard.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([code as u32, 0, 0, 0]), + close_on_select: true, + }); + let code: usize = KeyMap::Dvorak.into(); + menu_items.push(MenuItem { + name: xous_ipc::String::from_str("Dvorak"), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::SetKeyboard.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([code as u32, 0, 0, 0]), + close_on_select: true, + }); + + menu_matic(menu_items, gam::KBD_MENU_NAME, Some(kbd_mgr)).expect("couldn't create MenuMatic manager") +} diff --git a/services/status/src/main.rs b/services/status/src/main.rs index a49d45de9..d349ea8ad 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -5,6 +5,8 @@ mod mainmenu; use mainmenu::*; mod appmenu; use appmenu::*; +mod kbdmenu; +use kbdmenu::*; mod app_autogen; use com::api::*; @@ -48,12 +50,17 @@ pub(crate) enum StatusOpcode { SubmenuPddb, /// Raise the App menu SubmenuApp, + /// Raise the Keyboard layout menu + SubmenuKbd, /// Raise the Shellchat app SwitchToShellchat, /// Switch to an app SwitchToApp, + /// Set the keyboard map + SetKeyboard, + /// Suspend handler from the main menu TrySuspend, /// for returning wifi stats @@ -333,6 +340,9 @@ fn xmain() -> ! { log::debug!("starting main menu thread"); create_main_menu(keys.clone(), xous::connect(status_sid).unwrap(), &com); create_app_menu(xous::connect(status_sid).unwrap()); + let kbd_mgr = xous::create_server().unwrap(); + let kbd_menumatic = create_kbd_menu(xous::connect(status_sid).unwrap(), kbd_mgr); + let kbd = keyboard::Keyboard::new(&xns).unwrap(); // some RTC UX structures let modals = modals::Modals::new(&xns).unwrap(); @@ -689,6 +699,19 @@ fn xmain() -> ! { ticktimer.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::SubmenuKbd) => { + log::info!("getting keyboard map"); + let map = kbd.get_keymap().expect("couldn't get key mapping"); + log::info!("setting index to {:?}", map); + kbd_menumatic.set_index(map.into()); + log::info!("raising keyboard menu"); + ticktimer.sleep_ms(100).ok(); // yield for a moment to allow the previous menu to close + gam.raise_menu(gam::KBD_MENU_NAME).expect("couldn't raise keyboard layout submenu"); + }, + Some(StatusOpcode::SetKeyboard) => msg_scalar_unpack!(msg, code, _, _, _, { + let map = keyboard::KeyMap::from(code); + kbd.set_keymap(map).expect("couldn't set keyboard mapping"); + }), Some(StatusOpcode::SwitchToShellchat) => { ticktimer.sleep_ms(100).ok(); gam.switch_to_app(gam::APP_NAME_SHELLCHAT, security_tv.token.unwrap()).expect("couldn't raise shellchat"); diff --git a/services/status/src/mainmenu.rs b/services/status/src/mainmenu.rs index fb3435651..68fda548d 100644 --- a/services/status/src/mainmenu.rs +++ b/services/status/src/mainmenu.rs @@ -95,6 +95,14 @@ pub fn create_main_menu(keys: Arc>, status_conn: xous::CID, com: close_on_select: true, }); + menuitems.push(MenuItem { + name: String::from_str(t!("mainmenu.kbd", xous::LANG)), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::SubmenuKbd.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", xous::LANG)), action_conn: None, diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index 95e1db67e..f9f235f63 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -23,9 +23,11 @@ pub const SOC_STAGING_GW_LEN: u32 = 0x0028_0000; pub const LOADER_LOC: u32 = 0x0050_0000; // loader - base pub const LOADER_CODE_LEN: u32 = 0x0003_0000; // code region only pub const LOADER_FONT_LOC: u32 = 0x0053_0000; // should be the same as graphics-server/src/fontmap.rs/FONT_BASE -pub const LOADER_FONT_LEN: u32 = 0x0045_0000; // length of font region only +pub const LOADER_FONT_LEN: u32 = 0x0044_0000; // length of font region only pub const LOADER_TOTAL_LEN: u32 = LOADER_CODE_LEN + LOADER_FONT_LEN; // code + font +pub const EARLY_SETTINGS: u32 = 0x0097_0000; + pub const KERNEL_LOC: u32 = 0x0098_0000; // kernel start pub const KERNEL_LEN: u32 = 0x0140_0000; // max kernel length = 0xA0_0000 * 2 => half the area for backup kernel & updates