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

@ -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,25 +16,22 @@ 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())
@ -44,7 +41,7 @@ impl Keyboard {
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())
@ -52,42 +49,36 @@ impl Keyboard {
}
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")]
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")]
use std::collections::VecDeque;
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"))]
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
@ -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); }
if esc {
keystates.push(bs);
}
let func = self.chord[3][9];
let cr: char = 0xd_u8.into(); // carriage return
if func { keystates.push(cr); }
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;
@ -459,21 +503,24 @@ mod implementation {
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,16 +534,18 @@ 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;
}
@ -504,10 +553,12 @@ mod implementation {
} else {
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;
@ -534,9 +585,11 @@ mod implementation {
KeyMap::Qwertz => map_qwertz(rc),
_ => 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);
}
@ -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 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 update(&self) -> KeyRawStates {
KeyRawStates::new()
}
pub fn update(&self) -> KeyRawStates { KeyRawStates::new() }
pub fn track_chord(&mut self, _krs: &KeyRawStates) -> Vec<char> {
Vec::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 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) {}
}
}
@ -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();
@ -778,10 +822,9 @@ 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")]
if blocking_queue.len() != 0 {
@ -795,7 +838,7 @@ fn main() -> ! {
}
#[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 kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
@ -810,7 +853,7 @@ fn main() -> ! {
listener_op = None;
}
}
},
}
Some(Opcode::RegisterRawListener) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
@ -825,7 +868,7 @@ fn main() -> ! {
raw_listener_op = None;
}
}
},
}
Some(Opcode::RegisterKeyObserver) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
@ -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);
@ -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();
@ -928,11 +970,7 @@ 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}')
}
}
@ -944,14 +982,17 @@ fn main() -> ! {
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,28 +1002,26 @@ 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,
xous::try_send_message(
observer_conn.unwrap(),
xous::Message::new_scalar(observer_op.unwrap(), 0, 0, 0, 0),
)
).ok();
.ok();
}
#[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()
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.
@ -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,
xous::try_send_message(
observer_conn.unwrap(),
xous::Message::new_scalar(observer_op.unwrap(), 0, 0, 0, 0),
)
).ok();
.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");
@ -1099,28 +1135,38 @@ 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 {
_ => extended.push(c),
},
_ => {
if c == 0x7e {
if extended.len() == 1 {
if extended[0] == 0x31 {
return Ok(Some('∴'))
return Ok(Some('∴'));
}
} else {
return Err(()) // code unrecognized
return Err(()); // code unrecognized
}
} else {
extended.push(c)
}
}
}
}
Ok(None)
}

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::*;
#[rustfmt::skip] // this file is a lookup table. Allow wide columns.
mod qwertz;
pub(crate) use qwertz::*;
#[rustfmt::skip] // this file is a lookup table. Allow wide columns.
mod azerty;
pub(crate) use azerty::*;
#[rustfmt::skip] // this file is a lookup table. Allow wide columns.
mod dvorak;
pub(crate) use dvorak::*;