Merge pull request #847 from betrusted-io/ux-work

UX work
This commit is contained in:
bunnie 2026-04-07 01:01:52 +08:00 committed by GitHub
commit b522993ae9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 242 additions and 35 deletions

View file

@ -52,6 +52,7 @@ pub enum HalOpcode {
/// Configure Iox IRQ
ConfigureIoxIrq = 11,
IrqLocalHandler = 12,
UpdateIoxIrq = 13,
/// Manipulate the OS timer
SetPreemptionState = 64,

View file

@ -1,3 +1,6 @@
#[cfg(feature = "std")]
use std::ops::Not;
#[cfg(feature = "std")]
use num_traits::ToPrimitive;
@ -64,6 +67,18 @@ impl From<u32> for IoxValue {
fn from(value: u32) -> Self { if value == 0 { IoxValue::Low } else { IoxValue::High } }
}
#[cfg(feature = "std")]
impl Not for IoxValue {
type Output = IoxValue;
fn not(self) -> Self::Output {
match self {
IoxValue::Low => IoxValue::High,
IoxValue::High => IoxValue::Low,
}
}
}
/// Use a trait that will allow us to share code between both `std` and `no-std` implementations
pub trait IoSetup {
fn setup_pin(
@ -93,7 +108,21 @@ pub trait IoIrq {
/// with `server` and the opcode number `usize` when an IRQ is detected on the port/pin.
/// The active state of the IRQ is defined by `active`; the transition edge from inactive
/// to active is when the event is generated.
fn set_irq_pin(&self, port: IoxPort, pin: u8, active: IoxValue, server: &str, opcode: usize);
///
/// Returns Some(index) which is required for future API calls to modify IRQ pin parameters.
/// If `None` is returned, the IRQ is unavailable (due a resource conflict, or exhausting of
/// interrupt routing slots - there are only 8 available in the hardware).
fn set_irq_pin(
&self,
port: IoxPort,
pin: u8,
active: IoxValue,
server: &str,
opcode: usize,
) -> Option<usize>;
/// `index` is the returned value from `set_irq_pin()`
fn update_irq_pin(&self, server: &str, index: usize, active: Option<IoxValue>, opcode: Option<usize>);
}
#[cfg_attr(feature = "derive-rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
@ -118,6 +147,17 @@ pub struct IoxIrqRegistration {
pub port: IoxPort,
pub pin: u8,
pub active: IoxValue,
pub index: Option<usize>,
}
#[cfg_attr(feature = "derive-rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[derive(Debug)]
#[cfg(feature = "std")]
pub struct IoxIrqUpdate {
pub server: String,
pub opcode: Option<usize>,
pub active: Option<IoxValue>,
pub index: usize,
}
#[cfg(feature = "std")]
@ -325,9 +365,24 @@ impl IoGpio for IoxHal {
#[cfg(feature = "std")]
impl IoIrq for IoxHal {
fn set_irq_pin(&self, port: IoxPort, pin: u8, active: IoxValue, server: &str, opcode: usize) {
let msg = IoxIrqRegistration { server: server.to_owned(), opcode, port, pin, active };
fn set_irq_pin(
&self,
port: IoxPort,
pin: u8,
active: IoxValue,
server: &str,
opcode: usize,
) -> Option<usize> {
let msg = IoxIrqRegistration { server: server.to_owned(), opcode, port, pin, active, index: None };
let mut buf = xous_ipc::Buffer::into_buf(msg).unwrap();
buf.lend_mut(self.conn, HalOpcode::ConfigureIoxIrq as u32).expect("Couldn't set up IRQ");
let ret: IoxIrqRegistration = buf.to_original().unwrap();
ret.index
}
fn update_irq_pin(&self, server: &str, index: usize, active: Option<IoxValue>, opcode: Option<usize>) {
let msg = IoxIrqUpdate { server: server.to_owned(), opcode, active, index };
let buf = xous_ipc::Buffer::into_buf(msg).unwrap();
buf.lend(self.conn, HalOpcode::ConfigureIoxIrq as u32).expect("Couldn't set up IRQ");
buf.lend(self.conn, HalOpcode::UpdateIoxIrq as u32).expect("Couldn't update IRQ");
}
}

View file

@ -91,6 +91,10 @@ pub enum KeyboardOpcode {
/// a blocking key listener - blocks until a key is hit
BlockingKeyListener = 9,
/// change orientation, and thus key mapping of directional keys. Behavior
/// depends on the hardware type selected.
SetOrientation = 128,
}
// this structure is used to register a keyboard listener.
@ -201,6 +205,20 @@ impl Keyboard {
.unwrap();
}
pub fn flip_orientation(&self, flipped: bool) {
send_message(
self.conn,
Message::new_scalar(
KeyboardOpcode::SetOrientation.to_usize().unwrap(),
if flipped { 1 } else { 0 },
0,
0,
0,
),
)
.unwrap();
}
/// Reveal the connection ID for use with unsafe FFI calls
pub fn conn(&self) -> xous::CID { self.conn }
}

View file

@ -514,6 +514,22 @@ impl<'a> Oled128x128<'a> {
Ok(())
}
pub fn flip_vertical(&mut self, flip: bool) -> Result<(), xous::Error> {
use Command::*;
let cmds = if flip {
// flipped
[SetSegmentReMap(true), SetCOMScanDirection(Direction::Normal)]
} else {
// normal
[SetSegmentReMap(false), SetCOMScanDirection(Direction::Inverted)]
};
for c in cmds {
let bytes = c.encode();
self.send_command(bytes)?;
}
Ok(())
}
pub fn powerdown(&mut self) {
self.powerdown = true;
// assert reset

View file

@ -112,6 +112,8 @@ pub enum GfxOpcode {
BaosecBitmap,
#[cfg(feature = "board-baosec")]
Brightness,
#[cfg(feature = "board-baosec")]
FlipScreen,
/// Gutter for invalid calls
InvalidCall,

View file

@ -801,6 +801,21 @@ impl Gfx {
.map(|_| ())
}
#[cfg(feature = "board-baosec")]
pub fn flip_screen(&self, flip: bool) -> Result<(), xous::Error> {
send_message(
self.conn,
Message::new_blocking_scalar(
GfxOpcode::FlipScreen.to_usize().unwrap(),
if flip { 1 } else { 0 },
0,
0,
0,
),
)
.map(|_| ())
}
#[cfg(feature = "hosted-baosec")]
pub fn acquire_qr(&self) -> Result<QrAcquisition, xous::Error> {
let dummy = "otpauth://totp/ACME%20Co:john.doe@email.com?secret=HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30".to_string();

View file

@ -902,6 +902,14 @@ pub fn wrapped_main(main_thread_token: MainThreadToken) -> ! {
.unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display));
}
}
#[cfg(feature = "board-baosec")]
GfxOpcode::FlipScreen => {
if let Some(scalar) = msg.body.scalar_message_mut() {
display
.flip_vertical(scalar.arg1 != 0)
.unwrap_or_else(|_| display_timeout_handler(&udma_global, &mut display))
}
}
GfxOpcode::Quit => break,
_ => {
// This is perfectly normal because not all opcodes are handled by all platforms.

View file

@ -190,6 +190,9 @@ fn keyboard_service() {
Some(KeyboardOpcode::HandlerTrigger) => {
todo!("Write this once we have an IRQ handler for keyboard interrupts");
}
Some(KeyboardOpcode::SetOrientation) => {
// nop - doesn't do anything on emulation
}
None => {
log::error!("couldn't convert KeyboardOpcode");
break;

View file

@ -34,7 +34,7 @@ bitfield! {
fn irq_select_from_port(port: IoxPort, pin: u8) -> u32 { (port as u32) * 16 + pin as u32 }
fn find_first_none<T>(arr: &[Option<T>]) -> Option<usize> { arr.iter().position(|item| item.is_none()) }
#[derive(Debug, Copy, Clone)]
#[derive(Debug)]
#[allow(dead_code)]
struct IrqLocalRegistration {
pub cid: xous::CID,
@ -42,6 +42,7 @@ struct IrqLocalRegistration {
pub port: IoxPort,
pub pin: u8,
pub active: IoxValue,
pub server: String,
}
struct IrqHandler {
@ -274,9 +275,12 @@ fn main() {
.expect("couldn't claim Iox interrupt");
irq.irq_csr.wo(utralib::utra::irqarray10::EV_PENDING, 0xFFFF_FFFF);
irq.irq_csr.wfo(utralib::utra::irqarray10::EV_ENABLE_IOXIRQ, 1);
// Up to 8 slots where we can populate interrupt mappings in the hardware
// The index of the array corresponds to the slot.
let mut irq_table: [Option<IrqLocalRegistration>; 8] = [None; 8];
// This is an [Option; 8] instead of a Vec because in hardware we have only
// 8 slots where we can populate interrupt mappings in the hardware. Each slot's
// index maps 1:1 to a hardware register offset. Thus as interrupts are de-allocated,
// we don't want the indices to change - in this case, Vec is not the right object,
// we want a static array defined like this.
let mut irq_table: [Option<IrqLocalRegistration>; 8] = [const { None }; 8];
let mut msg_opt = None;
log::debug!("Starting main loop");
@ -399,12 +403,12 @@ fn main() {
}
}
HalOpcode::ConfigureIoxIrq => {
let buf = unsafe {
let mut buf = unsafe {
xous_ipc::Buffer::from_memory_message(
msg_opt.as_mut().unwrap().body.memory_message().unwrap(),
msg_opt.as_mut().unwrap().body.memory_message_mut().unwrap(),
)
};
let registration = buf.to_original::<IoxIrqRegistration, _>().unwrap();
let mut registration = buf.to_original::<IoxIrqRegistration, _>().unwrap();
log::info!("Got registration request: {:?}", registration);
if let Some(index) = find_first_none(&irq_table) {
// create the reverse-lookup registration
@ -417,6 +421,7 @@ fn main() {
port: registration.port,
pin: registration.pin,
active: registration.active,
server: registration.server.to_owned(),
};
irq_table[index] = Some(local_reg);
@ -429,6 +434,7 @@ fn main() {
IoxValue::High => int_cr.set_mode(IntMode::RisingEdge as u32),
}
int_cr.set_enable(true);
int_cr.set_wakeup(true);
// safety: the index and offset are mapped to the intended range because the index is
// bounded by the size of irq_table, and the offset comes from the generated header
// file.
@ -448,10 +454,53 @@ fn main() {
.add(index)
.write_volatile(int_cr.0);
}
registration.index = Some(index);
buf.replace(registration).unwrap();
} else {
panic!("Ran out of Iox interrupt slots: maximum 8 available");
}
}
HalOpcode::UpdateIoxIrq => {
let buf = unsafe {
xous_ipc::Buffer::from_memory_message(
msg_opt.as_ref().unwrap().body.memory_message().unwrap(),
)
};
let update = buf.to_original::<IoxIrqUpdate, _>().unwrap();
log::debug!("Got IRQ update request: {:?}", update);
if let Some(Some(reg)) = irq_table.get_mut(update.index) {
if reg.server == update.server {
if let Some(active) = update.active {
reg.active = active;
// fetch the interrupt control register value
let mut int_cr = IntCr(unsafe {
iox.csr
.base()
.add(utralib::utra::iox::SFR_INTCR_CRINT0.offset())
.add(update.index)
.read_volatile()
});
// update the edge option
match active {
IoxValue::Low => int_cr.set_mode(IntMode::FallingEdge as u32),
IoxValue::High => int_cr.set_mode(IntMode::RisingEdge as u32),
}
// commit
unsafe {
iox.csr
.base()
.add(utralib::utra::iox::SFR_INTCR_CRINT0.offset())
.add(update.index)
.write_volatile(int_cr.0);
}
}
if let Some(opcode) = update.opcode {
reg.opcode = opcode;
}
}
}
}
HalOpcode::IrqLocalHandler => {
if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message() {
// Figure out which port(s) caused the IRQ
@ -462,7 +511,7 @@ fn main() {
for bitpos in 0..8 {
// the bit position is flipped versus register order in memory
if ((irq_flag << (bitpos as u32)) & 0x80) != 0 {
if let Some(local_reg) = irq_table[bitpos] {
if let Some(local_reg) = &irq_table[bitpos] {
found = true;
// interrupts are "Best effort" and can gracefully fail if the receiver
// has been overwhelmed by too many

View file

@ -62,10 +62,18 @@ struct KeyTracker {
pub rate_ms: usize,
pub delay_ms: usize,
pub keys: Vec<KeypressTimestamp>,
pub orientation_flipped: bool,
}
#[cfg(feature = "board-baosec")]
impl KeyTracker {
pub fn new() -> Self { KeyTracker { rate_ms: KEYUP_DELAY_MS as usize, delay_ms: 1000, keys: Vec::new() } }
pub fn new() -> Self {
KeyTracker {
rate_ms: KEYUP_DELAY_MS as usize,
delay_ms: 1000,
keys: Vec::new(),
orientation_flipped: false,
}
}
pub fn register_key_down(&mut self, key: KeyPress, ts: u64) {
if let Some(entry) = self.keys.iter_mut().find(|e| e.kp == key) {
@ -113,11 +121,13 @@ impl KeyTracker {
/// Returns any keys that should have repeat key-press events generated
pub fn get_repeats(&mut self, now: u64) -> Vec<char> {
let mut kps = Vec::new();
for key in self.keys.iter_mut() {
if now >= key.next_repeat_time {
kps.push(map_keypress(key.kp));
// use index-based iteration to avoid borrow checker issue on map_keypress() call
for i in 0..self.keys.len() {
if now >= self.keys[i].next_repeat_time {
let kp = self.keys[i].kp;
kps.push(self.map_keypress(kp));
// rebasing off of now prevents keys from "lagging on" in case of UI delay
key.next_repeat_time = now + self.rate_ms as u64;
self.keys[i].next_repeat_time = now + self.rate_ms as u64;
}
}
kps
@ -126,23 +136,47 @@ impl KeyTracker {
pub fn keys_pressed(&self) -> usize { self.keys.len() }
pub fn clear_keys(&mut self) { self.keys.clear(); }
}
#[cfg(feature = "board-baosec")]
fn map_keypress(kp: KeyPress) -> char {
match kp {
KeyPress::Down => '↓',
KeyPress::Up => '↑',
KeyPress::Left => '←',
KeyPress::Right => '→',
KeyPress::Select => '∴',
// "Fire" is used as the mapping for the center instead of carriage return ('\r' (0xd))
// because carriage return is reserved for the shell to indicate the end of line. Thus
// by mapping "fire" to the center key, we get a UI-specific action key without invoking
// shell commands in the background unintentionally.
KeyPress::Center => '🔥',
#[cfg(feature = "accel-kbd")]
KeyPress::Accel => '⏯',
_ => '\u{0000}',
pub fn map_keypress(&self, kp: KeyPress) -> char {
match kp {
KeyPress::Down => {
if self.orientation_flipped {
'↑'
} else {
'↓'
}
}
KeyPress::Up => {
if self.orientation_flipped {
'↓'
} else {
'↑'
}
}
KeyPress::Left => {
if self.orientation_flipped {
'→'
} else {
'←'
}
}
KeyPress::Right => {
if self.orientation_flipped {
'←'
} else {
'→'
}
}
KeyPress::Select => '∴',
// "Fire" is used as the mapping for the center instead of carriage return ('\r' (0xd))
// because carriage return is reserved for the shell to indicate the end of line. Thus
// by mapping "fire" to the center key, we get a UI-specific action key without invoking
// shell commands in the background unintentionally.
KeyPress::Center => '🔥',
#[cfg(feature = "accel-kbd")]
KeyPress::Accel => '⏯',
_ => '\u{0000}',
}
}
}
@ -475,7 +509,7 @@ fn keyboard_service() {
log::debug!("{:?}", key_down);
if key_down != KeyPress::Invalid && key_down != KeyPress::None {
key_tracker.register_key_down(key_down, now);
kc.push(map_keypress(key_down))
kc.push(key_tracker.map_keypress(key_down))
}
}
// the keys_pressed() check is necessary because the interrupt will fire *before* a key
@ -542,6 +576,12 @@ fn keyboard_service() {
log::warn!("Unhandled interrupt: {:x}", pending);
}
}),
Some(KeyboardOpcode::SetOrientation) => msg_scalar_unpack!(msg, _flipped, _, _, _, {
#[cfg(feature = "board-baosec")]
{
key_tracker.orientation_flipped = _flipped != 0;
}
}),
None => {
log::error!("couldn't convert KeyboardOpcode");
break;