format services/keyboard

exceptions are made for the mappings/ modules, because they
are lookup tables and benefit from strict line-by-line ordering
with wide columns.
This commit is contained in:
bunnie 2024-01-14 22:24:08 +08:00
parent 4a292c29a9
commit a994cbd447
4 changed files with 330 additions and 289 deletions

View file

@ -1,6 +1,6 @@
use std::fmt::Display;
pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_";
pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_";
#[derive(Debug, Default, Copy, Clone)]
pub struct ScanCode {
@ -83,7 +83,8 @@ pub(crate) enum Opcode {
/// set repeat delay, rate; both in ms
SetRepeat = 4, //(u32, u32),
/// set chording interval (how long to wait for all keydowns to happen before interpreting as a chord), in ms (for braille keyboards)
/// set chording interval (how long to wait for all keydowns to happen before interpreting as a chord),
/// in ms (for braille keyboards)
SetChordInterval = 5, //(u32),
/// used by host mode emulation and debug UART to inject keys
@ -107,7 +108,7 @@ pub(crate) enum Opcode {
// which is the GAM.
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub(crate) struct KeyboardRegistration {
pub server_name: xous_ipc::String::<64>,
pub server_name: xous_ipc::String<64>,
pub listener_op_id: usize,
}
@ -118,21 +119,14 @@ pub struct RowCol {
}
impl RowCol {
#[allow(dead_code)]
pub fn new(r: u8, c: u8) -> RowCol {
RowCol { r, c }
}
pub fn new(r: u8, c: u8) -> RowCol { RowCol { r, c } }
}
#[derive(Debug)]
pub struct KeyRawStates {
pub keydowns: Vec::<RowCol>,
pub keyups: Vec::<RowCol>,
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),
}
}
pub fn new() -> Self { KeyRawStates { keydowns: Vec::with_capacity(16), keyups: Vec::with_capacity(16) } }
}

View file

@ -16,78 +16,69 @@ impl Keyboard {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(api::SERVER_NAME_KBD).expect("Can't connect to KBD");
Ok(Keyboard {
conn,
})
Ok(Keyboard { conn })
}
pub fn register_listener(&self, server_name: &str, action_opcode: usize) {
let kr = KeyboardRegistration {
server_name: String::<64>::from_str(server_name),
listener_op_id: action_opcode
listener_op_id: action_opcode,
};
let buf = Buffer::into_buf(kr).unwrap();
buf.lend(self.conn, Opcode::RegisterListener.to_u32().unwrap())
.expect("couldn't register listener");
buf.lend(self.conn, Opcode::RegisterListener.to_u32().unwrap()).expect("couldn't register listener");
}
pub fn register_raw_listener(&self, server_name: &str, action_opcode: usize) {
let kr = KeyboardRegistration {
server_name: String::<64>::from_str(server_name),
listener_op_id: action_opcode
listener_op_id: action_opcode,
};
let buf = Buffer::into_buf(kr).unwrap();
buf.lend(self.conn, Opcode::RegisterRawListener.to_u32().unwrap())
.expect("couldn't register listener");
.expect("couldn't register listener");
}
pub fn register_observer(&self, server_name: &str, action_opcode: usize) {
let kr = KeyboardRegistration {
server_name: String::<64>::from_str(server_name),
listener_op_id: action_opcode
listener_op_id: action_opcode,
};
let buf = Buffer::into_buf(kr).unwrap();
buf.lend(self.conn, Opcode::RegisterKeyObserver.to_u32().unwrap())
.expect("couldn't register listener");
.expect("couldn't register listener");
}
pub fn set_vibe(&self, enable: bool) -> Result<(), xous::Error> {
let ena =
if enable { 1 }
else { 0 };
send_message(self.conn,
Message::new_scalar(Opcode::Vibe.to_usize().unwrap(),
ena, 0, 0, 0,)
).map(|_| ())
let ena = if enable { 1 } else { 0 };
send_message(self.conn, Message::new_scalar(Opcode::Vibe.to_usize().unwrap(), ena, 0, 0, 0))
.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(|_| ())
send_message(
self.conn,
Message::new_scalar(Opcode::SelectKeyMap.to_usize().unwrap(), map.into(), 0, 0, 0),
)
.map(|_| ())
}
pub fn get_keymap(&self) -> Result<KeyMap, xous::Error> {
match send_message(self.conn,
Message::new_blocking_scalar(Opcode::GetKeyMap.to_usize().unwrap(),
0, 0, 0, 0)
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)
Ok(xous::Result::Scalar1(code)) => Ok(code.into()),
_ => Err(xous::Error::InternalError),
}
}
/// Blocks until a key is hit. Does not block the keyboard server, just the caller.
/// Returns a `Vec::<char>`, as the user can press more than one key at a time.
/// The specific order of a simultaneous key hit event is not defined.
pub fn get_keys_blocking(&self) -> Vec<char> {
match send_message(self.conn,
Message::new_blocking_scalar(
Opcode::BlockingKeyListener.to_usize().unwrap(),
0, 0, 0, 0
)
match send_message(
self.conn,
Message::new_blocking_scalar(Opcode::BlockingKeyListener.to_usize().unwrap(), 0, 0, 0, 0),
) {
Ok(xous::Result::Scalar2(k1, k2)) => {
let mut ret = Vec::<char>::new();
@ -99,28 +90,31 @@ impl Keyboard {
}
ret
}
Ok(_) | Err(_) => panic!("internal error: Incorrect return type")
Ok(_) | Err(_) => panic!("internal error: Incorrect return type"),
}
}
/// Reveal the connection ID for use with unsafe FFI calls
pub fn conn(&self) -> xous::CID { self.conn }
#[cfg(not(target_os = "xous"))]
pub fn hostmode_inject_key(&self, c: char) {
send_message(self.conn,
Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(),
c as u32 as usize, 0, 0, 0
)).unwrap();
send_message(
self.conn,
Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), c as u32 as usize, 0, 0, 0),
)
.unwrap();
}
/// This is used to shove keys into the keyboard module as if you were typing on the
/// physical keyboard.
#[cfg(feature="inject-api")]
#[cfg(feature = "inject-api")]
pub fn inject_key(&self, c: char) {
send_message(self.conn,
Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(),
c as u32 as usize, 0, 0, 0
)).unwrap();
send_message(
self.conn,
Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), c as u32 as usize, 0, 0, 0),
)
.unwrap();
}
}
@ -128,9 +122,12 @@ use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Keyboard {
fn drop(&mut self) {
// now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
// now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using
// the connection.
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();}
unsafe {
xous::disconnect(self.conn).unwrap();
}
}
}
}

