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 /// set repeat delay, rate; both in ms
SetRepeat = 4, //(u32, u32), 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), SetChordInterval = 5, //(u32),
/// used by host mode emulation and debug UART to inject keys /// used by host mode emulation and debug UART to inject keys
@ -107,7 +108,7 @@ pub(crate) enum Opcode {
// which is the GAM. // which is the GAM.
#[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: usize, pub listener_op_id: usize,
} }
@ -118,21 +119,14 @@ pub struct RowCol {
} }
impl RowCol { impl RowCol {
#[allow(dead_code)] #[allow(dead_code)]
pub fn new(r: u8, c: u8) -> RowCol { pub fn new(r: u8, c: u8) -> RowCol { RowCol { r, c } }
RowCol { r, c }
}
} }
#[derive(Debug)] #[derive(Debug)]
pub struct KeyRawStates { pub struct KeyRawStates {
pub keydowns: Vec::<RowCol>, pub keydowns: Vec<RowCol>,
pub keyups: Vec::<RowCol>, pub keyups: Vec<RowCol>,
} }
impl KeyRawStates { impl KeyRawStates {
pub fn new() -> Self { pub fn new() -> Self { KeyRawStates { keydowns: Vec::with_capacity(16), keyups: Vec::with_capacity(16) } }
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> { pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.fetch_add(1, Ordering::Relaxed); REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(api::SERVER_NAME_KBD).expect("Can't connect to KBD"); let conn = xns.request_connection_blocking(api::SERVER_NAME_KBD).expect("Can't connect to KBD");
Ok(Keyboard { Ok(Keyboard { conn })
conn,
})
} }
pub fn register_listener(&self, server_name: &str, action_opcode: usize) { pub fn register_listener(&self, server_name: &str, action_opcode: usize) {
let kr = KeyboardRegistration { let kr = KeyboardRegistration {
server_name: String::<64>::from_str(server_name), 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(); let buf = Buffer::into_buf(kr).unwrap();
buf.lend(self.conn, Opcode::RegisterListener.to_u32().unwrap()) buf.lend(self.conn, Opcode::RegisterListener.to_u32().unwrap()).expect("couldn't register listener");
.expect("couldn't register listener");
} }
pub fn register_raw_listener(&self, server_name: &str, action_opcode: usize) { pub fn register_raw_listener(&self, server_name: &str, action_opcode: usize) {
let kr = KeyboardRegistration { let kr = KeyboardRegistration {
server_name: String::<64>::from_str(server_name), 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(); let buf = Buffer::into_buf(kr).unwrap();
buf.lend(self.conn, Opcode::RegisterRawListener.to_u32().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) { pub fn register_observer(&self, server_name: &str, action_opcode: usize) {
let kr = KeyboardRegistration { let kr = KeyboardRegistration {
server_name: String::<64>::from_str(server_name), 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(); let buf = Buffer::into_buf(kr).unwrap();
buf.lend(self.conn, Opcode::RegisterKeyObserver.to_u32().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> { pub fn set_vibe(&self, enable: bool) -> Result<(), xous::Error> {
let ena = let ena = if enable { 1 } else { 0 };
if enable { 1 } send_message(self.conn, Message::new_scalar(Opcode::Vibe.to_usize().unwrap(), ena, 0, 0, 0))
else { 0 }; .map(|_| ())
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> { pub fn set_keymap(&self, map: KeyMap) -> Result<(), xous::Error> {
send_message(self.conn, send_message(
Message::new_scalar(Opcode::SelectKeyMap.to_usize().unwrap(), self.conn,
map.into(), Message::new_scalar(Opcode::SelectKeyMap.to_usize().unwrap(), map.into(), 0, 0, 0),
0, 0, 0) )
).map(|_| ()) .map(|_| ())
} }
pub fn get_keymap(&self) -> Result<KeyMap, xous::Error> { pub fn get_keymap(&self) -> Result<KeyMap, xous::Error> {
match send_message(self.conn, match send_message(
Message::new_blocking_scalar(Opcode::GetKeyMap.to_usize().unwrap(), self.conn,
0, 0, 0, 0) Message::new_blocking_scalar(Opcode::GetKeyMap.to_usize().unwrap(), 0, 0, 0, 0),
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => Ok(code.into()),
Ok(code.into()) _ => Err(xous::Error::InternalError),
}
_ => Err(xous::Error::InternalError)
} }
} }
/// Blocks until a key is hit. Does not block the keyboard server, just the caller. /// 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. /// 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. /// The specific order of a simultaneous key hit event is not defined.
pub fn get_keys_blocking(&self) -> Vec<char> { pub fn get_keys_blocking(&self) -> Vec<char> {
match send_message(self.conn, match send_message(
Message::new_blocking_scalar( self.conn,
Opcode::BlockingKeyListener.to_usize().unwrap(), Message::new_blocking_scalar(Opcode::BlockingKeyListener.to_usize().unwrap(), 0, 0, 0, 0),
0, 0, 0, 0
)
) { ) {
Ok(xous::Result::Scalar2(k1, k2)) => { Ok(xous::Result::Scalar2(k1, k2)) => {
let mut ret = Vec::<char>::new(); let mut ret = Vec::<char>::new();
@ -99,28 +90,31 @@ impl Keyboard {
} }
ret 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 /// Reveal the connection ID for use with unsafe FFI calls
pub fn conn(&self) -> xous::CID { self.conn } pub fn conn(&self) -> xous::CID { self.conn }
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
pub fn hostmode_inject_key(&self, c: char) { pub fn hostmode_inject_key(&self, c: char) {
send_message(self.conn, send_message(
Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), self.conn,
c as u32 as usize, 0, 0, 0 Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), c as u32 as usize, 0, 0, 0),
)).unwrap(); )
.unwrap();
} }
/// This is used to shove keys into the keyboard module as if you were typing on the /// This is used to shove keys into the keyboard module as if you were typing on the
/// physical keyboard. /// physical keyboard.
#[cfg(feature="inject-api")] #[cfg(feature = "inject-api")]
pub fn inject_key(&self, c: char) { pub fn inject_key(&self, c: char) {
send_message(self.conn, send_message(
Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), self.conn,
c as u32 as usize, 0, 0, 0 Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), c as u32 as usize, 0, 0, 0),
)).unwrap(); )
.unwrap();
} }
} }
@ -128,9 +122,12 @@ use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0); static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Keyboard { impl Drop for Keyboard {
fn drop(&mut self) { 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 { 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::*; use api::*;
mod mappings; mod mappings;
use log::info; #[cfg(feature = "rawserial")]
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 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; const BLOCKING_QUEUE_LEN: usize = 128;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
mod implementation { mod implementation {
use utralib::generated::*; use std::collections::HashSet;
use crate::{RowCol, KeyRawStates, api::*};
use crate::mappings::*;
use ticktimer_server::Ticktimer;
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; 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 /// note: the code is structured to use at most 16 rows or 16 cols
const KBD_ROWS: usize = 9; const KBD_ROWS: usize = 9;
@ -34,9 +36,9 @@ mod implementation {
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: HashSet::<RowCol>, new_state: HashSet<RowCol>,
/// remember the last key states /// remember the last key states
last_state: HashSet::<RowCol>, 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
@ -63,9 +65,10 @@ mod implementation {
chord: [[bool; KBD_COLS]; KBD_ROWS], chord: [[bool; KBD_COLS]; KBD_ROWS],
/// memoize number of keys that have been pressed /// memoize number of keys that have been pressed
chord_active: u32, 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, 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 /// a field used for debugging various keyboard issues, especially with the interrupt handler
pub debug: usize, pub debug: usize,
/// access to settings stored in the first few sectors of FLASH /// access to settings stored in the first few sectors of FLASH
@ -84,23 +87,32 @@ mod implementation {
if cols != 0 { if cols != 0 {
for c in 0..KBD_COLS { for c in 0..KBD_COLS {
if (cols & (1 << c)) != 0 { if (cols & (1 << c)) != 0 {
kbd.new_state.insert( kbd.new_state.insert(RowCol { r: r as _, c: c as _ });
RowCol{r: r as _, c: c as _}
);
} }
} }
} }
} }
xous::try_send_message(kbd.conn, xous::try_send_message(
xous::Message::new_scalar(Opcode::HandlerTrigger.to_usize().unwrap(), 0, 0, 0, 0)).ok(); 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 { if kbd.csr.rf(utra::keyboard::EV_PENDING_INJECT) != 0 {
loop { loop {
let char_reg = kbd.csr.r(utra::keyboard::UART_CHAR); let char_reg = kbd.csr.r(utra::keyboard::UART_CHAR);
if char_reg & kbd.csr.ms(utra::keyboard::UART_CHAR_STB, 1) != 0 { if char_reg & kbd.csr.ms(utra::keyboard::UART_CHAR_STB, 1) != 0 {
xous::try_send_message(kbd.conn, xous::try_send_message(
xous::Message::new_scalar(Opcode::InjectKey.to_usize().unwrap(), (char_reg & 0xff) as _, 0, 0, 0) kbd.conn,
).ok(); xous::Message::new_scalar(
Opcode::InjectKey.to_usize().unwrap(),
(char_reg & 0xff) as _,
0,
0,
0,
),
)
.ok();
kbd.debug += 1; kbd.debug += 1;
} else { } else {
break; break;
@ -123,7 +135,7 @@ mod implementation {
6 => kbd.csr.rf(utra::keyboard::ROW6DAT_ROW6DAT) as u16, 6 => kbd.csr.rf(utra::keyboard::ROW6DAT_ROW6DAT) as u16,
7 => kbd.csr.rf(utra::keyboard::ROW7DAT_ROW7DAT) as u16, 7 => kbd.csr.rf(utra::keyboard::ROW7DAT_ROW7DAT) as u16,
8 => kbd.csr.rf(utra::keyboard::ROW8DAT_ROW8DAT) 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") { let default_map = if cfg!(feature = "braille") {
KeyMap::Braille KeyMap::Braille
} else { } else {
// the boot setting is intended to only contain the keyboard mapping...soooooooo.....we manage it as such // the boot setting is intended to only contain the keyboard mapping...soooooooo.....we manage
// if feature creep causes more stuff to end up here this should be made into something more generic. // it as such if feature creep causes more stuff to end up here this should be
// But! If you think you need to slap something in the boot setting, think again. This is an unverified, // made into something more generic. But! If you think you need to slap
// unencrypted and plaintext bit of memory that anyone can read or mess with. The only reason the keyboard // something in the boot setting, think again. This is an unverified,
// layout is kept here is because you want your keyboard to be in the right language before typing in the // unencrypted and plaintext bit of memory that anyone can read or mess with. The only reason
// password to unlock the PDDB, which is *actually* where all the user settings should be located. // 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 kb_raw = ea.get_keymap().expect("cannot fetch keymap from early settings");
let map = KeyMap::from(kb_raw); let map = KeyMap::from(kb_raw);
map map
@ -161,7 +175,8 @@ mod implementation {
Keyboard { 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: 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), last_state: HashSet::with_capacity(16),
ticktimer, ticktimer,
map: default_map, map: default_map,
@ -192,9 +207,10 @@ mod implementation {
) )
.expect("couldn't claim irq"); .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_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.wo(
self.csr.ms(utra::keyboard::EV_ENABLE_KEYPRESSED, 1) | utra::keyboard::EV_ENABLE,
self.csr.ms(utra::keyboard::EV_ENABLE_INJECT, 1) 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); self.susres.push_fixed_value(RegOrField::Reg(utra::keyboard::EV_PENDING), 0xFFFF_FFFF);
@ -205,6 +221,7 @@ mod implementation {
self.susres.suspend(); self.susres.suspend();
self.csr.wo(utra::keyboard::EV_ENABLE, 0); self.csr.wo(utra::keyboard::EV_ENABLE, 0);
} }
pub(crate) fn resume(&mut self) { pub(crate) fn resume(&mut self) {
self.susres.resume(); self.susres.resume();
@ -224,9 +241,10 @@ mod implementation {
// ensure interrupts are re-enabled -- this could /shouldn't/ be necessary but we're having // 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. // 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_PENDING, self.csr.r(utra::keyboard::EV_PENDING));
self.csr.wo(utra::keyboard::EV_ENABLE, self.csr.wo(
self.csr.ms(utra::keyboard::EV_ENABLE_KEYPRESSED, 1) | utra::keyboard::EV_ENABLE,
self.csr.ms(utra::keyboard::EV_ENABLE_INJECT, 1) 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.early_settings.set_keymap(map.into()).expect("cannot set early keymap");
self.map = map; self.map = map;
} }
pub(crate) fn get_map(&mut self) -> KeyMap { pub(crate) fn get_map(&mut self) -> KeyMap {
let kb_raw = self.early_settings.get_keymap().expect("cannot fetch early keymap"); let kb_raw = self.early_settings.get_keymap().expect("cannot fetch early keymap");
self.map = KeyMap::from(kb_raw); self.map = KeyMap::from(kb_raw);
self.map self.map
} }
pub(crate) 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(crate) fn set_chord_interval(&mut self, delay: u32) {
self.chord_interval = delay; pub(crate) fn set_chord_interval(&mut self, delay: u32) { self.chord_interval = delay; }
}
pub(crate) fn get_repeat_check_interval(&self) -> u32 { pub(crate) fn get_repeat_check_interval(&self) -> u32 { self.rate }
self.rate
}
pub(crate) fn poll(&mut self) { pub(crate) fn poll(&mut self) {
// disable the interrupt while we're polling, to avoid a race condition... // disable the interrupt while we're polling, to avoid a race condition...
@ -259,9 +277,7 @@ mod implementation {
if cols != 0 { if cols != 0 {
for c in 0..KBD_COLS { for c in 0..KBD_COLS {
if (cols & (1 << c)) != 0 { if (cols & (1 << c)) != 0 {
self.new_state.insert( self.new_state.insert(RowCol { r: r as _, c: c as _ });
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 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; self.chord_captured = true;
log::trace!("interpreting chords"); log::trace!("interpreting chords");
// extract chord state // extract chord state
@ -402,30 +421,55 @@ mod implementation {
} }
let up = self.chord[6][4]; let up = self.chord[6][4];
if up { keystates.push('↑'); } if up {
keystates.push('↑');
}
let left = self.chord[8][3]; let left = self.chord[8][3];
if left { keystates.push('←'); } if left {
keystates.push('←');
}
let right = self.chord[3][6]; let right = self.chord[3][6];
if right { keystates.push('→'); } if right {
keystates.push('→');
}
let down = self.chord[8][2]; let down = self.chord[8][2];
if down { keystates.push('↓'); } if down {
keystates.push('↓');
}
let center = self.chord[5][2]; let center = self.chord[5][2];
if center { keystates.push('∴'); } if center {
keystates.push('∴');
}
let space = self.chord[2][3]; let space = self.chord[2][3];
if space { keystates.push(' '); } if space {
keystates.push(' ');
}
let esc = self.chord[8][0]; let esc = self.chord[8][0];
let bs: char = 0x8_u8.into(); // back space 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 func = self.chord[3][9];
let cr: char = 0xd_u8.into(); // carriage return 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 {}", log::debug!(
up, left, right, down, center, space, esc, func); "up {}, left {}, right {}, down, {}, center, {}, space {}, esc {}, func {}",
up,
left,
right,
down,
center,
space,
esc,
func
);
} }
for rc in krs.keyups.iter() { for rc in krs.keyups.iter() {
self.chord[rc.r as usize][rc.c as usize] = false; self.chord[rc.r as usize][rc.c as usize] = false;
@ -459,21 +503,24 @@ mod implementation {
for rc in krs.keydowns.iter() { for rc in krs.keydowns.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)
if self.alt_up == false { if self.alt_up == false {
self.alt_down = true; self.alt_down = true;
} else { } else {
self.alt_up = false; 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 { if self.shift_up == false {
self.shift_down = true; self.shift_down = true;
} else { } else {
self.shift_up = false; 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 ((rc.r == 8) && (rc.c == 5)) || ((rc.r == 8) && (rc.c == 9)) {
// if the shift key was tapped twice, remove the shift modifier // if the shift key was tapped twice, remove the shift modifier
if self.shift_up == false { 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() { for &rc in krs.keyups.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)
if self.alt_down { if self.alt_down {
self.alt_up = true; self.alt_up = true;
} }
self.alt_down = false; 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 { if self.shift_down {
self.shift_up = true; self.shift_up = true;
} }
self.shift_down = false; self.shift_down = false;
} else { } 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)) { 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 { if self.shift_down {
//info!("shift up true"); //info!("shift up true");
self.shift_up = true; self.shift_up = true;
@ -516,7 +567,7 @@ mod implementation {
self.shift_down = false; self.shift_down = false;
} else { } else {
//info!("adding non-shift entry {:?}", rc); //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::Dvorak => map_dvorak(rc),
KeyMap::Azerty => map_azerty(rc), KeyMap::Azerty => map_azerty(rc),
KeyMap::Qwertz => map_qwertz(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 if code.hold == None && !((rc.r == 5) && (rc.c == 2))
&& !((rc.r == 5) && (rc.c == 2)) // scan code for the menu key // 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 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 { if let Some(key) = code.key {
self.repeating_key = Some(key); self.repeating_key = Some(key);
} }
@ -561,7 +614,7 @@ mod implementation {
KeyMap::Dvorak => map_dvorak(rc), KeyMap::Dvorak => map_dvorak(rc),
KeyMap::Azerty => map_azerty(rc), KeyMap::Azerty => map_azerty(rc),
KeyMap::Qwertz => map_qwertz(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 // delete the key repeat if there is one
if code.hold == None { if code.hold == None {
@ -603,7 +656,7 @@ mod implementation {
ks.push(keycode); ks.push(keycode);
} }
} }
}, }
_ => { _ => {
if self.shift_down || self.alt_down || self.shift_up || self.alt_up { if self.shift_down || self.alt_down || self.shift_up || self.alt_up {
if let Some(shiftcode) = code.shift { 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() { if hold && ((now - self.rate_timestamp) >= self.rate as u64) && self.repeating_key.is_some() {
self.rate_timestamp = now; self.rate_timestamp = now;
if let Some(repeatkey) = self.repeating_key { if let Some(repeatkey) = self.repeating_key {
@ -639,9 +693,8 @@ mod implementation {
ks 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, debug: 0,
} }
} }
pub fn init(&mut self) {} pub fn init(&mut self) {}
pub fn suspend(&self) {
}
pub fn resume(&self) {
}
pub fn set_map(&mut self, map: KeyMap) { pub fn suspend(&self) {}
self.map = map;
}
pub fn get_map(&self) -> KeyMap {self.map}
pub fn update(&self) -> KeyRawStates { pub fn resume(&self) {}
KeyRawStates::new()
}
pub fn track_chord(&mut self, _krs: &KeyRawStates) -> Vec<char> { pub fn set_map(&mut self, map: KeyMap) { self.map = map; }
Vec::new()
}
pub fn track_keys(&mut self, _rs: &KeyRawStates) -> Vec<char> { pub fn get_map(&self) -> KeyMap { self.map }
Vec::new()
} 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) { pub 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 fn set_chord_interval(&mut self, delay: u32) { self.chord_interval = delay; }
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) {} pub(crate) fn poll(&mut self) {}
} }
} }
@ -727,9 +770,9 @@ fn main() -> ! {
// - status sub system (for setting the layout, autobacklight feature) // - status sub system (for setting the layout, autobacklight feature)
// - USB (for getting layout) // - USB (for getting layout)
// - Preference manager // - 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"); 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"); let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(4)).expect("can't register server");
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
let kbd_sid = xns.register_name(api::SERVER_NAME_KBD, Some(5)).expect("can't register server"); 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 // register a suspend/resume listener
let self_cid = xous::connect(kbd_sid).expect("couldn't create suspend callback connection"); 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 // start a thread that can ping the keyboard loop when a key is held down
let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); 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"); log::warn!("kbd server is overriding WFI for debugging, remember to disable for production");
llio.wfi_override(true).unwrap(); llio.wfi_override(true).unwrap();
}*/ }*/
#[cfg(not(feature="rawserial"))] #[cfg(not(feature = "rawserial"))]
let mut esc_index: Option<usize> = None; let mut esc_index: Option<usize> = None;
#[cfg(not(feature="rawserial"))] #[cfg(not(feature = "rawserial"))]
let mut esc_chars = [0u8; 16]; let mut esc_chars = [0u8; 16];
// storage for any blocking listeners // storage for any blocking listeners
let mut blocking_listener = Vec::<MessageSender>::new(); let mut blocking_listener = Vec::<MessageSender>::new();
#[cfg(feature="rawserial")] #[cfg(feature = "rawserial")]
let mut blocking_queue = VecDeque::<usize>::new(); let mut blocking_queue = VecDeque::<usize>::new();
log::trace!("starting main loop"); log::trace!("starting main loop");
@ -778,12 +822,11 @@ fn main() -> ! {
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
kbd.resume(); kbd.resume();
}), }),
Some(Opcode::Vibe) => msg_scalar_unpack!(msg, ena, _, _, _, { Some(Opcode::Vibe) => {
if ena != 0 { vibe = true } msg_scalar_unpack!(msg, ena, _, _, _, { if ena != 0 { vibe = true } else { vibe = false } })
else { vibe = false } }
}),
Some(Opcode::BlockingKeyListener) => { Some(Opcode::BlockingKeyListener) => {
#[cfg(feature="rawserial")] #[cfg(feature = "rawserial")]
if blocking_queue.len() != 0 { if blocking_queue.len() != 0 {
// we have a pending byte in the queue, return it. // we have a pending byte in the queue, return it.
let k_prime = blocking_queue.pop_front().unwrap(); 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 // the sender will remain blocked until the return value is generated
blocking_listener.push(msg.sender); blocking_listener.push(msg.sender);
} }
#[cfg(not(feature="rawserial"))] #[cfg(not(feature = "rawserial"))]
blocking_listener.push(msg.sender); blocking_listener.push(msg.sender);
}, }
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 kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap(); let kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
match xns.request_connection_blocking(kr.server_name.as_str()) { match xns.request_connection_blocking(kr.server_name.as_str()) {
Ok(cid) => { Ok(cid) => {
@ -810,9 +853,9 @@ fn main() -> ! {
listener_op = None; listener_op = None;
} }
} }
}, }
Some(Opcode::RegisterRawListener) => { 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(); let kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
match xns.request_connection_blocking(kr.server_name.as_str()) { match xns.request_connection_blocking(kr.server_name.as_str()) {
Ok(cid) => { Ok(cid) => {
@ -825,9 +868,9 @@ fn main() -> ! {
raw_listener_op = None; raw_listener_op = None;
} }
} }
}, }
Some(Opcode::RegisterKeyObserver) => { 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(); let kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
if observer_conn.is_none() { if observer_conn.is_none() {
match xns.request_connection_blocking(kr.server_name.as_str()) { match xns.request_connection_blocking(kr.server_name.as_str()) {
@ -842,14 +885,12 @@ fn main() -> ! {
} }
} }
} }
}, }
Some(Opcode::SelectKeyMap) => msg_scalar_unpack!(msg, km, _, _, _, { Some(Opcode::SelectKeyMap) => {
kbd.set_map(KeyMap::from(km)) msg_scalar_unpack!(msg, km, _, _, _, { kbd.set_map(KeyMap::from(km)) })
}), }
Some(Opcode::GetKeyMap) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::GetKeyMap) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, xous::return_scalar(msg.sender, kbd.get_map().into()).expect("can't retrieve keymap");
kbd.get_map().into()
).expect("can't retrieve keymap");
}), }),
Some(Opcode::SetRepeat) => msg_scalar_unpack!(msg, rate, delay, _, _, { Some(Opcode::SetRepeat) => msg_scalar_unpack!(msg, rate, delay, _, _, {
kbd.set_repeat(rate as u32, delay as u32); kbd.set_repeat(rate as u32, delay as u32);
@ -867,7 +908,7 @@ fn main() -> ! {
log::trace!("{:x} {}", k, kbd.debug); log::trace!("{:x} {}", k, kbd.debug);
kbd.debug = 0; kbd.debug = 0;
#[cfg(feature="rawserial")] #[cfg(feature = "rawserial")]
{ {
if blocking_listener.len() == 0 { if blocking_listener.len() == 0 {
if blocking_queue.len() > BLOCKING_QUEUE_LEN { if blocking_queue.len() > BLOCKING_QUEUE_LEN {
@ -878,7 +919,8 @@ fn main() -> ! {
} else { } else {
for listener in blocking_listener.drain(..) { for listener in blocking_listener.drain(..) {
// we must unblock anyways once the key is hit; even if the key is invalid, // 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 { if blocking_queue.len() != 0 {
blocking_queue.push_back(k); blocking_queue.push_back(k);
let k_prime = blocking_queue.pop_front().unwrap(); let k_prime = blocking_queue.pop_front().unwrap();
@ -890,7 +932,7 @@ fn main() -> ! {
} }
continue; // do not execute the remaining code in this branch continue; // do not execute the remaining code in this branch
} }
#[cfg(not(feature="rawserial"))] #[cfg(not(feature = "rawserial"))]
let key = match esc_index { let key = match esc_index {
Some(i) => { Some(i) => {
esc_chars[i] = (k & 0xff) as u8; esc_chars[i] = (k & 0xff) as u8;
@ -914,7 +956,7 @@ fn main() -> ! {
} }
// invalid sequence encountered, abort // invalid sequence encountered, abort
Err(_) => { 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_chars = [0u8; 16];
esc_index = None; esc_index = None;
'\u{0000}' '\u{0000}'
@ -928,30 +970,29 @@ fn main() -> ! {
esc_chars[0] = 0x1b; esc_chars[0] = 0x1b;
'\u{0000}' '\u{0000}'
} else { } else {
let bs_del_fix = if k == 0x7f { let bs_del_fix = if k == 0x7f { 0x08 } else { k };
0x08
} else {
k
};
core::char::from_u32(bs_del_fix as u32).unwrap_or('\u{0000}') 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 let Some(conn) = listener_conn {
if key != '\u{0000}' { if key != '\u{0000}' {
if key >= '\u{f700}' && key <= '\u{f8ff}' { if key >= '\u{f700}' && key <= '\u{f8ff}' {
log::info!("ignoring key '{}'({:x})", key, key as u32); // ignore Apple PUA characters log::info!("ignoring key '{}'({:x})", key, key as u32); // ignore Apple PUA characters
} else { } else {
log::info!("injecting key '{}'({:x})", key, key as u32); // always be noisy about this, it's an exploit path 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::try_send_message(
xous::Message::new_scalar(listener_op.unwrap(), conn,
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,
),
) )
).unwrap_or_else(|_| { .unwrap_or_else(|_| {
log::info!("Input overflow, dropping keys!"); log::info!("Input overflow, dropping keys!");
xous::Result::Ok xous::Result::Ok
}); });
@ -961,28 +1002,26 @@ fn main() -> ! {
if observer_conn.is_some() && observer_op.is_some() { if observer_conn.is_some() && observer_op.is_some() {
log::trace!("sending observer key"); log::trace!("sending observer key");
xous::try_send_message(observer_conn.unwrap(), xous::try_send_message(
xous::Message::new_scalar( observer_conn.unwrap(),
observer_op.unwrap(), xous::Message::new_scalar(observer_op.unwrap(), 0, 0, 0, 0),
0,
0,
0,
0,
) )
).ok(); .ok();
} }
#[cfg(all(feature="debuginject", not(feature="rawserial")))] #[cfg(all(feature = "debuginject", not(feature = "rawserial")))]
for listener in blocking_listener.drain(..) { for listener in blocking_listener.drain(..) {
// we must unblock anyways once the key is hit; even if the key is invalid, // 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(); xous::return_scalar2(listener, key as u32 as usize, 0).unwrap();
} }
}), }),
Some(Opcode::HandlerTrigger) => { Some(Opcode::HandlerTrigger) => {
let rawstates = kbd.update(); 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) && (rawstates.keydowns.len() > 0 || rawstates.keyups.len() > 0)
{ {
// manual serialization of KeyRawStates, because rkyv can't derive a serializer. // manual serialization of KeyRawStates, because rkyv can't derive a serializer.
@ -996,32 +1035,28 @@ fn main() -> ! {
*c = src.c; *c = src.c;
} }
let buf = Buffer::into_buf(krs_ser).or(Err(xous::Error::InternalError)).expect("couldn't serialize krs buffer"); let buf = Buffer::into_buf(krs_ser)
buf.lend(raw_listener_conn.unwrap(), raw_listener_op.unwrap()).expect("couldn't send raw scancodes"); .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() { if observer_conn.is_some() && observer_op.is_some() {
log::trace!("sending observer key"); log::trace!("sending observer key");
xous::try_send_message(observer_conn.unwrap(), xous::try_send_message(
xous::Message::new_scalar( observer_conn.unwrap(),
observer_op.unwrap(), xous::Message::new_scalar(observer_op.unwrap(), 0, 0, 0, 0),
0,
0,
0,
0,
) )
).ok(); .ok();
} }
// 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(&rawstates),
kbd.track_chord(&rawstates) _ => kbd.track_keys(&rawstates),
},
_ => {
kbd.track_keys(&rawstates)
},
}; };
// send keys, if any // send keys, if any
@ -1030,17 +1065,10 @@ fn main() -> ! {
for listener in blocking_listener.drain(..) { for listener in blocking_listener.drain(..) {
xous::return_scalar2( xous::return_scalar2(
listener, listener,
if kc.len() >= 1 { if kc.len() >= 1 { kc[0] as u32 as usize } else { 0 },
kc[0] as u32 as usize if kc.len() >= 2 { kc[1] as u32 as usize } else { 0 },
} else { )
0 .unwrap();
},
if kc.len() >= 2 {
kc[1] as u32 as usize
} else {
0
},
).unwrap();
if kc.len() > 2 { if kc.len() > 2 {
log::warn!( log::warn!(
"Extra keys in multi-hit event went unreported: only 2 of {} total keys reported out of {:?}", "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]; keys[i] = kv[i];
} }
log::trace!("sending keys {:?}", keys); log::trace!("sending keys {:?}", keys);
xous::try_send_message(listener_conn.unwrap(), xous::try_send_message(
listener_conn.unwrap(),
xous::Message::new_scalar( xous::Message::new_scalar(
listener_op.unwrap(), listener_op.unwrap(),
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,
),
) )
).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() { if kbd.is_repeating_key() {
log::trace!("keydowns hold"); log::trace!("keydowns hold");
// fire a second call to check if we should transition to a repeating state // fire a second call to check if we should transition to a repeating state
ticktimer.sleep_ms(kbd.get_repeat_check_interval() as _).unwrap(); ticktimer.sleep_ms(kbd.get_repeat_check_interval() as _).unwrap();
kbd.poll(); kbd.poll();
// this is highly likely to overflow; if it does, just discard any excess // this is highly likely to overflow; if it does, just discard any excess
xous::try_send_message(self_cid, xous::try_send_message(
xous::Message::new_scalar(Opcode::HandlerTrigger.to_usize().unwrap(), 0, 0, 0, 0) self_cid,
).ok(); 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"); log::trace!("main loop exit, destroying servers");
@ -1094,33 +1130,43 @@ fn main() -> ! {
xous::terminate_process(0) xous::terminate_process(0)
} }
#[cfg(not(feature="rawserial"))] #[cfg(not(feature = "rawserial"))]
fn esc_match(esc_chars: &[u8]) -> Result<Option<char>, ()> { fn esc_match(esc_chars: &[u8]) -> Result<Option<char>, ()> {
let mut extended = Vec::<u8>::new(); let mut extended = Vec::<u8>::new();
for (i, &c) in esc_chars.iter().enumerate() { for (i, &c) in esc_chars.iter().enumerate() {
match i { match i {
0 => if c != 0x1b { return Err(()) }, 0 => {
1 => if c != 0x5b { return Err(()) }, if c != 0x1b {
return Err(());
}
}
1 => {
if c != 0x5b {
return Err(());
}
}
2 => match c { 2 => match c {
0x41 => return Ok(Some('↑')), 0x41 => return Ok(Some('↑')),
0x42 => return Ok(Some('↓')), 0x42 => return Ok(Some('↓')),
0x43 => return Ok(Some('→')), 0x43 => return Ok(Some('→')),
0x44 => return Ok(Some('←')), 0x44 => return Ok(Some('←')),
0x7e => return Err(()), // premature end 0x7e => return Err(()), // premature end
_ => extended.push(c) _ => extended.push(c),
} },
_ => if c == 0x7e { _ => {
if c == 0x7e {
if extended.len() == 1 { if extended.len() == 1 {
if extended[0] == 0x31 { if extended[0] == 0x31 {
return Ok(Some('∴')) return Ok(Some('∴'));
} }
} else { } else {
return Err(()) // code unrecognized return Err(()); // code unrecognized
} }
} else { } else {
extended.push(c) extended.push(c)
} }
} }
} }
}
Ok(None) Ok(None)
} }

View file

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