From f4e8e73887e510c0d50763d9e6cfdd26c4a141c7 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 11 Mar 2021 10:48:25 +0800 Subject: [PATCH 01/13] xous: tag 0.1.1 Signed-off-by: Sean Cross --- xous-rs/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xous-rs/Cargo.toml b/xous-rs/Cargo.toml index ef4f60b1d..8ddf89b95 100644 --- a/xous-rs/Cargo.toml +++ b/xous-rs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "xous" -version = "0.1.0" +version = "0.1.1" authors = ["Sean Cross "] edition = "2018" license = "MIT OR Apache-2.0" From 530e105fe47f8c000d9b295cccaaf85be2b7e254 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 11 Mar 2021 11:19:51 +0800 Subject: [PATCH 02/13] xous: add GetProcessID and GetThreadID syscalls Signed-off-by: Sean Cross --- xous-rs/Cargo.toml | 2 +- xous-rs/src/syscall.rs | 52 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/xous-rs/Cargo.toml b/xous-rs/Cargo.toml index 8ddf89b95..e92c63b4b 100644 --- a/xous-rs/Cargo.toml +++ b/xous-rs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "xous" -version = "0.1.1" +version = "0.1.2" authors = ["Sean Cross "] edition = "2018" license = "MIT OR Apache-2.0" diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index cd07e5a2e..c663b24d1 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -299,6 +299,12 @@ pub enum SysCall { /// disclosing SIDs. ConnectForProcess(PID, SID), + /// Get the current Thread ID + GetThreadId, + + /// Get the current Process ID + GetProcessId, + /// This syscall does not exist. It captures all possible /// arguments so detailed analysis can be performed. Invalid(usize, usize, usize, usize, usize, usize, usize), @@ -336,6 +342,8 @@ pub enum SysCallNumber { CreateServer = 29, ConnectForProcess = 30, CreateServerId = 31, + GetThreadId = 32, + GetProcessId = 33, Invalid, } @@ -373,6 +381,8 @@ impl SysCallNumber { 29 => CreateServer, 30 => ConnectForProcess, 31 => CreateServerId, + 32 => GetThreadId, + 33 => GetProcessId, _ => Invalid, } } @@ -668,6 +678,24 @@ impl SysCall { 0, 0, ], + SysCall::GetThreadId => [SysCallNumber::GetThreadId as usize, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + SysCall::GetProcessId => [SysCallNumber::GetProcessId as usize, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7) => [ SysCallNumber::Invalid as usize, *a1, @@ -867,6 +895,8 @@ impl SysCall { SID::from_u32(a2 as _, a3 as _, a4 as _, a5 as _), ), SysCallNumber::CreateServerId => SysCall::CreateServerId, + SysCallNumber::GetThreadId => SysCall::GetThreadId, + SysCallNumber::GetProcessId => SysCall::GetProcessId, SysCallNumber::Invalid => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7), }) } @@ -1375,6 +1405,28 @@ pub fn wait_process(joiner: crate::arch::ProcessHandle) -> SysCallResult { crate::arch::wait_process(joiner) } +/// Get the current process ID +pub fn current_pid() -> SysCallResult { + rsyscall(SysCall::GetProcessId).and_then(|result| { + if let Result::ProcessID(pid) = result { + Ok(Result::ProcessID(pid)) + } else { + Err(Error::InternalError) + } + }) +} + +/// Get the current thread ID +pub fn current_tid() -> SysCallResult { + rsyscall(SysCall::GetProcessId).and_then(|result| { + if let Result::ThreadID(tid) = result { + Ok(Result::ThreadID(tid)) + } else { + Err(Error::InternalError) + } + }) +} + pub fn rsyscall(call: SysCall) -> SysCallResult { let mut ret = Result::Ok; let args = call.as_args(); From cf1e2435bc416d10c01e97f198e73f36a56f5c2a Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 11 Mar 2021 11:20:35 +0800 Subject: [PATCH 03/13] kernel: implement GetThreadID and GetProcessID Signed-off-by: Sean Cross --- kernel/Cargo.lock | 2 +- kernel/src/syscall.rs | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/kernel/Cargo.lock b/kernel/Cargo.lock index 798f3bd67..82b972d00 100644 --- a/kernel/Cargo.lock +++ b/kernel/Cargo.lock @@ -574,7 +574,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "xous" -version = "0.1.0" +version = "0.1.2" dependencies = [ "bitflags", "hex", diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 48596cbe8..f12e473e9 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -792,6 +792,12 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR SysCall::Shutdown => { SystemServices::with_mut(|ss| ss.shutdown().map(|_| xous_kernel::Result::Ok)) } + SysCall::GetProcessId => { + Ok(xous_kernel::Result::ProcessID(pid)) + } + SysCall::GetThreadId => { + Ok(xous_kernel::Result::ThreadID(tid)) + } SysCall::Connect(sid) => { let result = SystemServices::with_mut(|ss| { From d89ac9cf900370c5fe23fbc9bbca70c36fc37302 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 11 Mar 2021 11:21:12 +0800 Subject: [PATCH 04/13] Cargo: commit new lockfile Signed-off-by: Sean Cross --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index a1d3b93d7..93ab1095c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1536,7 +1536,7 @@ checksum = "b07db065a5cf61a7e4ba64f29e67db906fb1787316516c4e6e5ff0fea1efcd8a" [[package]] name = "xous" -version = "0.1.0" +version = "0.1.2" dependencies = [ "bitflags", "hex", From a0c82ee25c370d9f9cebe5a671d0504133436d08 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 11 Mar 2021 12:27:55 +0800 Subject: [PATCH 05/13] xous: initial draft of `xous` target support This is an initial cut of the library as it will be included in the libstd. Signed-off-by: Sean Cross --- xous-rs/Cargo.toml | 18 +++++++++++++--- xous-rs/src/arch/mod.rs | 8 ++++---- xous-rs/src/arch/native.rs | 12 +++++------ xous-rs/src/buffer.rs | 42 +++++++++++++++++++------------------- xous-rs/src/carton.rs | 13 ++++++------ xous-rs/src/definitions.rs | 20 ++++++++++++++++++ xous-rs/src/lib.rs | 19 ++++++++++------- xous-rs/src/process.rs | 20 ++++++------------ xous-rs/src/syscall.rs | 18 ++++++++-------- 9 files changed, 99 insertions(+), 71 deletions(-) diff --git a/xous-rs/Cargo.toml b/xous-rs/Cargo.toml index e92c63b4b..6aab704d7 100644 --- a/xous-rs/Cargo.toml +++ b/xous-rs/Cargo.toml @@ -7,21 +7,33 @@ license = "MIT OR Apache-2.0" description = "System call interface for Xous" [dependencies] -bitflags = "1" +bitflags = {version = "1", optional = true } xous-macros = { path = "../macros", version = "0.1.0" } log = { version = "0.4", optional = true } -rkyv = { version = "0.3.1", default_features = false } +rkyv = { version = "0.3.1", default_features = false, optional = true } +core = { version = '1.0.0', optional = true, package = 'rustc-std-workspace-core' } +compiler_builtins = { version = '0.1.0', optional = true } [features] + # If this is set, then the "Drop" feature of MemoryMessage structs # will not be implemented. This should only be set by the kernel. forget-memory-messages = [] +# Enable using `bitflags` +bit-flags = ["bitflags"] + +# Enable sending commands using `rkyv` +archive = ["rkyv"] + # `logging` causes this program to connect to a log server on startup # so you can run log commands such as `info!()`. logging = ["log"] -default = [] +# This is being built as part of libstd +rustc-dep-of-std = ['core', 'compiler_builtins/rustc-dep-of-std'] + +default = ["bit-flags", "archive"] [target.'cfg(any(windows,unix))'.dependencies] lazy_static = "1.4" diff --git a/xous-rs/src/arch/mod.rs b/xous-rs/src/arch/mod.rs index 481135b2e..e25ed479f 100644 --- a/xous-rs/src/arch/mod.rs +++ b/xous-rs/src/arch/mod.rs @@ -1,9 +1,9 @@ -#[cfg(target_os = "none")] +#[cfg(any(target_os = "none", target_os = "xous"))] pub mod native; -#[cfg(target_os = "none")] +#[cfg(any(target_os = "none", target_os = "xous"))] pub use native::*; -#[cfg(not(target_os = "none"))] +#[cfg(not(any(target_os = "none", target_os = "xous")))] pub mod hosted; -#[cfg(not(target_os = "none"))] +#[cfg(not(any(target_os = "none", target_os = "xous")))] pub use hosted::*; diff --git a/xous-rs/src/arch/native.rs b/xous-rs/src/arch/native.rs index b9cebc292..7f0411329 100644 --- a/xous-rs/src/arch/native.rs +++ b/xous-rs/src/arch/native.rs @@ -174,12 +174,12 @@ where T: Send + 'static, U: Send + 'static, { - let stack = crate::map_memory( - None, - None, - 131_072, - crate::MemoryFlags::R | crate::MemoryFlags::W | crate::MemoryFlags::RESERVE, - )?; + #[cfg(feature = "bit-flags")] + let flags = crate::MemoryFlags::R | crate::MemoryFlags::W | crate::MemoryFlags::RESERVE; + #[cfg(not(feature = "bit-flags"))] + let flags = 0b0000_0010 | 0b0000_0100 | 0b0000_0001; + + let stack = crate::map_memory(None, None, 131_072, flags)?; let start = unsafe { core::mem::transmute(*f) }; let arg = unsafe { core::mem::transmute(arg) }; Ok(ThreadInit::new(start, stack, Some(arg), [0; 12])) diff --git a/xous-rs/src/buffer.rs b/xous-rs/src/buffer.rs index 6b9a440cd..47926a150 100644 --- a/xous-rs/src/buffer.rs +++ b/xous-rs/src/buffer.rs @@ -1,4 +1,7 @@ -use crate::{Result, Error, MemoryMessage, MemoryRange, MemoryFlags, MemorySize, Message, CID, map_memory, send_message}; +use crate::{ + map_memory, send_message, Error, MemoryMessage, MemoryRange, MemorySize, Message, + Result, CID, +}; #[derive(Debug)] pub struct XousBuffer<'a> { @@ -11,16 +14,23 @@ pub struct XousBuffer<'a> { impl<'a> XousBuffer<'a> { #[allow(dead_code)] pub fn new(len: usize) -> Self { - let remainder = - if ((len & 0xFFF) == 0) && (len > 0) { 0 } - else { 0x1000 - (len & 0xFFF) }; + let remainder = if ((len & 0xFFF) == 0) && (len > 0) { + 0 + } else { + 0x1000 - (len & 0xFFF) + }; + + #[cfg(feature = "bit-flags")] + let flags = crate::MemoryFlags::R | crate::MemoryFlags::W; + #[cfg(not(feature = "bit-flags"))] + let flags = 0b0000_0010 | 0b0000_0100; let new_mem = map_memory( None, None, // Ensure our byte size is a multiple of 4096 len + remainder, - MemoryFlags::R | MemoryFlags::W, + flags, ) .expect("XousBuffer: error in new()/map_memory"); @@ -28,7 +38,9 @@ impl<'a> XousBuffer<'a> { valid.size = MemorySize::new(len + remainder).unwrap(); XousBuffer { range: new_mem, - slice: unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), len + remainder) }, + slice: unsafe { + core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), len + remainder) + }, valid, should_drop: true, } @@ -46,11 +58,7 @@ impl<'a> XousBuffer<'a> { /// Perform a mutable lend of this Carton to the server. #[allow(dead_code)] - pub fn lend_mut( - &mut self, - connection: CID, - id: u32, - ) -> core::result::Result { + pub fn lend_mut(&mut self, connection: CID, id: u32) -> core::result::Result { let msg = MemoryMessage { id: id as usize, buf: self.valid, @@ -61,11 +69,7 @@ impl<'a> XousBuffer<'a> { } #[allow(dead_code)] - pub fn lend( - &self, - connection: CID, - id: u32 - ) -> core::result::Result { + pub fn lend(&self, connection: CID, id: u32) -> core::result::Result { let msg = MemoryMessage { id: id as usize, buf: self.valid, @@ -76,11 +80,7 @@ impl<'a> XousBuffer<'a> { } #[allow(dead_code)] - pub fn send( - mut self, - connection: CID, - id: u32, - ) -> core::result::Result { + pub fn send(mut self, connection: CID, id: u32) -> core::result::Result { let msg = crate::MemoryMessage { id: id as usize, buf: self.valid, diff --git a/xous-rs/src/carton.rs b/xous-rs/src/carton.rs index c81a0d805..b087b5698 100644 --- a/xous-rs/src/carton.rs +++ b/xous-rs/src/carton.rs @@ -19,13 +19,12 @@ impl<'a> Carton<'a> { let remainder = bytes.len() & 4095; let size = bytes.len() + (4096 - remainder); - let new_mem = crate::map_memory( - None, - None, - size, - crate::MemoryFlags::R | crate::MemoryFlags::W, - ) - .unwrap(); + #[cfg(feature = "bit-flags")] + let flags = crate::MemoryFlags::R | crate::MemoryFlags::W; + #[cfg(not(feature = "bit-flags"))] + let flags = 0b0000_0010 | 0b0000_0100; + + let new_mem = crate::map_memory(None, None, size, flags).unwrap(); // NOTE: Remaining bytes are not zeroed. We assume the kernel has done this for us. unsafe { diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index b2b7b9b42..1c14e45dc 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -115,6 +115,7 @@ pub struct MemoryRange { pub size: MemorySize, } +#[cfg(feature = "bitflags")] bitflags! { /// Flags to be passed to the MapMemory struct. /// Note that it is an error to have memory be @@ -138,6 +139,25 @@ bitflags! { const X = 0b0000_1000; } } +#[cfg(feature = "bitflags")] +pub(crate) fn get_bits(bf: &MemoryFlags) -> usize { + bf.bits() +} +#[cfg(feature = "bitflags")] +pub(crate) fn from_bits(raw: usize) -> Option { + MemoryFlags::from_bits(raw) +} + +#[cfg(not(feature = "bitflags"))] +pub type MemoryFlags = usize; +#[cfg(not(feature = "bitflags"))] +pub(crate) fn get_bits(bf: &MemoryFlags) -> usize { + *bf +} +#[cfg(not(feature = "bitflags"))] +pub(crate) fn from_bits(raw: usize) -> Option { + Some(raw) +} pub fn pid_from_usize(src: usize) -> core::result::Result { if src > u8::MAX as _ { diff --git a/xous-rs/src/lib.rs b/xous-rs/src/lib.rs index 1229a7c14..805591e22 100644 --- a/xous-rs/src/lib.rs +++ b/xous-rs/src/lib.rs @@ -1,5 +1,6 @@ -#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(any(target_os = "none", target_os = "xous"), no_std)] +#[cfg(feature = "bitflags")] #[macro_use] extern crate bitflags; @@ -12,27 +13,30 @@ pub mod arch; pub mod carton; pub mod definitions; mod messages; -pub mod string; + pub mod buffer; -pub mod syscall; pub mod process; +#[cfg(feature = "archive")] +pub mod string; +pub mod syscall; pub mod names; pub use arch::{ProcessArgs, ProcessInit, ProcessKey, ThreadInit}; +pub use buffer::XousBuffer; pub use definitions::*; pub use messages::*; +#[cfg(feature = "archive")] pub use string::*; pub use syscall::*; -pub use buffer::XousBuffer; -#[cfg(not(target_os = "none"))] +#[cfg(not(any(target_os = "none", target_os = "xous")))] pub use arch::ProcessArgsAsThread; -#[cfg(target_os = "none")] +#[cfg(any(target_os = "none", target_os = "xous"))] pub fn init() {} -#[cfg(not(target_os = "none"))] +#[cfg(not(any(target_os = "none", target_os = "xous")))] pub fn init() { use std::panic; panic::set_hook(Box::new(|arg| { @@ -61,6 +65,7 @@ macro_rules! maybe_main { } fn main() { + #[cfg(not(target_os = "xous"))] xous::arch::ensure_connection().unwrap(); unsafe { xous_entry() }; } diff --git a/xous-rs/src/process.rs b/xous-rs/src/process.rs index 171a78f47..c0357d85f 100644 --- a/xous-rs/src/process.rs +++ b/xous-rs/src/process.rs @@ -1,17 +1,9 @@ -#[cfg(not(target_os = "none"))] pub fn id() -> u32 { - std::process::id() + if let Ok(crate::Result::ProcessID(pid)) = crate::syscall::current_pid() { + pid.get() as u32 + } else { + 0 + } } -#[cfg(target_os = "none")] -static PID_KEEPER: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); - -#[cfg(target_os = "none")] -pub fn id() -> u32 { - PID_KEEPER.load(core::sync::atomic::Ordering::Relaxed) -} - -#[cfg(target_os = "none")] -pub fn set_id(id: u32) { - PID_KEEPER.store(id, core::sync::atomic::Ordering::Relaxed) -} +pub fn set_id(_id: u32) {} diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index c663b24d1..1c242b5b8 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -8,7 +8,7 @@ use core::convert::TryInto; // use num_derive::FromPrimitive; // use num_traits::FromPrimitive; -#[cfg(not(target_os = "none"))] +#[cfg(not(any(target_os = "none", target_os = "xous")))] use crate::ProcessArgsAsThread; #[derive(Debug, PartialEq)] @@ -405,7 +405,7 @@ impl SysCall { a1.map(|x| x.get()).unwrap_or_default(), a2.map(|x| x.get()).unwrap_or_default(), a3.get(), - a4.bits(), + crate::get_bits(a4), 0, 0, 0, @@ -509,7 +509,7 @@ impl SysCall { SysCall::IncreaseHeap(a1, a2) => [ SysCallNumber::IncreaseHeap as usize, *a1 as usize, - a2.bits(), + crate::get_bits(a2), 0, 0, 0, @@ -530,7 +530,7 @@ impl SysCall { SysCallNumber::UpdateMemoryFlags as usize, a1.get(), *a2 as usize, - a3.bits(), + crate::get_bits(a3), 0, 0, 0, @@ -725,7 +725,7 @@ impl SysCall { MemoryAddress::new(a1), MemoryAddress::new(a2), MemoryAddress::new(a3).ok_or(Error::InvalidSyscall)?, - MemoryFlags::from_bits(a4).ok_or(Error::InvalidSyscall)?, + crate::from_bits(a4).ok_or(Error::InvalidSyscall)?, ), SysCallNumber::UnmapMemory => { SysCall::UnmapMemory(MemoryRange::new(a1, a2).or(Err(Error::InvalidSyscall))?) @@ -749,13 +749,13 @@ impl SysCall { SysCallNumber::ReadyThreads => SysCall::ReadyThreads(pid_from_usize(a1)?), SysCallNumber::IncreaseHeap => SysCall::IncreaseHeap( a1 as usize, - MemoryFlags::from_bits(a2).ok_or(Error::InvalidSyscall)?, + crate::from_bits(a2).ok_or(Error::InvalidSyscall)?, ), SysCallNumber::DecreaseHeap => SysCall::DecreaseHeap(a1 as usize), SysCallNumber::UpdateMemoryFlags => SysCall::UpdateMemoryFlags( MemoryAddress::new(a1).ok_or(Error::InvalidSyscall)?, a2 as usize, - MemoryFlags::from_bits(a3).ok_or(Error::InvalidSyscall)?, + crate::from_bits(a3).ok_or(Error::InvalidSyscall)?, ), SysCallNumber::SetMemRegion => SysCall::SetMemRegion( pid_from_usize(a1)?, @@ -1364,7 +1364,7 @@ pub fn wait_thread(joiner: crate::arch::WaitHandle) -> SysCallResult { } /// Create a new process by running it in its own thread -#[cfg(not(target_os = "none"))] +#[cfg(not(any(target_os = "none", target_os = "xous")))] pub fn create_process_as_thread( args: ProcessArgsAsThread, ) -> core::result::Result @@ -1382,7 +1382,7 @@ where } /// Wait for a thread to finish -#[cfg(not(target_os = "none"))] +#[cfg(not(any(target_os = "none", target_os = "xous")))] pub fn wait_process_as_thread(joiner: crate::arch::ProcessHandleAsThread) -> SysCallResult { crate::arch::wait_process_as_thread(joiner) } From b8dfa1ddcb52e3163831c3f8605318a723a990ce Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 11 Mar 2021 18:28:38 +0800 Subject: [PATCH 06/13] Update README.md --- services/gam/README.md | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/services/gam/README.md b/services/gam/README.md index 9a7f9f06f..9926afd5d 100644 --- a/services/gam/README.md +++ b/services/gam/README.md @@ -108,27 +108,3 @@ but for MVP we simply avoid having multiple applications contend for access to the same `Canvas`. - --------------------- - - - -The problem is: -1. you don't have access to the drawing objects; they are domiciled in the apps -2. you don't want to just clear large regions of the FB; that will slow things down. -You want to take advantage of dirty bits as much as possible for good performance. -3. It would be nice to be able to have a more trusted "pop-up" on top of a less -trusted app, and have it obscure the lower app. - -Options include: - -1. A bitmap that stores the drawable mask based on a trust level. This would have -to be recalculated from the priority queue for each Canvas every time the queue -is updated. This structure consumes 24kiB per canvas in this case... -2. Coming up with an arbitrary polygonal region (that can also support holes) and -then doing maths to figure out if a point may or may not be updated. This would -be memory efficient but rather time and CPU-inefficient to compute. -3. Disallowing overlapping Canvas features?? -4. Maintaining each Canvas with a bitmap that has the latest drawing on it, -updating only that bitmap, and then doing compositing and dirty bit computation -before sending off to the graphics engine? From d24a8a67b51de33d580e9f9939bdf36a0edc2196 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 11 Mar 2021 18:49:30 +0800 Subject: [PATCH 07/13] Update README.md --- services/gam/README.md | 77 +++++++++++++++++++++++++----------------- 1 file changed, 46 insertions(+), 31 deletions(-) diff --git a/services/gam/README.md b/services/gam/README.md index 9926afd5d..59cabac6d 100644 --- a/services/gam/README.md +++ b/services/gam/README.md @@ -4,37 +4,47 @@ The GAM provides abstract UI primitives to other modules. The goal is to have this module work in close conjunction with the `graphics-server`, and all other modules would route abstract UI -requests through this module. +requests through this module. ## Structure +At a high level, you can think of the GAM as a firewall around the `graphics-server`. +The `graphics-server` has no concept of what pixel belongs where; it's happy +to mutate a pixel that is anywhere within the physical hardware framebuffer. + +Giving processes direct access to `graphics-server` means that a less trusted +program could draw into an OS-reserved area, thus presenting false information +to a user. The GAM solves this problem by dividing the screen into `Canvas` objects. ### Canvas A `Canvas` is a minimal data structure that defines a physical region of the screen that will display a set of primitives. `Canvas` structures are domiciled -in the UI server, and are considered trusted by default, although there is +in the GAM server, and are considered trusted by default, although there is a flag that can be cleared to make everything within it untrusted. Each `Canvas` has a 128-bit GUID. Application processes that wish to draw something to the screen must refer to a `Canvas` by its 128-bit GUID; it is up -to the GAM to not share secure GUIDs with insecure processes. +to the GAM to not share secure GUIDs with insecure processes. Thus the security +of a `Canvas` rests in the difficulty of guessing the 128-bit GUID, and also +in the system not leaking GUIDs. -The `Canvas` selection is modal on a per-connection basis. In other words, -an application can request several `Canvas` objects to draw on, but it -must first send a `SelectCanvas` command first to pick the right `Canvas`. -By default, the last requested `Canvas` is the default `Canvas` for a -given connection to the GAM. +Every GAM drawing object includes the GUID of the `Canvas` to which it should be drawn. +Upon receiving a draw request, it validates that the GUID exists, and applies +any other relevant rules (for example, a higher security process can use the +GAM to prohibit all drawing of lower security processes by marking their +`Canvas` as not drawable). -The region of the physical screen that can be drawn on by a `Canvas` is -defined by a `clip_rect`. The coordinate space of the `clip_rect` is fixed +All GAM drawing objects specify pixel offsets from a `(0,0)` top-left coordinate +system. The GAM then handles translating these offsets from a virtual `(0,0)` +Canvas offset to a physical region of a screen through the `clip_rect` +record within the `Canvas`. The coordinate space of the `clip_rect` is fixed to the screen's coordinates, that is, `(0,0)` in the top left, X increasing to the right, Y increasing down. -A `Canvas` stores a `pan_offset`. If the pan offset is `(0,0)`, then the top left -corner of the `clip_rect` corresponds to data drawn at location `(0,0)` inside -the `Canvas`. The `pan_offset` is added to every coordinate inside the objects that -refer to a `Canvas` at render time; this allows for easy implementation -of panning and scrolling. +A `Canvas` also stores a `pan_offset`. The `pan_offset` is added to every +coordinate inside the objects that refer to a `Canvas` and then the result +is clipped with `clip_rect`; this allows for easy implementation +of panning and scrolling. (Note: this feature is largely untested as of March 2021) A `Canvas` has a `trust_level` associated with it. Higher numbers are more trusted; 255 is the highest level of trust. Rules for drawing are as follows: @@ -81,13 +91,23 @@ control over customizing their interfaces, and also helps introduce a layer of protection against phishing; however it also means that UX designers will not be able to have exquisite control over the "look and feel" of their applications. -`TextView` objects are domiciled on the application process. Process-local API -calls can "simulate" certain properties (such as figuring out the dynamic -width or height of a text box based on the size of the string within) to assist -with laying out `TextViews`. Once the layout is finalized, the `TextView` objects -are then immutably lent to the GAM using an `rkyv` lend wrapper; +`TextView` objects are domiciled on the application process. The application +process is responsible for guiding the rough layout of where `TextView`s go +in a canvas. Once the object is finalized, the `TextView` objects +are then mutably lent to the GAM using an `rkyv` lend wrapper; the calling thread then blocks until the GAM completes the rendering operation. +For layouts that need to adjust in height based on variable-length text strings, +the calling application can use the `bounds_hint`/`TextBounds` to help manage this. +The bounds of a `TextView` can either be a fixed-sized rectangle, or a box that +grows up and out from a point plus a width. So, for example, a `TextView` could have +an anchor in the lower-right hand corner, plus a maximum width, and the height of the +box will be computed based as the text is rendered. The height of text can't be +known a-priori, because for example, emoji glyphs and hanzi characters will +have a different height than latin characters. A `dry_run` option is also +available for a `TextView` so one can simulate the rendering to determine the height +without paying the compuational price. + One can think of a `TextView` as a text bubble, that can have rounded or square corners, and its content string can be rendered with a selection of options that specify the glyph style (*not* a font -- it's more of a hint than a specifier), @@ -95,16 +115,11 @@ aligment, and the size of the text bubble. The text bubble can either be of a fixed size (such that the string will show ellipses `...` if it overruns the bubble), or of a dynamically growable size based on its content. +Thus, a typical "chat-style" app where text bubbles show a history of the chat +going from the most recent at the bottom of the screen to the oldest at the top, +would start by rendering variable-height text bubbles on the bottom, getting the +returned value of the rendered height, and setting the height of the next bubble +on top for rendering, and then rendering that. + `TextView` can both be directly rendered to a `Canvas`, or managed by secondary object such as a `Menu` or `List` to compose other UI elements. - -`TextView` supports a `draw_order` attribute, which allows multiple `TextViews` -within a single application to be stacked on top of each other. -Note that `draw_order` can only be respected within the context of a single application; -if two applications are drawing to the same `Canvas`, then who gets the last -draw depend on who sends the last update request. This might be fixable later -on with a bit to "mutex" the drawing of other applications to enforce an order, -but for MVP we simply avoid having multiple applications contend for access to -the same `Canvas`. - - From 443e4a144412c13236529c2594928806cd59b0df Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 11 Mar 2021 18:52:10 +0800 Subject: [PATCH 08/13] remove draw_order from TextView We can't support this anyways, because the textviews are immediately drawn on call by the calling app --- services/gam/src/status.rs | 4 ++-- services/graphics-server/src/api/text.rs | 7 +------ services/ime-frontend/src/main.rs | 6 +++--- services/shellchat/src/main.rs | 4 ++-- 4 files changed, 8 insertions(+), 13 deletions(-) diff --git a/services/gam/src/status.rs b/services/gam/src/status.rs index 0a3a50d5d..6ad8ff169 100644 --- a/services/gam/src/status.rs +++ b/services/gam/src/status.rs @@ -25,7 +25,7 @@ pub fn status_thread(canvas_gid: [u32; 4]) { if debug1{info!("GAM|status: building textview objects");} // build uptime text view: left half of status bar - let mut uptime_tv = TextView::new(status_gid, 0, + let mut uptime_tv = TextView::new(status_gid, TextBounds::BoundingBox(Rectangle::new(Point::new(0,0), Point::new(screensize.x / 2, screensize.y - 1)))); uptime_tv.untrusted = false; @@ -37,7 +37,7 @@ pub fn status_thread(canvas_gid: [u32; 4]) { if debug1{info!("GAM|status: uptime initialized to '{:?}'", uptime_tv);} // build battstats text view: right half of status bar - let mut battstats_tv = TextView::new(status_gid, 0, + let mut battstats_tv = TextView::new(status_gid, TextBounds::BoundingBox(Rectangle::new(Point::new(screensize.x / 2, 0), Point::new(screensize.x, screensize.y - 1)))); battstats_tv.style = blitstr::GlyphStyle::Small; diff --git a/services/graphics-server/src/api/text.rs b/services/graphics-server/src/api/text.rs index 3002e606f..6f77e2697 100644 --- a/services/graphics-server/src/api/text.rs +++ b/services/graphics-server/src/api/text.rs @@ -54,9 +54,6 @@ pub struct TextView { pub token: Option<[u32; 4]>, // optional 128-bit token which is presented to prove a field's trustability pub invert: bool, // only trusted, token-validated TextViews will have the invert bit respected - // lower numbers are drawn last - pub draw_order: u32, - // offsets for text drawing -- exactly one of the following options should be specified // note that the TextBounds coordinate system is local to the canvas, not the screen pub bounds_hint: TextBounds, @@ -83,13 +80,12 @@ pub struct TextView { pub clip_rect: Option, // this is set by the GAM to the canvas' clip_rect; needed by gfx for drawing. Note this is in screen coordinates. } impl TextView { - pub fn new(canvas: Gid, draw_order: u32, bounds_hint: TextBounds) -> Self { + pub fn new(canvas: Gid, bounds_hint: TextBounds) -> Self { TextView { operation: TextOp::Nop, untrusted: true, token: None, invert: false, - draw_order, clip_rect: None, bounds_hint, bounds_computed: None, @@ -124,7 +120,6 @@ impl TextView { self.untrusted = t.untrusted; self.token = t.token; self.invert = t.invert; - self.draw_order = t.draw_order; self.bounds_hint = t.bounds_hint; self.bounds_computed = t.bounds_computed; self.style = t.style; diff --git a/services/ime-frontend/src/main.rs b/services/ime-frontend/src/main.rs index 259730e77..4fa00804e 100644 --- a/services/ime-frontend/src/main.rs +++ b/services/ime-frontend/src/main.rs @@ -219,7 +219,7 @@ impl InputTracker { if let Some(ic) = self.input_canvas { if debug1{info!("IMEF: updating input area");} let ic_bounds: Point = gam::get_canvas_bounds(self.gam_conn, ic).expect("IMEF: Couldn't get input canvas bounds"); - let mut input_tv = TextView::new(ic, 255, + let mut input_tv = TextView::new(ic, TextBounds::BoundingBox(Rectangle::new(Point::new(0,1), ic_bounds))); input_tv.draw_border = false; input_tv.border_width = 1; @@ -524,7 +524,7 @@ impl InputTracker { } if valid_predictions == 0 { - let mut empty_tv = TextView::new(pc, 255, + let mut empty_tv = TextView::new(pc, TextBounds::BoundingBox(Rectangle::new(Point::new(0, 1), pc_bounds))); empty_tv.draw_border = false; empty_tv.border_width = 1; @@ -554,7 +554,7 @@ impl InputTracker { DrawStyle { fill_color: None, stroke_color: Some(PixelColor::Dark), stroke_width: 1 } )).expect("IMEF: couldn't draw dividing lines in prediction area"); } - let mut p_tv = TextView::new(pc, 255, + let mut p_tv = TextView::new(pc, TextBounds::BoundingBox(p_clip)); p_tv.draw_border = false; p_tv.border_width = 1; diff --git a/services/shellchat/src/main.rs b/services/shellchat/src/main.rs index 88c96f57d..d49315962 100644 --- a/services/shellchat/src/main.rs +++ b/services/shellchat/src/main.rs @@ -153,12 +153,12 @@ impl Repl{ for h in self.history.iter().rev() { let mut bubble_tv = if h.is_input { - TextView::new(self.content, 255, + TextView::new(self.content, TextBounds::GrowableFromBr( Point::new(self.screensize.x - self.margin.x, bubble_baseline), self.bubble_width)) } else { - TextView::new(self.content, 255, + TextView::new(self.content, TextBounds::GrowableFromBl( Point::new(self.margin.x, bubble_baseline), self.bubble_width)) From ae418f5718c137c72f8d432e9b684f736ea4d592 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 11 Mar 2021 22:31:38 +0800 Subject: [PATCH 09/13] refactor shellchat API to have less repeated code --- services/shellchat/README.md | 14 ++++++++++++++ services/shellchat/src/cmds.rs | 23 +++++++++++++++++++++-- services/shellchat/src/cmds/echo.rs | 14 +------------- services/shellchat/src/cmds/sensors.rs | 15 ++------------- services/shellchat/src/cmds/sleep.rs | 16 ++-------------- services/shellchat/src/cmds/test.rs | 14 +------------- 6 files changed, 41 insertions(+), 55 deletions(-) create mode 100644 services/shellchat/README.md diff --git a/services/shellchat/README.md b/services/shellchat/README.md new file mode 100644 index 000000000..341fec838 --- /dev/null +++ b/services/shellchat/README.md @@ -0,0 +1,14 @@ +# Shell Chat + +`shellchat` is a baseline demo application for Xous. It uses a chat-client +style interface (stacking bubbles of text, with user input right-aligned +and shell feedback left-aligned) to facilitate interactions with the hardware. +It implements the basic envisioned structure of a Xous application, namely: + + - Text input comes via the `ime-frontend` + - Graphical output is rendered via the `gam` + +Other facilities for handling system-level messages, such as menu configurations +and network events, have yet to be implemented. However, they will likely end up +with a demo in this application first. + diff --git a/services/shellchat/src/cmds.rs b/services/shellchat/src/cmds.rs index 785aed3e5..f0135dec6 100644 --- a/services/shellchat/src/cmds.rs +++ b/services/shellchat/src/cmds.rs @@ -2,13 +2,32 @@ use xous::String; use core::fmt::Write; pub trait ShellCmdApi<'a> { - // checks if the command matches the current verb in question - fn matches(&self, verb: &str) -> bool; + // user implemented: // called to process the command with the remainder of the string attached fn process(&mut self, rest: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error>; + + // created with cmd_api! macro + // checks if the command matches the current verb in question + fn matches(&self, verb: &str) -> bool; // returns my verb fn verb(&self) -> &'static str; } +// the argument to this macro is the command verb +macro_rules! cmd_api { + ($verb:expr) => { + fn verb(&self) -> &'static str { + stringify!($verb) + } + fn matches(&self, verb: &str) -> bool { + if verb == stringify!($verb) { + true + } else { + false + } + } + }; +} + /// extract the first token, as delimited by spaces /// modifies the incoming line by removing the token and returning the remainder diff --git a/services/shellchat/src/cmds/echo.rs b/services/shellchat/src/cmds/echo.rs index 2c572faa0..226edefd1 100644 --- a/services/shellchat/src/cmds/echo.rs +++ b/services/shellchat/src/cmds/echo.rs @@ -5,22 +5,10 @@ use xous::String; pub struct Echo { } -const VERB: &str = "echo"; - impl<'a> ShellCmdApi<'a> for Echo { - fn matches(&self, verb: &str) -> bool { - if verb == VERB { - true - } else { - false - } - } + cmd_api!(echo); // inserts boilerplate for command API fn process(&mut self, rest: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { Ok(Some(rest)) } - - fn verb(&self) -> &'static str { - VERB - } } \ No newline at end of file diff --git a/services/shellchat/src/cmds/sensors.rs b/services/shellchat/src/cmds/sensors.rs index 420376c16..46e661bb6 100644 --- a/services/shellchat/src/cmds/sensors.rs +++ b/services/shellchat/src/cmds/sensors.rs @@ -10,9 +10,10 @@ impl Sensors { } } -const VERB: &str = "sensors"; impl<'a> ShellCmdApi<'a> for Sensors { + cmd_api!(sensors); + fn process(&mut self, _rest: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; let mut ret = String::<1024>::new(); @@ -29,16 +30,4 @@ impl<'a> ShellCmdApi<'a> for Sensors { Ok(Some(ret)) } - - - fn verb(&self) -> &'static str { - VERB - } - fn matches(&self, verb: &str) -> bool { - if verb == VERB { - true - } else { - false - } - } } \ No newline at end of file diff --git a/services/shellchat/src/cmds/sleep.rs b/services/shellchat/src/cmds/sleep.rs index 080d0d8d1..96b5b1080 100644 --- a/services/shellchat/src/cmds/sleep.rs +++ b/services/shellchat/src/cmds/sleep.rs @@ -10,9 +10,9 @@ impl Sleep { } } -const VERB: &str = "sleep"; - impl<'a> ShellCmdApi<'a> for Sleep { + cmd_api!(sleep); // inserts boilerplate for command API + fn process(&mut self, _rest: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; @@ -41,16 +41,4 @@ impl<'a> ShellCmdApi<'a> for Sleep { Ok(Some(ret)) } } - - - fn verb(&self) -> &'static str { - VERB - } - fn matches(&self, verb: &str) -> bool { - if verb == VERB { - true - } else { - false - } - } } \ No newline at end of file diff --git a/services/shellchat/src/cmds/test.rs b/services/shellchat/src/cmds/test.rs index 74dc08dd7..81464ccdd 100644 --- a/services/shellchat/src/cmds/test.rs +++ b/services/shellchat/src/cmds/test.rs @@ -13,16 +13,8 @@ impl Test { } } -const VERB: &str = "test"; - impl<'a> ShellCmdApi<'a> for Test { - fn matches(&self, verb: &str) -> bool { - if verb == VERB { - true - } else { - false - } - } + cmd_api!(test); fn process(&mut self, _rest: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; @@ -32,8 +24,4 @@ impl<'a> ShellCmdApi<'a> for Test { write!(ret, "Test has run {} times.", self.state).unwrap(); Ok(Some(ret)) } - - fn verb(&self) -> &'static str { - VERB - } } \ No newline at end of file From d2ef03b7e28f931d9087a2537ce49901abb07f13 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 11 Mar 2021 22:32:05 +0800 Subject: [PATCH 10/13] intermediate commit to try and lock in a bug --- Cargo.lock | 17 +++++++++++++++++ services/gam/src/canvas.rs | 12 ++++++------ services/gam/src/main.rs | 7 +++++-- services/gam/src/status.rs | 2 +- services/graphics-server/src/api/text.rs | 11 ++++++----- services/ime-frontend/src/main.rs | 9 ++++++--- 6 files changed, 41 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 93ab1095c..ed21811f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -261,6 +261,15 @@ dependencies = [ "com_rs", ] +[[package]] +name = "compiler_builtins" +version = "0.1.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3748f82c7d366a0b4950257d19db685d4958d2fa27c6d164a3f069fec42b748b" +dependencies = [ + "rustc-std-workspace-core", +] + [[package]] name = "content-plugin-api" version = "0.1.0" @@ -1028,6 +1037,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +[[package]] +name = "rustc-std-workspace-core" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1956f5517128a2b6f23ab2dadf1a976f4f5b27962e7724c2bf3d45e539ec098c" + [[package]] name = "ryu" version = "1.0.5" @@ -1539,10 +1554,12 @@ name = "xous" version = "0.1.2" dependencies = [ "bitflags", + "compiler_builtins", "hex", "lazy_static", "log", "rkyv", + "rustc-std-workspace-core", "xous-macros", ] diff --git a/services/gam/src/canvas.rs b/services/gam/src/canvas.rs index c379bc629..fa6994a5f 100644 --- a/services/gam/src/canvas.rs +++ b/services/gam/src/canvas.rs @@ -22,21 +22,21 @@ pub enum CanvasState { /// A rectangular region that defines a top-left zero relative offset for graphical items /// and a bottom-right point that defines a clipping area for things drawn inside. #[derive(Debug, Copy, Clone)] -#[repr(C)] pub struct Canvas { + // unique, random identifier for the Canvas + gid: Gid, + // screen coordinates of the clipping region clip_rect: Rectangle, // trust level, 255 is most trusted trust_level: u8, - state: CanvasState, - - // unique, random identifier for the Canvas - gid: Gid, - // enables scroll/pan of objects within a region pan_offset: Point, + + // track the drawing state of the canvas + state: CanvasState, } #[allow(dead_code)] diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index 6f81163d4..6488dcb5e 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -25,6 +25,7 @@ use heapless::consts::*; use rkyv::{Unarchive, archived_value, archived_value_mut}; use core::pin::Pin; +#[derive(Debug)] // GIDs of canvases that are used the "Chat" layout. struct ChatLayout { // a set of GIDs to track the elements of the chat layout @@ -178,6 +179,7 @@ impl ModalCanvases { #[xous::xous_main] fn xmain() -> ! { let debug1 = false; // debug level 1 - most general level + let debugc = false; log_server::init_wait().unwrap(); info!("GAM: my PID is {}", xous::process::id()); @@ -194,7 +196,7 @@ fn xmain() -> ! { // a map of canvases accessable by Gid let mut canvases: FnvIndexMap = FnvIndexMap::new(); - let modallayout = ModalCanvases::init(trng_conn, &mut canvases).expect("GAM: can't add modal layouts"); + // let modallayout = ModalCanvases::init(trng_conn, &mut canvases).expect("GAM: can't add modal layouts"); let mut chatlayout = ChatLayout::init(gfx_conn, trng_conn, &mut canvases).expect("GAM: couldn't create chat layout"); chatlayout.clear(&mut canvases).expect("GAM: couldn't clear initial chatlayout"); @@ -217,6 +219,7 @@ fn xmain() -> ! { // no content canvas initially, but keep a placeholder for one let mut ccc: ContentCanvasConnection = ContentCanvasConnection{connection: None}; + if debugc{info!("GAM: chatlayout made st {:?} co {:?} pr {:?} in {:?}", chatlayout.status, chatlayout.content, chatlayout.predictive, chatlayout.input);} // make a thread to manage the status bar -- this needs to start after the IMEF is initialized // the status bar is a trusted element managed by the OS, and we are chosing to domicile this in the GAM process for now xous::create_thread_simple(status_thread, chatlayout.status.gid()).expect("GAM: couldn't create status thread"); @@ -327,7 +330,7 @@ fn xmain() -> ! { info!("GAM: attempt to draw TextView on non-drawable canvas. Not fatal, but request ignored."); } } else { - info!("GAM: bogus GID in TextView, not doing anything in response to draw request."); + info!("GAM: bogus GID {:?} in TextView {}, not doing anything in response to draw request.", tv.get_canvas_gid(), tv.text); // silently fail if a bogus Gid is given??? } }, diff --git a/services/gam/src/status.rs b/services/gam/src/status.rs index 6ad8ff169..d3ad58935 100644 --- a/services/gam/src/status.rs +++ b/services/gam/src/status.rs @@ -15,9 +15,9 @@ pub fn status_thread(canvas_gid: [u32; 4]) { if debug1{info!("GAM|status: registering GAM|status thread");} let status_sid = xous_names::register_name(xous::names::SERVER_NAME_STATUS).expect("GAM|status: can't register server"); + let gam_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_GAM).expect("GAM|status: can't connect to GAM"); let ticktimer_conn = xous::connect(xous::SID::from_bytes(b"ticktimer-server").unwrap()).unwrap(); let com_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_COM).expect("GAM|status: can't connect to COM"); - let gam_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_GAM).expect("GAM|status: can't connect to GAM"); if debug1{info!("GAM|status: getting screen size");} let screensize = gam::get_canvas_bounds(gam_conn, status_gid).expect("GAM|status: Couldn't get canvas size"); diff --git a/services/graphics-server/src/api/text.rs b/services/graphics-server/src/api/text.rs index 6f77e2697..9e812561e 100644 --- a/services/graphics-server/src/api/text.rs +++ b/services/graphics-server/src/api/text.rs @@ -46,6 +46,9 @@ const TEXTVIEW_LEN: usize = 3072; #[derive(Copy, Clone, rkyv::Archive, rkyv::Unarchive)] pub struct TextView { + canvas: Gid, // GID of the canvas to draw on + pub clip_rect: Option, // this is set by the GAM to the canvas' clip_rect; needed by gfx for drawing. Note this is in screen coordinates. + // this is the operation as specified for the GAM. Note this is different from the "op" when sent to graphics-server // only the GAM should be sending TextViews to the graphics-server, and a different coding scheme is used for that link. operation: TextOp, @@ -62,7 +65,6 @@ pub struct TextView { pub dry_run: bool, // set to true if no drawing is desired and we just want to compute the bounds pub style: GlyphStyle, - pub text: xous::String::<3072>, pub cursor: Cursor, pub insertion: Option, // this is the insertion point offset, if it's to be drawn, on the string pub ellipsis: bool, @@ -76,12 +78,12 @@ pub struct TextView { // this field specifies the beginning and end of a "selected" region of text pub selected: Option<[u32; 2]>, - canvas: Gid, // GID of the canvas to draw on - pub clip_rect: Option, // this is set by the GAM to the canvas' clip_rect; needed by gfx for drawing. Note this is in screen coordinates. + pub text: xous::String::<3072>, } impl TextView { pub fn new(canvas: Gid, bounds_hint: TextBounds) -> Self { TextView { + canvas, operation: TextOp::Nop, untrusted: true, token: None, @@ -99,7 +101,6 @@ impl TextView { rounded_border: None, margin: Point { x: 4, y: 4 }, selected: None, - canvas, clear_area: true, overflow: None, dry_run: false, @@ -116,6 +117,7 @@ impl TextView { pub fn clear_str(&mut self) { self.text.clear() } pub fn populate_from(&mut self, t: &TextView) { + self.canvas = t.canvas; self.operation = t.operation; self.untrusted = t.untrusted; self.token = t.token; @@ -131,7 +133,6 @@ impl TextView { self.rounded_border = t.rounded_border; self.margin = t.margin; self.selected = t.selected; - self.canvas = t.canvas; self.overflow = t.overflow; self.clip_rect = t.clip_rect; self.dry_run = t.dry_run; diff --git a/services/ime-frontend/src/main.rs b/services/ime-frontend/src/main.rs index 4fa00804e..615d3f111 100644 --- a/services/ime-frontend/src/main.rs +++ b/services/ime-frontend/src/main.rs @@ -523,6 +523,7 @@ impl InputTracker { } } + let debug_canvas = false; if valid_predictions == 0 { let mut empty_tv = TextView::new(pc, TextBounds::BoundingBox(Rectangle::new(Point::new(0, 1), pc_bounds))); @@ -530,6 +531,7 @@ impl InputTracker { empty_tv.border_width = 1; empty_tv.clear_area = true; write!(empty_tv.text, "Ready for input...").expect("IMEF: couldn't set up empty TextView"); + if debug_canvas { info!("IMEF: pc canvas {:?}", pc) } gam::post_textview(self.gam_conn, &mut empty_tv).expect("IMEF: can't draw prediction TextView"); } else if update_predictor { // alright, first, let's clear the area @@ -578,7 +580,8 @@ impl InputTracker { #[xous::xous_main] fn xmain() -> ! { let debug1 = false; - let dbglistener = true; + let dbglistener = false; + let dbgcanvas = false; log_server::init_wait().unwrap(); info!("IMEF: my PID is {}", xous::process::id()); @@ -601,11 +604,11 @@ fn xmain() -> ! { if let Ok(opcode) = ImefOpcode::try_from(&envelope.body) { match opcode { ImefOpcode::SetInputCanvas(g) => { - if debug1{info!("IMEF: got input canvas {:?}", g);} + if debug1 || dbgcanvas {info!("IMEF: got input canvas {:?}", g);} tracker.set_input_canvas(g); }, ImefOpcode::SetPredictionCanvas(g) => { - if debug1{info!("IMEF: got prediction canvas {:?}", g);} + if debug1 || dbgcanvas {info!("IMEF: got prediction canvas {:?}", g);} tracker.set_pred_canvas(g); }, _ => info!("IMEF: expected canvas Gid, but got {:?}", opcode) From 307df04e8b232ef305e0fd4b2d1f8c67328d59b1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 11 Mar 2021 22:33:57 +0800 Subject: [PATCH 11/13] a commit that exhibits the string bug --- services/graphics-server/src/api/text.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/services/graphics-server/src/api/text.rs b/services/graphics-server/src/api/text.rs index 9e812561e..f3a92bed4 100644 --- a/services/graphics-server/src/api/text.rs +++ b/services/graphics-server/src/api/text.rs @@ -46,9 +46,6 @@ const TEXTVIEW_LEN: usize = 3072; #[derive(Copy, Clone, rkyv::Archive, rkyv::Unarchive)] pub struct TextView { - canvas: Gid, // GID of the canvas to draw on - pub clip_rect: Option, // this is set by the GAM to the canvas' clip_rect; needed by gfx for drawing. Note this is in screen coordinates. - // this is the operation as specified for the GAM. Note this is different from the "op" when sent to graphics-server // only the GAM should be sending TextViews to the graphics-server, and a different coding scheme is used for that link. operation: TextOp, @@ -65,6 +62,7 @@ pub struct TextView { pub dry_run: bool, // set to true if no drawing is desired and we just want to compute the bounds pub style: GlyphStyle, + pub text: xous::String::<3072>, pub cursor: Cursor, pub insertion: Option, // this is the insertion point offset, if it's to be drawn, on the string pub ellipsis: bool, @@ -78,7 +76,8 @@ pub struct TextView { // this field specifies the beginning and end of a "selected" region of text pub selected: Option<[u32; 2]>, - pub text: xous::String::<3072>, + canvas: Gid, // GID of the canvas to draw on + pub clip_rect: Option, // this is set by the GAM to the canvas' clip_rect; needed by gfx for drawing. Note this is in screen coordinates. } impl TextView { pub fn new(canvas: Gid, bounds_hint: TextBounds) -> Self { From 685f36af410f29d04338ec11d3049bdf46c3eb5d Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 11 Mar 2021 22:35:57 +0800 Subject: [PATCH 12/13] commit that shows the bug fixed --- services/graphics-server/src/api/text.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/graphics-server/src/api/text.rs b/services/graphics-server/src/api/text.rs index f3a92bed4..b8d196100 100644 --- a/services/graphics-server/src/api/text.rs +++ b/services/graphics-server/src/api/text.rs @@ -62,7 +62,6 @@ pub struct TextView { pub dry_run: bool, // set to true if no drawing is desired and we just want to compute the bounds pub style: GlyphStyle, - pub text: xous::String::<3072>, pub cursor: Cursor, pub insertion: Option, // this is the insertion point offset, if it's to be drawn, on the string pub ellipsis: bool, @@ -78,6 +77,8 @@ pub struct TextView { canvas: Gid, // GID of the canvas to draw on pub clip_rect: Option, // this is set by the GAM to the canvas' clip_rect; needed by gfx for drawing. Note this is in screen coordinates. + + pub text: xous::String::<3072>, } impl TextView { pub fn new(canvas: Gid, bounds_hint: TextBounds) -> Self { From 4006df3c4fc0f7a07e8024ea39ca094fef7b80ed Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 11 Mar 2021 22:54:24 +0800 Subject: [PATCH 13/13] add instructions on how to make commands --- services/shellchat/README.md | 30 +++++++ services/shellchat/src/cmds.rs | 117 +++++++++++++------------ services/shellchat/src/cmds/echo.rs | 4 +- services/shellchat/src/cmds/sensors.rs | 2 +- services/shellchat/src/cmds/sleep.rs | 2 +- services/shellchat/src/cmds/test.rs | 2 +- 6 files changed, 94 insertions(+), 63 deletions(-) diff --git a/services/shellchat/README.md b/services/shellchat/README.md index 341fec838..5b576fd5f 100644 --- a/services/shellchat/README.md +++ b/services/shellchat/README.md @@ -12,3 +12,33 @@ Other facilities for handling system-level messages, such as menu configurations and network events, have yet to be implemented. However, they will likely end up with a demo in this application first. +To make your own command, copy the `echo.rs` template or snag the one below, and put +it in the services/shellchat/src/cmds/ directory: + +```Rust +use crate::{ShellCmdApi, CommonEnv}; +use xous::String; + +#[derive(Debug)] +pub struct Echo { +} + +impl<'a> ShellCmdApi<'a> for Echo { + cmd_api!(echo); // inserts boilerplate for command API + + fn process(&mut self, args: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { + Ok(Some(rest)) + } +} +``` + +The "verb" is the name of your command, and it is the argument to the `cmd_api!()` macro. + +`process()` is your "main" function, and `args` is a string which contains the +rest of the line that was typed into the chat, minus the verb used to identify +your command (the arguments, as they may be, but not tokenized or parsed in +any way). `env` contains some items in a common environment, for example, connections +to the GAM, LLIO server or other resources required by your implementation. + +Once you've added your command to the directory, go to the `cmds.rs` file, and follow +the four-step instructions embedded within the file, starting around line 40. \ No newline at end of file diff --git a/services/shellchat/src/cmds.rs b/services/shellchat/src/cmds.rs index f0135dec6..b21da8449 100644 --- a/services/shellchat/src/cmds.rs +++ b/services/shellchat/src/cmds.rs @@ -1,10 +1,10 @@ use xous::String; use core::fmt::Write; - +/////////////////////////// Common items to all commands pub trait ShellCmdApi<'a> { // user implemented: // called to process the command with the remainder of the string attached - fn process(&mut self, rest: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error>; + fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error>; // created with cmd_api! macro // checks if the command matches the current verb in question @@ -28,41 +28,7 @@ macro_rules! cmd_api { }; } - -/// extract the first token, as delimited by spaces -/// modifies the incoming line by removing the token and returning the remainder -/// returns the found token -/// note: we don't have split() because of nostd -pub fn tokenize(line: &mut String::<1024>) -> Option> { - let mut token = String::<1024>::new(); - let mut retline = String::<1024>::new(); - - let lineiter = line.as_str().unwrap().chars(); - let mut foundspace = false; - let mut foundrest = false; - for ch in lineiter { - if ch != ' ' && !foundspace { - token.push(ch).unwrap(); - } else if foundspace && foundrest { - retline.push(ch).unwrap(); - } else if foundspace && ch != ' ' { - // handle case of multiple spaces in a row - foundrest = true; - retline.push(ch).unwrap(); - } else { - foundspace = true; - // consume the space - } - } - line.clear(); - write!(line, "{}", retline.as_str().unwrap()).unwrap(); - if token.len() > 0 { - Some(token) - } else { - None - } -} - +/////////////////////////// Command shell integration #[derive(Debug)] pub struct CommonEnv { llio: xous::CID, @@ -71,18 +37,29 @@ pub struct CommonEnv { gam: xous::CID, } -mod echo; -use echo::*; -mod test; -use test::*; -mod sleep; -use sleep::*; -mod sensors; -use sensors::*; +/* + To add a new command: + 0. ensure that the command implements the ShellCmdApi (above) + 1. mod/use the new command + 2. create an entry for the command's storage in the CmdEnv structure + 3. initialize the persistant storage here + 4. add it to the "commands" array in the dispatch() routine below + + Side note: if your command doesn't require persistent storage, you could, + technically, generate the command dynamically every time it's called. Echo + demonstrates this. +*/ + +///// 1. add your module here, and pull its namespace into the local crate +mod echo; use echo::*; +mod test; use test::*; +mod sleep; use sleep::*; +mod sensors; use sensors::*; #[derive(Debug)] pub struct CmdEnv { common_env: CommonEnv, + ///// 2. declare storage for your command here. test_cmd: Test, sleep_cmd: Sleep, sensors_cmd: Sensors, @@ -90,18 +67,6 @@ pub struct CmdEnv { impl CmdEnv { pub fn new(gam: xous::CID) -> CmdEnv { let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); - /* - To add a new command: - - ensure that the command implements the ShellCmdApi - - mod/use the new command (above) - - create an entry for the command's storage in the CmdEnv structure - - initialize the persistant storage here - - add it to the "commands" array in the dispatch() routine below - - Side note: if your command doesn't require persistent storage, you could, - technically, generate the command dynamically every time it's called. Echo - demonstrates this. - */ CmdEnv { common_env: CommonEnv { llio: xous_names::request_connection_blocking(xous::names::SERVER_NAME_LLIO).expect("CMD: can't connect to LLIO"), @@ -109,6 +74,7 @@ impl CmdEnv { ticktimer: xous::connect(ticktimer_server_id).unwrap(), gam, }, + ///// 3. initialize your storage, by calling new() test_cmd: Test::new(), sleep_cmd: Sleep::new(), sensors_cmd: Sensors::new(), @@ -120,6 +86,7 @@ impl CmdEnv { let mut echo_cmd = Echo {}; // this command has no persistent storage, so we can "create" it every time we call dispatch (but it's a zero-cost absraction so this doesn't actually create any instructions) let commands: &mut [& mut dyn ShellCmdApi] = &mut [ + ///// 4. add your command to this array, so that it can be looked up and dispatched &mut echo_cmd, &mut self.test_cmd, &mut self.sleep_cmd, @@ -161,4 +128,38 @@ impl CmdEnv { Ok(None) } } -} \ No newline at end of file +} + +/// extract the first token, as delimited by spaces +/// modifies the incoming line by removing the token and returning the remainder +/// returns the found token +/// note: we don't have split() because of nostd +pub fn tokenize(line: &mut String::<1024>) -> Option> { + let mut token = String::<1024>::new(); + let mut retline = String::<1024>::new(); + + let lineiter = line.as_str().unwrap().chars(); + let mut foundspace = false; + let mut foundrest = false; + for ch in lineiter { + if ch != ' ' && !foundspace { + token.push(ch).unwrap(); + } else if foundspace && foundrest { + retline.push(ch).unwrap(); + } else if foundspace && ch != ' ' { + // handle case of multiple spaces in a row + foundrest = true; + retline.push(ch).unwrap(); + } else { + foundspace = true; + // consume the space + } + } + line.clear(); + write!(line, "{}", retline.as_str().unwrap()).unwrap(); + if token.len() > 0 { + Some(token) + } else { + None + } +} diff --git a/services/shellchat/src/cmds/echo.rs b/services/shellchat/src/cmds/echo.rs index 226edefd1..8f64ddedd 100644 --- a/services/shellchat/src/cmds/echo.rs +++ b/services/shellchat/src/cmds/echo.rs @@ -8,7 +8,7 @@ pub struct Echo { impl<'a> ShellCmdApi<'a> for Echo { cmd_api!(echo); // inserts boilerplate for command API - fn process(&mut self, rest: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { - Ok(Some(rest)) + fn process(&mut self, args: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { + Ok(Some(args)) } } \ No newline at end of file diff --git a/services/shellchat/src/cmds/sensors.rs b/services/shellchat/src/cmds/sensors.rs index 46e661bb6..286d85653 100644 --- a/services/shellchat/src/cmds/sensors.rs +++ b/services/shellchat/src/cmds/sensors.rs @@ -14,7 +14,7 @@ impl Sensors { impl<'a> ShellCmdApi<'a> for Sensors { cmd_api!(sensors); - fn process(&mut self, _rest: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process(&mut self, _args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; let mut ret = String::<1024>::new(); diff --git a/services/shellchat/src/cmds/sleep.rs b/services/shellchat/src/cmds/sleep.rs index 96b5b1080..96cfd0942 100644 --- a/services/shellchat/src/cmds/sleep.rs +++ b/services/shellchat/src/cmds/sleep.rs @@ -13,7 +13,7 @@ impl Sleep { impl<'a> ShellCmdApi<'a> for Sleep { cmd_api!(sleep); // inserts boilerplate for command API - fn process(&mut self, _rest: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process(&mut self, _args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; let mut ret = String::<1024>::new(); diff --git a/services/shellchat/src/cmds/test.rs b/services/shellchat/src/cmds/test.rs index 81464ccdd..71150a63b 100644 --- a/services/shellchat/src/cmds/test.rs +++ b/services/shellchat/src/cmds/test.rs @@ -16,7 +16,7 @@ impl Test { impl<'a> ShellCmdApi<'a> for Test { cmd_api!(test); - fn process(&mut self, _rest: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { + fn process(&mut self, _args: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { use core::fmt::Write; self.state += 1;