View file

@ -5,26 +5,28 @@ mod api;
use api::*;
mod mappings;
use log::info;
use num_traits::*;
use xous_ipc::Buffer;
use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack, MessageSender};
#[cfg(feature="rawserial")]
#[cfg(feature = "rawserial")]
use std::collections::VecDeque;
#[cfg(feature="rawserial")]
use log::info;
use num_traits::*;
use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack, MessageSender, CID};
use xous_ipc::Buffer;
#[cfg(feature = "rawserial")]
const BLOCKING_QUEUE_LEN: usize = 128;
#[cfg(any(feature="precursor", feature="renode"))]
#[cfg(any(feature = "precursor", feature = "renode"))]
mod implementation {
use utralib::generated::*;
use crate::{RowCol, KeyRawStates, api::*};
use crate::mappings::*;
use ticktimer_server::Ticktimer;
use xous::CID;
use std::collections::HashSet;
use num_traits::ToPrimitive;
use susres::{RegManager, RegOrField, SuspendResume};
use std::collections::HashSet;
use ticktimer_server::Ticktimer;
use utralib::generated::*;
use xous::CID;
use crate::mappings::*;
use crate::{api::*, KeyRawStates, RowCol};
/// note: the code is structured to use at most 16 rows or 16 cols
const KBD_ROWS: usize = 9;
@ -34,9 +36,9 @@ mod implementation {
conn: CID,
csr: utralib::CSR<u32>,
/// where the interrupt handler copies the new state
new_state: HashSet::<RowCol>,
new_state: HashSet<RowCol>,
/// remember the last key states
last_state: HashSet::<RowCol>,
last_state: HashSet<RowCol>,
/// connection to the timer for real-time events
ticktimer: Ticktimer,
/// mapping for ScanCode translation
@ -63,9 +65,10 @@ mod implementation {
chord: [[bool; KBD_COLS]; KBD_ROWS],
/// memoize number of keys that have been pressed
chord_active: u32,
/// indicate if the chord has been captured. Once captured, further presses are ignored, until all keys are let up.
/// 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}>,
susres: RegManager<{ utra::keyboard::KEYBOARD_NUMREGS }>,
/// a field used for debugging various keyboard issues, especially with the interrupt handler
pub debug: usize,
/// access to settings stored in the first few sectors of FLASH
@ -84,23 +87,32 @@ mod implementation {
if cols != 0 {
for c in 0..KBD_COLS {
if (cols & (1 << c)) != 0 {
kbd.new_state.insert(
RowCol{r: r as _, c: c as _}
);
kbd.new_state.insert(RowCol { r: r as _, c: c as _ });
}
}
}
}
xous::try_send_message(kbd.conn,
xous::Message::new_scalar(Opcode::HandlerTrigger.to_usize().unwrap(), 0, 0, 0, 0)).ok();
xous::try_send_message(
kbd.conn,
xous::Message::new_scalar(Opcode::HandlerTrigger.to_usize().unwrap(), 0, 0, 0, 0),
)
.ok();
}
if kbd.csr.rf(utra::keyboard::EV_PENDING_INJECT) != 0 {
loop {
let char_reg = kbd.csr.r(utra::keyboard::UART_CHAR);
if char_reg & kbd.csr.ms(utra::keyboard::UART_CHAR_STB, 1) != 0 {
xous::try_send_message(kbd.conn,
xous::Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), (char_reg & 0xff) as _, 0, 0, 0)
).ok();
xous::try_send_message(
kbd.conn,
xous::Message::new_scalar(
Opcode::InjectKey.to_usize().unwrap(),
(char_reg & 0xff) as _,
0,
0,
0,
),
)
.ok();
kbd.debug += 1;
} else {
break;
@ -123,7 +135,7 @@ mod implementation {
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
_ => 0,
}
}
@ -147,12 +159,14 @@ mod implementation {
let default_map = if cfg!(feature = "braille") {
KeyMap::Braille
} else {
// 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.
// 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 kb_raw = ea.get_keymap().expect("cannot fetch keymap from early settings");
let map = KeyMap::from(kb_raw);
map
@ -161,7 +175,8 @@ mod implementation {
Keyboard {
conn: xous::connect(sid).unwrap(),
csr: CSR::new(csr.as_mut_ptr() as *mut u32),
new_state: HashSet::with_capacity(16), // pre-allocate space since this has to work in an interrupt context
new_state: HashSet::with_capacity(16), /* pre-allocate space since this has to work in an
* interrupt context */
last_state: HashSet::with_capacity(16),
ticktimer,
map: default_map,
@ -192,9 +207,10 @@ mod implementation {
)
.expect("couldn't claim irq");
self.csr.wo(utra::keyboard::EV_PENDING, self.csr.r(utra::keyboard::EV_PENDING)); // clear in case it's pending for some reason
self.csr.wo(utra::keyboard::EV_ENABLE,
self.csr.ms(utra::keyboard::EV_ENABLE_KEYPRESSED, 1) |
self.csr.ms(utra::keyboard::EV_ENABLE_INJECT, 1)
self.csr.wo(
utra::keyboard::EV_ENABLE,
self.csr.ms(utra::keyboard::EV_ENABLE_KEYPRESSED, 1)
| self.csr.ms(utra::keyboard::EV_ENABLE_INJECT, 1),
);
self.susres.push_fixed_value(RegOrField::Reg(utra::keyboard::EV_PENDING), 0xFFFF_FFFF);
@ -205,6 +221,7 @@ mod implementation {
self.susres.suspend();
self.csr.wo(utra::keyboard::EV_ENABLE, 0);
}
pub(crate) fn resume(&mut self) {
self.susres.resume();
@ -224,9 +241,10 @@ mod implementation {
// ensure interrupts are re-enabled -- this could /shouldn't/ be necessary but we're having
// some strange resume behavior, trying to see if this resolves it.
self.csr.wo(utra::keyboard::EV_PENDING, self.csr.r(utra::keyboard::EV_PENDING));
self.csr.wo(utra::keyboard::EV_ENABLE,
self.csr.ms(utra::keyboard::EV_ENABLE_KEYPRESSED, 1) |
self.csr.ms(utra::keyboard::EV_ENABLE_INJECT, 1)
self.csr.wo(
utra::keyboard::EV_ENABLE,
self.csr.ms(utra::keyboard::EV_ENABLE_KEYPRESSED, 1)
| self.csr.ms(utra::keyboard::EV_ENABLE_INJECT, 1),
);
}
@ -234,21 +252,21 @@ mod implementation {
self.early_settings.set_keymap(map.into()).expect("cannot set early keymap");
self.map = map;
}
pub(crate) fn get_map(&mut self) -> KeyMap {
let kb_raw = self.early_settings.get_keymap().expect("cannot fetch early keymap");
self.map = KeyMap::from(kb_raw);
self.map
}
pub(crate) fn set_repeat(&mut self, rate: u32, delay: u32) {
self.rate = rate;
self.delay = delay;
}
pub(crate) fn set_chord_interval(&mut self, delay: u32) {
self.chord_interval = delay;
}
pub(crate) fn get_repeat_check_interval(&self) -> u32 {
self.rate
}
pub(crate) fn set_chord_interval(&mut self, delay: u32) { self.chord_interval = delay; }
pub(crate) fn get_repeat_check_interval(&self) -> u32 { self.rate }
pub(crate) fn poll(&mut self) {
// disable the interrupt while we're polling, to avoid a race condition...
@ -259,9 +277,7 @@ mod implementation {
if cols != 0 {
for c in 0..KBD_COLS {
if (cols & (1 << c)) != 0 {
self.new_state.insert(
RowCol{r: r as _, c: c as _}
);
self.new_state.insert(RowCol { r: r as _, c: c as _ });
}
}
}
@ -328,7 +344,10 @@ mod implementation {
self.chord_timestamp = now; // record the beginning of the chord active interval
}
if self.chord_active != 0 && ((now - self.chord_timestamp) >= self.chord_interval as u64) && !self.chord_captured {
if self.chord_active != 0
&& ((now - self.chord_timestamp) >= self.chord_interval as u64)
&& !self.chord_captured
{
self.chord_captured = true;
log::trace!("interpreting chords");
// extract chord state
@ -341,12 +360,12 @@ mod implementation {
2 5
*/
/*
7/5 0/1 1/2 5/7 4/8 8/6
2/3 2/3
8/0 6/4 3/9
8/3 5/2 3/6
8/2
*/
7/5 0/1 1/2 5/7 4/8 8/6
2/3 2/3
8/0 6/4 3/9
8/3 5/2 3/6
8/2
*/
let keys: [bool; 6] = [
self.chord[1][2],
self.chord[0][1],
@ -402,30 +421,55 @@ mod implementation {
}
let up = self.chord[6][4];
if up { keystates.push('↑'); }
if up {
keystates.push('↑');
}
let left = self.chord[8][3];
if left { keystates.push('←'); }
if left {
keystates.push('←');
}
let right = self.chord[3][6];
if right { keystates.push('→'); }
if right {
keystates.push('→');
}
let down = self.chord[8][2];
if down { keystates.push('↓'); }
if down {
keystates.push('↓');
}
let center = self.chord[5][2];
if center { keystates.push('∴'); }
if center {
keystates.push('∴');
}
let space = self.chord[2][3];
if space { keystates.push(' '); }
if space {
keystates.push(' ');
}
let esc = self.chord[8][0];
let bs: char = 0x8_u8.into(); // back space
if esc { keystates.push(bs); }
let bs: char = 0x8_u8.into(); // back space
if esc {
keystates.push(bs);
}
let func = self.chord[3][9];
let cr: char = 0xd_u8.into(); // carriage return
if func { keystates.push(cr); }
let cr: char = 0xd_u8.into(); // carriage return
if func {
keystates.push(cr);
}
log::debug!("up {}, left {}, right {}, down, {}, center, {}, space {}, esc {}, func {}",
up, left, right, down, center, space, esc, func);
log::debug!(
"up {}, left {}, right {}, down, {}, center, {}, space {}, esc {}, func {}",
up,
left,
right,
down,
center,
space,
esc,
func
);
}
for rc in krs.keyups.iter() {
self.chord[rc.r as usize][rc.c as usize] = false;
@ -444,36 +488,39 @@ mod implementation {
pub(crate) fn track_keys(&mut self, krs: &KeyRawStates) -> Vec<char> {
/*
"conventional" keyboard algorithm. The goals of this are to differentiate
the cases of "shift", "alt", and "hold".
"conventional" keyboard algorithm. The goals of this are to differentiate
the cases of "shift", "alt", and "hold".
thus, we check for the special-case of shift/alt in the keydowns/keyups vectors, and
track them as separate modifiers
thus, we check for the special-case of shift/alt in the keydowns/keyups vectors, and
track them as separate modifiers
then for all others, we note the down time, and compare it to the current time
to determine if a "hold" modifier applies
*/
then for all others, we note the down time, and compare it to the current time
to determine if a "hold" modifier applies
*/
let mut ks: Vec<char> = Vec::new();
// first check for shift and alt keys
for rc in krs.keydowns.iter() {
match self.map {
KeyMap::Azerty => {
if (rc.r == 8) && (rc.c == 5) { // left shift (orange)
if (rc.r == 8) && (rc.c == 5) {
// left shift (orange)
if self.alt_up == false {
self.alt_down = true;
} else {
self.alt_up = false;
}
} else if (rc.r == 8) && (rc.c == 9) { // right shift (yellow)
} else if (rc.r == 8) && (rc.c == 9) {
// right shift (yellow)
if self.shift_up == false {
self.shift_down = true;
} else {
self.shift_up = false;
}
}
},
_ => { // the rest just have one color of shift
}
_ => {
// the rest just have one color of shift
if ((rc.r == 8) && (rc.c == 5)) || ((rc.r == 8) && (rc.c == 9)) {
// if the shift key was tapped twice, remove the shift modifier
if self.shift_up == false {
@ -487,27 +534,31 @@ mod implementation {
}
}
}
let mut keyups_noshift: Vec::<RowCol> = Vec::new();
let mut keyups_noshift: Vec<RowCol> = Vec::new();
for &rc in krs.keyups.iter() {
match self.map {
KeyMap::Azerty => {
if (rc.r == 8) && (rc.c == 5) { // left shift (orange)
if (rc.r == 8) && (rc.c == 5) {
// left shift (orange)
if self.alt_down {
self.alt_up = true;
}
self.alt_down = false;
} else if (rc.r == 8) && (rc.c == 9) { // right shift (yellow)
} else if (rc.r == 8) && (rc.c == 9) {
// right shift (yellow)
if self.shift_down {
self.shift_up = true;
}
self.shift_down = false;
} else {
keyups_noshift.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
if ((rc.r == 8) && (rc.c == 5)) || ((rc.r == 8) && (rc.c == 9)) {
// only set the shift-up if we didn't previously clear it with a double-tap of shift
// only set the shift-up if we didn't previously clear it with a double-tap of
// shift
if self.shift_down {
//info!("shift up true");
self.shift_up = true;
@ -516,7 +567,7 @@ mod implementation {
self.shift_down = false;
} else {
//info!("adding non-shift entry {:?}", rc);
keyups_noshift.push(RowCol{r: rc.r as _, c: rc.c as _});
keyups_noshift.push(RowCol { r: rc.r as _, c: rc.c as _ });
}
}
}
@ -532,11 +583,13 @@ mod implementation {
KeyMap::Dvorak => map_dvorak(rc),
KeyMap::Azerty => map_azerty(rc),
KeyMap::Qwertz => map_qwertz(rc),
_ => ScanCode {key: None, shift: None, hold: None, alt: None},
_ => ScanCode { key: None, shift: None, hold: None, alt: None },
};
if code.hold == None
&& !((rc.r == 5) && (rc.c == 2)) // scan code for the menu key
{ // if there isn't a pre-defined meaning if the key is held *and* it's not the menu key: it's a repeating key
if code.hold == None && !((rc.r == 5) && (rc.c == 2))
// scan code for the menu key
{
// if there isn't a pre-defined meaning if the key is held *and* it's not the menu key:
// it's a repeating key
if let Some(key) = code.key {
self.repeating_key = Some(key);
}
@ -561,7 +614,7 @@ mod implementation {
KeyMap::Dvorak => map_dvorak(rc),
KeyMap::Azerty => map_azerty(rc),
KeyMap::Qwertz => map_qwertz(rc),
_ => ScanCode {key: None, shift: None, hold: None, alt: None},
_ => ScanCode { key: None, shift: None, hold: None, alt: None },
};
// delete the key repeat if there is one
if code.hold == None {
@ -603,7 +656,7 @@ mod implementation {
ks.push(keycode);
}
}
},
}
_ => {
if self.shift_down || self.alt_down || self.shift_up || self.alt_up {
if let Some(shiftcode) = code.shift {
@ -629,7 +682,8 @@ 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() {
self.rate_timestamp = now;
if let Some(repeatkey) = self.repeating_key {
@ -639,9 +693,8 @@ mod implementation {
ks
}
pub fn is_repeating_key(&self) -> bool {
self.repeating_key.is_some()
}
pub fn is_repeating_key(&self) -> bool { self.repeating_key.is_some() }
}
}
@ -671,44 +724,34 @@ mod implementation {
debug: 0,
}
}
pub fn init(&mut self) {}
pub fn suspend(&self) {
}
pub fn resume(&self) {
}
pub fn set_map(&mut self, map: KeyMap) {
self.map = map;
}
pub fn get_map(&self) -> KeyMap {self.map}
pub fn suspend(&self) {}
pub fn update(&self) -> KeyRawStates {
KeyRawStates::new()
}
pub fn resume(&self) {}
pub fn track_chord(&mut self, _krs: &KeyRawStates) -> Vec<char> {
Vec::new()
}
pub fn set_map(&mut self, map: KeyMap) { self.map = map; }
pub fn track_keys(&mut self, _rs: &KeyRawStates) -> Vec<char> {
Vec::new()
}
pub fn get_map(&self) -> KeyMap { self.map }
pub fn update(&self) -> KeyRawStates { KeyRawStates::new() }
pub fn track_chord(&mut self, _krs: &KeyRawStates) -> Vec<char> { Vec::new() }
pub fn track_keys(&mut self, _rs: &KeyRawStates) -> Vec<char> { Vec::new() }
pub fn set_repeat(&mut self, rate: u32, delay: u32) {
self.rate = rate;
self.delay = delay;
}
pub fn set_chord_interval(&mut self, delay: u32) {
self.chord_interval = delay;
}
pub fn set_chord_interval(&mut self, delay: u32) { self.chord_interval = delay; }
pub fn is_repeating_key(&self) -> bool { false }
pub(crate) fn get_repeat_check_interval(&self) -> u32 { self.rate }
pub fn is_repeating_key(&self) -> bool {
false
}
pub(crate) fn get_repeat_check_interval(&self) -> u32 {
self.rate
}
pub(crate) fn poll(&mut self) {}
}
}
@ -727,9 +770,9 @@ fn main() -> ! {
// - status sub system (for setting the layout, autobacklight feature)
// - USB (for getting layout)
// - Preference manager
#[cfg(all(any(feature="precursor", feature="renode"), not(feature="dvt")))]
#[cfg(all(any(feature = "precursor", feature = "renode"), not(feature = "dvt")))]
let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(5)).expect("can't register server");
#[cfg(all(any(feature="precursor", feature="renode"), feature="dvt"))] // dvt build has less in it
#[cfg(all(any(feature = "precursor", feature = "renode"), feature = "dvt"))] // dvt build has less in it
let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(4)).expect("can't register server");
#[cfg(not(target_os = "xous"))]
let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(5)).expect("can't register server");
@ -741,7 +784,8 @@ fn main() -> ! {
// register a suspend/resume listener
let self_cid = xous::connect(kbd_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(None, &xns, Opcode::SuspendResume as u32, self_cid).expect("couldn't create suspend/resume object");
let mut susres = susres::Susres::new(None, &xns, Opcode::SuspendResume as u32, self_cid)
.expect("couldn't create suspend/resume object");
// start a thread that can ping the keyboard loop when a key is held down
let ticktimer = ticktimer_server::Ticktimer::new().unwrap();
@ -759,13 +803,13 @@ fn main() -> ! {
log::warn!("kbd server is overriding WFI for debugging, remember to disable for production");
llio.wfi_override(true).unwrap();
}*/
#[cfg(not(feature="rawserial"))]
#[cfg(not(feature = "rawserial"))]
let mut esc_index: Option<usize> = None;
#[cfg(not(feature="rawserial"))]
#[cfg(not(feature = "rawserial"))]
let mut esc_chars = [0u8; 16];
// storage for any blocking listeners
let mut blocking_listener = Vec::<MessageSender>::new();
#[cfg(feature="rawserial")]
#[cfg(feature = "rawserial")]
let mut blocking_queue = VecDeque::<usize>::new();
log::trace!("starting main loop");
@ -778,12 +822,11 @@ fn main() -> ! {
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
kbd.resume();
}),
Some(Opcode::Vibe) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena != 0 { vibe = true }
else { vibe = false }
}),
Some(Opcode::Vibe) => {
msg_scalar_unpack!(msg, ena, _, _, _, { if ena != 0 { vibe = true } else { vibe = false } })
}
Some(Opcode::BlockingKeyListener) => {
#[cfg(feature="rawserial")]
#[cfg(feature = "rawserial")]
if blocking_queue.len() != 0 {
// we have a pending byte in the queue, return it.
let k_prime = blocking_queue.pop_front().unwrap();
@ -793,11 +836,11 @@ fn main() -> ! {
// the sender will remain blocked until the return value is generated
blocking_listener.push(msg.sender);
}
#[cfg(not(feature="rawserial"))]
#[cfg(not(feature = "rawserial"))]
blocking_listener.push(msg.sender);
},
}
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 kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
match xns.request_connection_blocking(kr.server_name.as_str()) {
Ok(cid) => {
@ -810,9 +853,9 @@ fn main() -> ! {
listener_op = None;
}
}
},
}
Some(Opcode::RegisterRawListener) => {
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 kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
match xns.request_connection_blocking(kr.server_name.as_str()) {
Ok(cid) => {
@ -825,9 +868,9 @@ fn main() -> ! {
raw_listener_op = None;
}
}
},
}
Some(Opcode::RegisterKeyObserver) => {
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 kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
if observer_conn.is_none() {
match xns.request_connection_blocking(kr.server_name.as_str()) {
@ -842,14 +885,12 @@ fn main() -> ! {
}
}
}
},
Some(Opcode::SelectKeyMap) => msg_scalar_unpack!(msg, km, _, _, _, {
kbd.set_map(KeyMap::from(km))
}),
}
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");
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);
@ -867,7 +908,7 @@ fn main() -> ! {
log::trace!("{:x} {}", k, kbd.debug);
kbd.debug = 0;
#[cfg(feature="rawserial")]
#[cfg(feature = "rawserial")]
{
if blocking_listener.len() == 0 {
if blocking_queue.len() > BLOCKING_QUEUE_LEN {
@ -878,7 +919,8 @@ fn main() -> ! {
} else {
for listener in blocking_listener.drain(..) {
// we must unblock anyways once the key is hit; even if the key is invalid,
// send the invalid key. The receiving library function will clean this up into a nil-response vector.
// send the invalid key. The receiving library function will clean this up into a
// nil-response vector.
if blocking_queue.len() != 0 {
blocking_queue.push_back(k);
let k_prime = blocking_queue.pop_front().unwrap();
@ -890,7 +932,7 @@ fn main() -> ! {
}
continue; // do not execute the remaining code in this branch
}
#[cfg(not(feature="rawserial"))]
#[cfg(not(feature = "rawserial"))]
let key = match esc_index {
Some(i) => {
esc_chars[i] = (k & 0xff) as u8;
@ -914,7 +956,7 @@ fn main() -> ! {
}
// invalid sequence encountered, abort
Err(_) => {
log::warn!("Unhandled escape sequence: {:x?}", &esc_chars[..i+1]);
log::warn!("Unhandled escape sequence: {:x?}", &esc_chars[..i + 1]);
esc_chars = [0u8; 16];
esc_index = None;
'\u{0000}'
@ -928,30 +970,29 @@ fn main() -> ! {
esc_chars[0] = 0x1b;
'\u{0000}'
} else {
let bs_del_fix = if k == 0x7f {
0x08
} else {
k
};
let bs_del_fix = if k == 0x7f { 0x08 } else { k };
core::char::from_u32(bs_del_fix as u32).unwrap_or('\u{0000}')
}
}
};
#[cfg(all(feature="debuginject", not(feature="rawserial")))]
#[cfg(all(feature = "debuginject", not(feature = "rawserial")))]
if let Some(conn) = listener_conn {
if key != '\u{0000}' {
if key >= '\u{f700}' && key <= '\u{f8ff}' {
log::info!("ignoring key '{}'({:x})", key, key as u32); // ignore Apple PUA characters
} else {
log::info!("injecting key '{}'({:x})", key, key as u32); // always be noisy about this, it's an exploit path
xous::try_send_message(conn,
xous::Message::new_scalar(listener_op.unwrap(),
xous::try_send_message(
conn,
xous::Message::new_scalar(
listener_op.unwrap(),
key as u32 as usize,
'\u{0000}' as u32 as usize,
'\u{0000}' as u32 as usize,
'\u{0000}' as u32 as usize,
)
).unwrap_or_else(|_| {
),
)
.unwrap_or_else(|_| {
log::info!("Input overflow, dropping keys!");
xous::Result::Ok
});
@ -961,29 +1002,27 @@ fn main() -> ! {
if observer_conn.is_some() && observer_op.is_some() {
log::trace!("sending observer key");
xous::try_send_message(observer_conn.unwrap(),
xous::Message::new_scalar(
observer_op.unwrap(),
0,
0,
0,
0,
)
).ok();
xous::try_send_message(
observer_conn.unwrap(),
xous::Message::new_scalar(observer_op.unwrap(), 0, 0, 0, 0),
)
.ok();
}
#[cfg(all(feature="debuginject", not(feature="rawserial")))]
#[cfg(all(feature = "debuginject", not(feature = "rawserial")))]
for listener in blocking_listener.drain(..) {
// we must unblock anyways once the key is hit; even if the key is invalid,
// send the invalid key. The receiving library function will clean this up into a nil-response vector.
// send the invalid key. The receiving library function will clean this up into a
// nil-response vector.
xous::return_scalar2(listener, key as u32 as usize, 0).unwrap();
}
}),
Some(Opcode::HandlerTrigger) => {
let rawstates = kbd.update();
if raw_listener_conn.is_some() && raw_listener_op.is_some()
&& (rawstates.keydowns.len() > 0 || rawstates.keyups.len() > 0)
if raw_listener_conn.is_some()
&& raw_listener_op.is_some()
&& (rawstates.keydowns.len() > 0 || rawstates.keyups.len() > 0)
{
// manual serialization of KeyRawStates, because rkyv can't derive a serializer.
let mut krs_ser: [(u8, u8); 32] = [(255, 255); 32];
@ -996,32 +1035,28 @@ fn main() -> ! {
*c = src.c;
}
let buf = Buffer::into_buf(krs_ser).or(Err(xous::Error::InternalError)).expect("couldn't serialize krs buffer");
buf.lend(raw_listener_conn.unwrap(), raw_listener_op.unwrap()).expect("couldn't send raw scancodes");
let buf = Buffer::into_buf(krs_ser)
.or(Err(xous::Error::InternalError))
.expect("couldn't serialize krs buffer");
buf.lend(raw_listener_conn.unwrap(), raw_listener_op.unwrap())
.expect("couldn't send raw scancodes");
}
if observer_conn.is_some() && observer_op.is_some() {
log::trace!("sending observer key");
xous::try_send_message(observer_conn.unwrap(),
xous::Message::new_scalar(
observer_op.unwrap(),
0,
0,
0,
0,
)
).ok();
xous::try_send_message(
observer_conn.unwrap(),
xous::Message::new_scalar(observer_op.unwrap(), 0, 0, 0, 0),
)
.ok();
}
// 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() {
KeyMap::Braille => {
kbd.track_chord(&rawstates)
},
_ => {
kbd.track_keys(&rawstates)
},
KeyMap::Braille => kbd.track_chord(&rawstates),
_ => kbd.track_keys(&rawstates),
};
// send keys, if any
@ -1030,17 +1065,10 @@ fn main() -> ! {
for listener in blocking_listener.drain(..) {
xous::return_scalar2(
listener,
if kc.len() >= 1 {
kc[0] as u32 as usize
} else {
0
},
if kc.len() >= 2 {
kc[1] as u32 as usize
} else {
0
},
).unwrap();
if kc.len() >= 1 { kc[0] as u32 as usize } else { 0 },
if kc.len() >= 2 { kc[1] as u32 as usize } else { 0 },
)
.unwrap();
if kc.len() > 2 {
log::warn!(
"Extra keys in multi-hit event went unreported: only 2 of {} total keys reported out of {:?}",
@ -1061,30 +1089,38 @@ fn main() -> ! {
keys[i] = kv[i];
}
log::trace!("sending keys {:?}", keys);
xous::try_send_message(listener_conn.unwrap(),
xous::try_send_message(
listener_conn.unwrap(),
xous::Message::new_scalar(
listener_op.unwrap(),
keys[0] as u32 as usize,
keys[1] as u32 as usize,
keys[2] as u32 as usize,
keys[3] as u32 as usize,
)
).ok();
),
)
.ok();
}
}
// as long as we have a keydown, keep pinging the loop at a high rate. this consumes more power, but keydowns are relatively rare.
// as long as we have a keydown, keep pinging the loop at a high rate. this consumes more
// power, but keydowns are relatively rare.
if kbd.is_repeating_key() {
log::trace!("keydowns hold");
// fire a second call to check if we should transition to a repeating state
ticktimer.sleep_ms(kbd.get_repeat_check_interval() as _).unwrap();
kbd.poll();
// this is highly likely to overflow; if it does, just discard any excess
xous::try_send_message(self_cid,
xous::Message::new_scalar(Opcode::HandlerTrigger.to_usize().unwrap(), 0, 0, 0, 0)
).ok();
xous::try_send_message(
self_cid,
xous::Message::new_scalar(Opcode::HandlerTrigger.to_usize().unwrap(), 0, 0, 0, 0),
)
.ok();
}
},
None => {log::error!("couldn't convert opcode"); break}
}
None => {
log::error!("couldn't convert opcode");
break;
}
}
}
log::trace!("main loop exit, destroying servers");
@ -1094,31 +1130,41 @@ fn main() -> ! {
xous::terminate_process(0)
}
#[cfg(not(feature="rawserial"))]
#[cfg(not(feature = "rawserial"))]
fn esc_match(esc_chars: &[u8]) -> Result<Option<char>, ()> {
let mut extended = Vec::<u8>::new();
for (i, &c) in esc_chars.iter().enumerate() {
match i {
0 => if c != 0x1b { return Err(()) },
1 => if c != 0x5b { return Err(()) },
0 => {
if c != 0x1b {
return Err(());
}
}
1 => {
if c != 0x5b {
return Err(());
}
}
2 => match c {
0x41 => return Ok(Some('↑')),
0x42 => return Ok(Some('↓')),
0x43 => return Ok(Some('→')),
0x44 => return Ok(Some('←')),
0x7e => return Err(()), // premature end
_ => extended.push(c)
}
_ => if c == 0x7e {
if extended.len() == 1 {
if extended[0] == 0x31 {
return Ok(Some('∴'))
_ => extended.push(c),
},
_ => {
if c == 0x7e {
if extended.len() == 1 {
if extended[0] == 0x31 {
return Ok(Some('∴'));
}
} else {
return Err(()); // code unrecognized
}
} else {
return Err(()) // code unrecognized
extended.push(c)
}
} else {
extended.push(c)
}
}
}

View file

@ -1,10 +1,14 @@
#![allow(dead_code)] // because hosted mode doesn't use mappings
#![allow(unused_imports)]
#[rustfmt::skip] // this file is a lookup table. Allow wide columns.
mod qwerty;
pub (crate) use qwerty::*;
pub(crate) use qwerty::*;
#[rustfmt::skip] // this file is a lookup table. Allow wide columns.
mod qwertz;
pub (crate) use qwertz::*;
pub(crate) use qwertz::*;
#[rustfmt::skip] // this file is a lookup table. Allow wide columns.
mod azerty;
pub (crate) use azerty::*;
pub(crate) use azerty::*;
#[rustfmt::skip] // this file is a lookup table. Allow wide columns.
mod dvorak;
pub (crate) use dvorak::*;
pub(crate) use dvorak::*;