major refactor of the keyboard server

This one gets rid of a ton of awful, crufty code that was pre-std.
It also removes the following features:

- raw scancode reporting: nobody uses them, and they've never been tested.
They can be added in later if someone wants to e.g. build a MAME emulator.
- multi-listener: there is no good reason to do this on a secure system.
multi-listener is basically a keyboard logger. It's better if we just
control it to a single keyboard listener.
This commit is contained in:
bunnie 2021-08-22 17:13:36 +08:00
parent abd8eadfd8
commit 5df8275c00
4 changed files with 268 additions and 515 deletions

View file

@ -116,7 +116,7 @@ impl ContextManager {
pub fn new(xns: &xous_names::XousNames) -> Self { pub fn new(xns: &xous_names::XousNames) -> Self {
// hook the keyboard event server and have it forward keys to our local main loop // hook the keyboard event server and have it forward keys to our local main loop
let kbd = keyboard::Keyboard::new(&xns).expect("can't connect to KBD"); let kbd = keyboard::Keyboard::new(&xns).expect("can't connect to KBD");
kbd.register_listener(api::SERVER_NAME_GAM, Some(Opcode::KeyboardEvent as u32), None).expect("couldn't register for keyboard events"); kbd.register_listener(api::SERVER_NAME_GAM, Opcode::KeyboardEvent as usize);
info!("acquiring connection to IMEF..."); info!("acquiring connection to IMEF...");
let mut imef = ime_plugin_api::ImeFrontEnd::new(&xns).expect("Couldn't connect to IME front end"); let mut imef = ime_plugin_api::ImeFrontEnd::new(&xns).expect("Couldn't connect to IME front end");

View file

@ -12,121 +12,6 @@ pub struct ScanCode {
pub alt: Option<char>, pub alt: Option<char>,
} }
// maximum number of key events to track simultaneously.
pub const MAX_KEYS: usize = 16;
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default, Copy, Clone, PartialEq, Eq)]
pub struct RowCol {
pub r: u8,
pub c: u8,
}
/// RowColVec is implemented here instead of using heapless::Vec because we can't
/// derive the rkyv traits on heapless::Vec. By making a janky vector type here
/// our IPC doesn't rely on dangerous serialization techniques like casting to
/// raw u8 slices which rely on the implicit shape of packed structures...
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct RowColVec {
storage: [Option<RowCol>; MAX_KEYS],
iter: usize,
}
impl RowColVec {
pub fn new() -> Self {
RowColVec {
storage: [None; MAX_KEYS],
iter: 0
}
}
pub fn clear(&mut self) {
self.storage = [None; MAX_KEYS];
self.iter = 0;
}
pub fn len(&self) -> usize {
return MAX_KEYS
}
pub fn get(&self, i: usize) -> Option<RowCol> {
if i < MAX_KEYS {
self.storage[i]
} else {
None
}
}
pub fn set(&mut self, i: usize, data: Option<RowCol>) {
if i < MAX_KEYS {
self.storage[i]= data;
}
}
// used by the interrupt handler, we can't deal with errors anyways
pub fn add_unchecked(&mut self, key: RowCol) {
for s in self.storage.iter_mut() {
if *s == None {
*s = Some(key);
break;
}
}
}
// returns True if key is unique and added; False if already exists in storage
pub fn add_rc(&mut self, key: RowCol) -> Result<bool, xous::Error> {
// first, check if the rc is in the array
for &s in self.storage.iter() {
if let Some(rc) = s {
if rc == key {
return Ok(false)
}
}
}
// if we got here, rc was not in the arary
let mut added = false;
for s in self.storage.iter_mut() {
if *s == None {
*s = Some(key);
added = true;
break;
}
}
if added {
Ok(true)
} else {
Err(xous::Error::OutOfMemory)
}
}
// returns True if the key was removed; false if the key did not exist already
pub fn remove_rc(&mut self, key: RowCol) -> bool {
for s in self.storage.iter_mut() {
if let Some(rc) = s {
if *rc == key {
*s = None;
return true
}
}
}
return false
}
pub fn contains(&self, key: RowCol) -> bool {
for s in self.storage.iter() {
if let Some(rc) = s {
if *rc == key {
return true
}
}
}
false
}
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct KeyRawStates {
pub keydowns: RowColVec,
pub keyups: RowColVec,
}
impl KeyRawStates {
pub fn new() -> Self {
KeyRawStates {
keydowns: RowColVec::new(),
keyups: RowColVec::new(),
}
}
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum KeyMap { pub enum KeyMap {
Qwerty, Qwerty,
@ -194,6 +79,5 @@ pub(crate) enum Opcode {
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub(crate) struct KeyboardRegistration { pub(crate) struct KeyboardRegistration {
pub server_name: xous_ipc::String::<64>, pub server_name: xous_ipc::String::<64>,
pub listener_op_id: Option<u32>, pub listener_op_id: usize,
pub rawlistener_op_id: Option<u32>,
} }

View file

@ -21,21 +21,14 @@ impl Keyboard {
}) })
} }
pub fn register_listener(&self, pub fn register_listener(&self, server_name: &str, action_opcode: usize) {
// the public name of the destination server. The calling server must guarantee it has sufficient connection priveleges with xous-names to accept the keyboard's incoming connection. let kr = KeyboardRegistration {
server_name: &str,
// if Some(u32), the enum Opcode ID of the command for the incoming scancodes (adjusted already for keyup/down, repeat, shift, etc.)
listener_id: Option<u32>,
// if Some(u32), the enum Opcode ID of the command for incoming raw scancodes (just raw row/col locations and up/down)
raw_listener_id: Option<u32>) -> Result<(), xous::Error> {
let registration = KeyboardRegistration {
server_name: String::<64>::from_str(server_name), server_name: String::<64>::from_str(server_name),
listener_op_id: listener_id, listener_op_id: action_opcode
rawlistener_op_id: raw_listener_id,
}; };
let buf = Buffer::into_buf(registration).or(Err(xous::Error::InternalError))?; let buf = Buffer::into_buf(kr).unwrap();
buf.lend(self.conn, Opcode::RegisterListener.to_u32().unwrap()).map(|_| ()) buf.lend(self.conn, Opcode::RegisterListener.to_u32().unwrap())
.expect("couldn't register listener");
} }
pub fn set_vibe(&self, enable: bool) -> Result<(), xous::Error> { pub fn set_vibe(&self, enable: bool) -> Result<(), xous::Error> {

View file

@ -8,9 +8,29 @@ use log::info;
use num_traits::*; use num_traits::*;
use xous_ipc::Buffer; use xous_ipc::Buffer;
use api::{Opcode, KeyRawStates, KeyboardRegistration};
use xous::{CID, msg_scalar_unpack}; use xous::{CID, msg_scalar_unpack};
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct RowCol {
pub r: u8,
pub c: u8,
}
#[derive(Debug)]
pub (crate) struct KeyRawStates {
pub keydowns: Vec::<RowCol>,
pub keyups: Vec::<RowCol>,
}
impl KeyRawStates {
pub fn new() -> Self {
KeyRawStates {
keydowns: Vec::with_capacity(16),
keyups: Vec::with_capacity(16),
}
}
}
/// Compute the dvorak key mapping of row/col to key tuples /// Compute the dvorak key mapping of row/col to key tuples
#[allow(dead_code)] #[allow(dead_code)]
fn map_dvorak(code: RowCol) -> ScanCode { fn map_dvorak(code: RowCol) -> ScanCode {
@ -161,24 +181,25 @@ fn map_qwerty(code: RowCol) -> ScanCode {
#[cfg(any(target_os = "none", target_os = "xous"))] #[cfg(any(target_os = "none", target_os = "xous"))]
mod implementation { mod implementation {
use utralib::generated::*; use utralib::generated::*;
use crate::api::*; use crate::{RowCol, KeyRawStates, api::*};
use crate::{map_dvorak, map_qwerty}; use crate::{map_dvorak, map_qwerty};
use ticktimer_server::Ticktimer; use ticktimer_server::Ticktimer;
use xous::CID; use xous::CID;
use num_traits::ToPrimitive; use num_traits::ToPrimitive;
use susres::{RegManager, RegOrField, SuspendResume}; use susres::{RegManager, RegOrField, SuspendResume};
use std::collections::HashSet;
/// note: the code is structured to use at most 16 rows or 16 cols /// note: the code is structured to use at most 16 rows or 16 cols
const KBD_ROWS: usize = 9; const KBD_ROWS: usize = 9;
const KBD_COLS: usize = 10; const KBD_COLS: usize = 10;
pub struct Keyboard { pub(crate) struct Keyboard {
conn: CID, conn: CID,
csr: utralib::CSR<u32>, csr: utralib::CSR<u32>,
/// where the interrupt handler copies the new state /// where the interrupt handler copies the new state
new_state: RowColVec, new_state: HashSet::<RowCol>,
/// remember the last key states /// remember the last key states
last_state: RowColVec, last_state: HashSet::<RowCol>,
/// connection to the timer for real-time events /// connection to the timer for real-time events
ticktimer: Ticktimer, ticktimer: Ticktimer,
/// mapping for ScanCode translation /// mapping for ScanCode translation
@ -213,7 +234,19 @@ mod implementation {
fn handle_kbd(_irq_no: usize, arg: *mut usize) { fn handle_kbd(_irq_no: usize, arg: *mut usize) {
let kbd = unsafe { &mut *(arg as *mut Keyboard) }; let kbd = unsafe { &mut *(arg as *mut Keyboard) };
if kbd.csr.rf(utra::keyboard::EV_PENDING_KEYPRESSED) != 0 { if kbd.csr.rf(utra::keyboard::EV_PENDING_KEYPRESSED) != 0 {
kbd.new_state = kbd.kbd_getcodes(); // scan the entire key matrix and return the list of keys that are currently
// pressed as key codes. If we missed an interrupt, then we missed the key...
kbd.new_state.clear();
for r in 0..KBD_ROWS {
let cols: u16 = kbd_getrow(kbd, r as u8);
for c in 0..KBD_COLS {
if (cols & (1 << c)) != 0 {
kbd.new_state.insert(
RowCol{r: r as _, c: c as _}
);
}
}
}
kbd.csr.wfo(utra::keyboard::EV_PENDING_KEYPRESSED, 1); // clear the interrupt kbd.csr.wfo(utra::keyboard::EV_PENDING_KEYPRESSED, 1); // clear the interrupt
xous::try_send_message(kbd.conn, xous::try_send_message(kbd.conn,
@ -227,9 +260,26 @@ mod implementation {
).ok(); ).ok();
} }
} }
/// get the column activation contents of the given row
/// row is coded as a binary number, so the result of kbd_rowchange has to be decoded from a binary
/// vector of rows to a set of numbers prior to using this function
fn kbd_getrow(kbd: &Keyboard, row: u8) -> u16 {
match row {
0 => kbd.csr.rf(utra::keyboard::ROW0DAT_ROW0DAT) as u16,
1 => kbd.csr.rf(utra::keyboard::ROW1DAT_ROW1DAT) as u16,
2 => kbd.csr.rf(utra::keyboard::ROW2DAT_ROW2DAT) as u16,
3 => kbd.csr.rf(utra::keyboard::ROW3DAT_ROW3DAT) as u16,
4 => kbd.csr.rf(utra::keyboard::ROW4DAT_ROW4DAT) as u16,
5 => kbd.csr.rf(utra::keyboard::ROW5DAT_ROW5DAT) as u16,
6 => kbd.csr.rf(utra::keyboard::ROW6DAT_ROW6DAT) as u16,
7 => kbd.csr.rf(utra::keyboard::ROW7DAT_ROW7DAT) as u16,
8 => kbd.csr.rf(utra::keyboard::ROW8DAT_ROW8DAT) as u16,
_ => 0
}
}
impl Keyboard { impl Keyboard {
pub fn new(sid: xous::SID) -> Keyboard { pub(crate) fn new(sid: xous::SID) -> Keyboard {
let csr = xous::syscall::map_memory( let csr = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::keyboard::HW_KEYBOARD_BASE), xous::MemoryAddress::new(utra::keyboard::HW_KEYBOARD_BASE),
None, None,
@ -244,8 +294,8 @@ mod implementation {
let mut kbd = Keyboard { let mut kbd = Keyboard {
conn: xous::connect(sid).unwrap(), conn: xous::connect(sid).unwrap(),
csr: CSR::new(csr.as_mut_ptr() as *mut u32), csr: CSR::new(csr.as_mut_ptr() as *mut u32),
new_state: RowColVec::new(), new_state: HashSet::with_capacity(16), // pre-allocate space since this has to work in an interrupt context
last_state: RowColVec::new(), last_state: HashSet::with_capacity(16),
ticktimer, ticktimer,
map: KeyMap::Qwerty, map: KeyMap::Qwerty,
delay: 500, delay: 500,
@ -283,11 +333,11 @@ mod implementation {
kbd kbd
} }
pub fn suspend(&mut self) { pub(crate) fn suspend(&mut self) {
self.susres.suspend(); self.susres.suspend();
self.csr.wo(utra::keyboard::EV_ENABLE, 0); self.csr.wo(utra::keyboard::EV_ENABLE, 0);
} }
pub fn resume(&mut self) { pub(crate) fn resume(&mut self) {
self.susres.resume(); self.susres.resume();
// clear the keyboard state vectors -- actually, if a key was being pressed at the time of suspend // clear the keyboard state vectors -- actually, if a key was being pressed at the time of suspend
@ -304,110 +354,48 @@ mod implementation {
self.chord = [[false; KBD_COLS]; KBD_ROWS]; self.chord = [[false; KBD_COLS]; KBD_ROWS];
} }
pub fn set_map(&mut self, map: KeyMap) { pub(crate) fn set_map(&mut self, map: KeyMap) {
self.map = map; self.map = map;
} }
pub fn get_map(&self) -> KeyMap {self.map} pub(crate) fn get_map(&self) -> KeyMap {self.map}
pub fn set_repeat(&mut self, rate: u32, delay: u32) { pub(crate) fn set_repeat(&mut self, rate: u32, delay: u32) {
self.rate = rate; self.rate = rate;
self.delay = delay; self.delay = delay;
} }
pub fn set_chord_interval(&mut self, delay: u32) { pub(crate) fn set_chord_interval(&mut self, delay: u32) {
self.chord_interval = delay; self.chord_interval = delay;
} }
pub(crate) fn update(&mut self) -> KeyRawStates {
/// get the column activation contents of the given row
/// row is coded as a binary number, so the result of kbd_rowchange has to be decoded from a binary
/// vector of rows to a set of numbers prior to using this function
fn kbd_getrow(&self, row: u8) -> u16 {
match row {
0 => self.csr.rf(utra::keyboard::ROW0DAT_ROW0DAT) as u16,
1 => self.csr.rf(utra::keyboard::ROW1DAT_ROW1DAT) as u16,
2 => self.csr.rf(utra::keyboard::ROW2DAT_ROW2DAT) as u16,
3 => self.csr.rf(utra::keyboard::ROW3DAT_ROW3DAT) as u16,
4 => self.csr.rf(utra::keyboard::ROW4DAT_ROW4DAT) as u16,
5 => self.csr.rf(utra::keyboard::ROW5DAT_ROW5DAT) as u16,
6 => self.csr.rf(utra::keyboard::ROW6DAT_ROW6DAT) as u16,
7 => self.csr.rf(utra::keyboard::ROW7DAT_ROW7DAT) as u16,
8 => self.csr.rf(utra::keyboard::ROW8DAT_ROW8DAT) as u16,
_ => 0
}
}
/// scan the entire key matrix and return the list of keys that are currently
/// pressed as key codes. Return format is an array of option-wrapped RowCol
/// which is structured as (row : col), where each of row and col are a u8.
/// Option "none" means no keys were pressed during this scan.
/// This has O(N^2) time growth as number of keys are pressed; but, typically,
/// it's rare that more than two keys are pressed at once, and most of the time, none are pressed.
/// The 16-element limit is more allowing for an extremely likely worst case. On average, this will perform
/// as well as an O(N) heapless Vec, but comes with the benefit of getting rid of that dependency.
fn kbd_getcodes(&self) -> RowColVec {
let mut keys = RowColVec::new();
for r in 0..KBD_ROWS {
let cols: u16 = self.kbd_getrow(r as u8);
for c in 0..KBD_COLS {
if (cols & (1 << c)) != 0 {
// note: we could implement a check to flag if more than 16 keys were pressed within a single
// debounce quanta (5ms) at once...
// this is an unlikely scenario, so we're just going to count on ample space being the solution
// to this problem
keys.add_unchecked(RowCol{r: r as _, c: c as _});
}
}
}
keys
}
pub fn update(&mut self) -> KeyRawStates {
// EV_PENDING_KEYPRESSED effectively does an XOR of the previous keyboard state // EV_PENDING_KEYPRESSED effectively does an XOR of the previous keyboard state
// to the current state, which is why update() does not repeatedly issue results // to the current state, which is why update() does not repeatedly issue results
// for keys that are pressed & held. // for keys that are pressed & held.
log::trace!("update new_state: {:?}", self.new_state);
log::trace!("update last_state: {:?}", self.last_state);
if log::log_enabled!(log::Level::Trace) { let mut krs = KeyRawStates::new();
log::trace!("pending detected");
log::trace!("{:?}", self.new_state);
}
let new_codes = self.new_state;
let mut keydowns = RowColVec::new(); // compute the key-ups: this would be codes that are in the last_state, but not in the incoming
let mut keyups = RowColVec::new(); // new_state
for &rc in self.last_state.difference(&self.new_state) {
// check to see if there are codes in the last state that aren't in the current codes krs.keyups.push(rc);
for i in 0..self.last_state.len() {
if let Some(lastcode) = self.last_state.get(i) {
if !new_codes.contains(lastcode) {
keyups.add_rc(lastcode).unwrap();
self.last_state.set(i, None);
}
}
}
// check to see if the codes in the current set aren't already in the current codes
for i in 0..new_codes.len() {
if let Some(rc) = new_codes.get(i) {
match self.last_state.add_rc(rc) {
Ok(true) => {
keydowns.add_rc(rc).unwrap();
},
Ok(false) => {
// already in the array, don't report anything as it's not a change
},
_ => log::error!("out of key storage state in keyboard update")
}
}
} }
let krs = KeyRawStates { // compute key-downs: codes that are in the new_state, but not in last_state
keydowns, for &rc in self.new_state.difference(&self.last_state) {
keyups, krs.keydowns.push(rc);
}; }
self.last_state.clear();
for &rc in self.new_state.iter() {
self.last_state.insert(rc);
}
log::trace!("krs: {:?}", krs);
krs krs
} }
pub fn track_chord(&mut self, keyups: Option<Vec<RowCol>>, keydowns: Option<Vec<RowCol>>) -> Vec<char> { pub(crate) fn track_chord(&mut self, krs: &KeyRawStates) -> Vec<char> {
/* /*
Chording algorithm: Chording algorithm:
@ -419,12 +407,10 @@ mod implementation {
6. Return scancodes 6. Return scancodes
*/ */
let was_idle = self.chord_active == 0; let was_idle = self.chord_active == 0;
if let Some(kds) = &keydowns { for rc in krs.keydowns.iter() {
for &rc in kds.iter() {
self.chord[rc.r as usize][rc.c as usize] = true; self.chord[rc.r as usize][rc.c as usize] = true;
self.chord_active += 1; self.chord_active += 1;
} }
}
log::trace!("self.chord: {:?}", self.chord); log::trace!("self.chord: {:?}", self.chord);
let mut keystates: Vec<char> = Vec::new(); let mut keystates: Vec<char> = Vec::new();
@ -526,8 +512,7 @@ mod implementation {
log::trace!("up {}, left {}, right {}, down, {}, center, {}, space {}, esc {}, func {}", log::trace!("up {}, left {}, right {}, down, {}, center, {}, space {}, esc {}, func {}",
up, left, right, down, center, space, esc, func); up, left, right, down, center, space, esc, func);
} }
if let Some(kus) = &keyups { for rc in krs.keyups.iter() {
for &rc in kus.iter() {
self.chord[rc.r as usize][rc.c as usize] = false; self.chord[rc.r as usize][rc.c as usize] = false;
if self.chord_active > 0 { if self.chord_active > 0 {
self.chord_active -= 1; self.chord_active -= 1;
@ -535,7 +520,6 @@ mod implementation {
log::error!("received more keyups than we had keydowns!") log::error!("received more keyups than we had keydowns!")
} }
} }
}
if self.chord_active == 0 { if self.chord_active == 0 {
self.chord_captured = false; self.chord_captured = false;
} }
@ -543,7 +527,7 @@ mod implementation {
keystates keystates
} }
pub fn track_keys(&mut self, keyups: Option<Vec<RowCol>>, keydowns: Option<Vec<RowCol>>) -> Vec<char> { pub(crate) fn track_keys(&mut self, krs: &KeyRawStates) -> Vec<char> {
/* /*
"conventional" keyboard algorithm. The goals of this are to differentiate "conventional" keyboard algorithm. The goals of this are to differentiate
the cases of "shift", "alt", and "hold". the cases of "shift", "alt", and "hold".
@ -557,8 +541,7 @@ mod implementation {
let mut ks: Vec<char> = Vec::new(); let mut ks: Vec<char> = Vec::new();
// first check for shift and alt keys // first check for shift and alt keys
if let Some(kds) = &keydowns { for rc in krs.keydowns.iter() {
for &rc in kds.iter() {
match self.map { match self.map {
KeyMap::Azerty => { KeyMap::Azerty => {
if (rc.r == 8) && (rc.c == 5) { // left shift (orange) if (rc.r == 8) && (rc.c == 5) { // left shift (orange)
@ -589,11 +572,8 @@ mod implementation {
} }
} }
} }
} let mut keyups_noshift: Vec::<RowCol> = Vec::new();
let keyups_noshift: Option<Vec<RowCol>> = for &rc in krs.keyups.iter() {
if let Some(kus) = &keyups {
let mut ku_ns: Vec<RowCol> = Vec::new();
for &rc in kus.iter() {
match self.map { match self.map {
KeyMap::Azerty => { KeyMap::Azerty => {
if (rc.r == 8) && (rc.c == 5) { // left shift (orange) if (rc.r == 8) && (rc.c == 5) { // left shift (orange)
@ -607,7 +587,7 @@ mod implementation {
} }
self.shift_down = false; self.shift_down = false;
} else { } else {
ku_ns.push(RowCol{r: rc.r as _, c: rc.c as _}); keyups_noshift.push(RowCol{r: rc.r as _, c: rc.c as _});
} }
}, },
_ => { // the rest just have one color of shift _ => { // the rest just have one color of shift
@ -621,21 +601,17 @@ mod implementation {
self.shift_down = false; self.shift_down = false;
} else { } else {
//info!("adding non-shift entry {:?}", rc); //info!("adding non-shift entry {:?}", rc);
ku_ns.push(RowCol{r: rc.r as _, c: rc.c as _}); keyups_noshift.push(RowCol{r: rc.r as _, c: rc.c as _});
} }
} }
} }
} }
Some(ku_ns)
} else {
None
};
// interpret keys in the context of the shift/alt modifiers // interpret keys in the context of the shift/alt modifiers
if let Some(kds) = &keydowns { if !krs.keydowns.is_empty() {
self.chord_timestamp = self.ticktimer.elapsed_ms(); self.chord_timestamp = self.ticktimer.elapsed_ms();
// if more than one is held, the key that gets picked for the repeat function is arbitrary! }
for &rc in kds.iter() { for &rc in krs.keydowns.iter() {
let code = match self.map { let code = match self.map {
KeyMap::Qwerty => map_qwerty(rc), KeyMap::Qwerty => map_qwerty(rc),
KeyMap::Dvorak => map_dvorak(rc), KeyMap::Dvorak => map_dvorak(rc),
@ -647,7 +623,7 @@ mod implementation {
} }
} }
} }
}
let now = self.ticktimer.elapsed_ms(); let now = self.ticktimer.elapsed_ms();
let hold: bool; let hold: bool;
if (now - self.chord_timestamp) >= self.delay as u64 { if (now - self.chord_timestamp) >= self.delay as u64 {
@ -659,8 +635,7 @@ mod implementation {
hold = false; hold = false;
} }
if let Some(kus) = &keyups_noshift { for &rc in keyups_noshift.iter() {
for &rc in kus.iter() {
// info!("interpreting keyups_noshift entry {:?}", rc); // info!("interpreting keyups_noshift entry {:?}", rc);
let code = match self.map { let code = match self.map {
KeyMap::Qwerty => map_qwerty(rc), KeyMap::Qwerty => map_qwerty(rc),
@ -732,7 +707,6 @@ mod implementation {
} }
} }
} }
}
// if we're in a key hold state, we've passed the rate timestamp point, and there's a repeating key defined // if we're in a key hold state, we've passed the rate timestamp point, and there's a repeating key defined
if hold && ((now - self.rate_timestamp) >= self.rate as u64) && self.repeating_key.is_some() { if hold && ((now - self.rate_timestamp) >= self.rate as u64) && self.repeating_key.is_some() {
@ -750,11 +724,10 @@ mod implementation {
// a stub to try to avoid breaking hosted mode for as long as possible. // a stub to try to avoid breaking hosted mode for as long as possible.
#[cfg(not(any(target_os = "none", target_os = "xous")))] #[cfg(not(any(target_os = "none", target_os = "xous")))]
mod implementation { mod implementation {
use crate::api::*; use crate::*;
//use crate::{map_dvorak, map_qwerty};
#[allow(dead_code)] #[allow(dead_code)]
pub struct Keyboard { pub(crate) struct Keyboard {
cid: xous::CID, cid: xous::CID,
map: KeyMap, map: KeyMap,
rate: u32, rate: u32,
@ -786,11 +759,11 @@ mod implementation {
KeyRawStates::new() KeyRawStates::new()
} }
pub fn track_chord(&mut self, _keyups: Option<Vec<RowCol>>, _keydowns: Option<Vec<RowCol>>) -> Vec<char> { pub fn track_chord(&mut self, _krs: &KeyRawStates) -> Vec<char> {
Vec::new() Vec::new()
} }
pub fn track_keys(&mut self, _keyups: Option<Vec<RowCol>>, _keydowns: Option<Vec<RowCol>>) -> Vec<char> { pub fn track_keys(&mut self, _rs: &KeyRawStates) -> Vec<char> {
Vec::new() Vec::new()
} }
@ -805,24 +778,6 @@ mod implementation {
} }
} }
// for now we restrict to 1: we delegate authentication to the primary listener, that is, the GAM.
const MAX_LISTENERS: usize = 1;
fn send_rawstates(cb_conns: &mut [Option<(CID, u32)>; MAX_LISTENERS], krs: &KeyRawStates) {
for maybe_conn in cb_conns.iter_mut() {
if let Some((conn, opcode)) = maybe_conn {
let buf = Buffer::into_buf(*krs).unwrap();
match buf.lend(*conn, *opcode) {
Err(xous::Error::ServerNotFound) => {
*maybe_conn = None
},
Ok(xous::Result::Ok) => {},
_ => panic!("unhandled error or result in callback processing"),
}
}
}
}
#[xous::xous_main] #[xous::xous_main]
fn xmain() -> ! { fn xmain() -> ! {
use crate::implementation::Keyboard; use crate::implementation::Keyboard;
@ -847,11 +802,8 @@ fn xmain() -> ! {
let sr_cid = xous::connect(kbd_sid).expect("couldn't create suspend callback connection"); let sr_cid = xous::connect(kbd_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(&xns, Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); let mut susres = susres::Susres::new(&xns, Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object");
// reduce connection count to 1, but leave the option to add more later let mut listener_conn: Option<CID> = None;
// for now, we only expect to ever foward events to the GAM, which is capable of doing authentication let mut listener_op: Option<usize> = None;
// on our behalf.
let mut normal_conns: [Option<(CID, u32)>; MAX_LISTENERS] = [None; {MAX_LISTENERS}];
let mut raw_conns: [Option<(CID, u32)>; MAX_LISTENERS] = [None; {MAX_LISTENERS}];
let mut vibe = false; let mut vibe = false;
let llio = llio::Llio::new(&xns).unwrap(); let llio = llio::Llio::new(&xns).unwrap();
@ -872,40 +824,16 @@ fn xmain() -> ! {
}), }),
Some(Opcode::RegisterListener) => { Some(Opcode::RegisterListener) => {
let buffer = unsafe{Buffer::from_memory_message(msg.body.memory_message().unwrap())}; let buffer = unsafe{Buffer::from_memory_message(msg.body.memory_message().unwrap())};
let registration = buffer.to_original::<KeyboardRegistration, _>().unwrap(); let kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
let cid = match xns.request_connection_blocking(registration.server_name.as_str().unwrap()) { match xns.request_connection_blocking(kr.server_name.as_str()) {
Ok(id) => id, Ok(cid) => {
_ => { listener_conn = Some(cid);
log::error!("register listener could not connect to {}, ignoring", registration.server_name); listener_op = Some(kr.listener_op_id as usize);
// TODO: maybe convert this to something that returns an error code.
// or maybe not? nobody /should/ be trying to eavesdrop on the keyboard server, after all, right? amiright?
continue;
} }
}; Err(e) => {
if let Some(op) = registration.listener_op_id { log::error!("couldn't connect to listener: {:?}", e);
let mut found = false; listener_conn = None;
for entry in normal_conns.iter_mut() { listener_op = None;
if *entry == None {
*entry = Some((cid, op));
found = true;
break;
}
}
if !found {
log::error!("RegisterListener ran out of space registering scancode callback");
}
}
if let Some(op) = registration.rawlistener_op_id {
let mut found = false;
for entry in raw_conns.iter_mut() {
if *entry == None {
*entry = Some((cid, op));
found = true;
break;
}
}
if !found {
log::error!("RegisterListener ran out of space registering rawcode callback");
} }
} }
}, },
@ -924,104 +852,52 @@ fn xmain() -> ! {
} else { } else {
'\u{0000}' '\u{0000}'
}; };
info!("injecting emulation key press '{}'", key); log::info!("got inject key, listener_conn: {:?}", listener_conn);
for maybe_conn in normal_conns.iter_mut() { if let Some(conn) = listener_conn {
if let Some((conn, opcode)) = maybe_conn { info!("injecting key '{}'", key); // always be noisy about this, it's an exploit path
match xous::send_message(*conn, xous::send_message(conn,
xous::Message::new_scalar(*opcode as usize, xous::Message::new_scalar(listener_op.unwrap(),
key as u32 as usize, key as u32 as usize,
'\u{0000}' as u32 as usize, '\u{0000}' as u32 as usize,
'\u{0000}' as u32 as usize, '\u{0000}' as u32 as usize,
'\u{0000}' as u32 as usize, '\u{0000}' as u32 as usize,
)) { )
Err(xous::Error::ServerNotFound) => { ).unwrap();
*maybe_conn = None
},
Ok(xous::Result::Ok) => {},
_ => log::error!("unhandled error in key event sending")
}
}
} }
}), }),
Some(Opcode::HandlerTrigger) => { Some(Opcode::HandlerTrigger) => {
let rawstates = kbd.update(); let rawstates = kbd.update();
// send rawstates on to rawstate listeners
send_rawstates(&mut raw_conns, &rawstates);
///// TODO: the comment below predates the addition of libstd to Xous. We need to fix this still,
///// for now we have just refactored out the heapless crate.
// GROSS: we copy our IPC-compatible RowColVec type into a heapless::Vec for further processing
// this code can probably be cleaned up and improved quite a bit to reduce CPU time.
// We don't use heapless::Vec for the IPC because we can't serialize the object with a trait natively
// which leaves us with ugly/dangerous slice-of-u8 cast techniques and/or inefficient serialization
// methods that rely on effectively a substantially similar intermediate array-based implementation.
// We retain the use of the "Vec" type here because the Vec type has some nice functions like iterators,
// and push(), len() etc. which doesn't really make sense to re-implement. But, maybe someone much
// more clever than I could do extend RowColVec to have these feature and get rid of this ugly copy
// step and make the rest of this routine operate natively on RowColVec types....
let mut keyups_core: Vec<RowCol> = Vec::new();
let mut keydowns_core: Vec<RowCol> = Vec::new();
for i in 0..rawstates.keyups.len() {
if let Some(rc) = rawstates.keyups.get(i) {
keyups_core.push(rc);
}
}
for i in 0..rawstates.keydowns.len() {
if let Some(rc) = rawstates.keydowns.get(i) {
keydowns_core.push(rc);
}
}
let keyups = if keyups_core.len() > 0 {
Some(keyups_core)
} else {
None
};
let keydowns = if keydowns_core.len() > 0 {
Some(keydowns_core)
} else {
None
};
// interpret scancodes // interpret scancodes
// the track_* functions track the keyup/keydowns to modify keys with shift, hold, and chord state // the track_* functions track the keyup/keydowns to modify keys with shift, hold, and chord state
let kc: Vec<char> = match kbd.get_map() { let kc: Vec<char> = match kbd.get_map() {
KeyMap::Braille => { KeyMap::Braille => {
kbd.track_chord(keyups, keydowns) kbd.track_chord(&rawstates)
}, },
_ => { _ => {
kbd.track_keys(keyups, keydowns) kbd.track_keys(&rawstates)
}, },
}; };
// send keys, if any // send keys, if any
if kc.len() > 0 { if kc.len() > 0 && listener_conn.is_some() && listener_op.is_some() {
if vibe { if vibe {
llio.vibe(llio::VibePattern::Short).unwrap(); llio.vibe(llio::VibePattern::Short).unwrap();
} }
let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}']; let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}'];
for i in 0..kc.len() { for i in 0..kc.len() {
// info!("sending key '{}'", kc[i]);
keys[i] = kc[i]; keys[i] = kc[i];
} }
log::trace!("sending keys {:?}", keys);
for maybe_conn in normal_conns.iter_mut() { xous::send_message(listener_conn.unwrap(),
if let Some((conn, opcode)) = maybe_conn { xous::Message::new_scalar(
match xous::send_message(*conn, listener_op.unwrap(),
xous::Message::new_scalar(*opcode as usize,
keys[0] as u32 as usize, keys[0] as u32 as usize,
keys[1] as u32 as usize, keys[1] as u32 as usize,
keys[2] as u32 as usize, keys[2] as u32 as usize,
keys[3] as u32 as usize, keys[3] as u32 as usize,
)) { )
Err(xous::Error::ServerNotFound) => { ).expect("couldn't send key codes to listener");
*maybe_conn = None
},
Ok(xous::Result::Ok) => {},
_ => log::error!("unhandled error in key event sending")
}
}
}
} }
}, },
None => {log::error!("couldn't convert opcode"); break} None => {log::error!("couldn't convert opcode"); break}