diff --git a/Cargo.lock b/Cargo.lock index 04bd72417..47bb19765 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -251,6 +251,25 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +[[package]] +name = "gam" +version = "0.1.0" +dependencies = [ + "bitflags", + "blitstr", + "com", + "graphics-server", + "heapless", + "keyboard", + "log", + "log-server", + "ticktimer-server", + "trng", + "utralib", + "xous", + "xous-names", +] + [[package]] name = "generic-array" version = "0.12.3" diff --git a/Cargo.toml b/Cargo.toml index ef59dac54..63669edad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "services/xous-names", "services/keyboard", "services/trng", + "services/gam", "svd2utra", "xtask", ] @@ -26,7 +27,8 @@ default-members = [ "services/xous-names", "services/keyboard", "services/com", - "services/trng" + "services/trng", + "services/gam", ] # These packages have custom RUSTFLAGS, so if they diff --git a/services/com/src/main.rs b/services/com/src/main.rs index 41b5539f6..f0274f264 100644 --- a/services/com/src/main.rs +++ b/services/com/src/main.rs @@ -266,6 +266,7 @@ fn xmain() -> ! { Opcode::PowerOffSoc => { info!("COM: power off called"); com.txrx(ComState::POWER_OFF.verb); + com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); // consume the obligatory return value, even if not used } Opcode::BattStats => { info!("COM: batt stats request received"); diff --git a/services/gam/Cargo.toml b/services/gam/Cargo.toml new file mode 100644 index 000000000..f393437c9 --- /dev/null +++ b/services/gam/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "gam" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "Graphical Abstraction Manager for Xous" + +[dependencies] +bitflags = "1.2.1" +xous = { path = "../../xous-rs" } +graphics-server = { path = "../graphics-server" } +ticktimer-server = { path = "../ticktimer-server" } +xous-names = { path = "../xous-names" } +log-server = { path = "../log-server" } +keyboard = { path = "../keyboard" } +trng = { path = "../trng" } +heapless = "0.5" +log = "0.4" + +com = { path = "../com"} + +# blitstr = { path = "../../../blitstr" } +blitstr = { git = "https://github.com/betrusted-io/blitstr.git", rev = "ea27e611d5ee165d8be894f9ca1c1130156c1931" } + + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +debugprint = [] +# default = ["debugprint"] # "debugprint" +default = [] diff --git a/services/gam/README.md b/services/gam/README.md new file mode 100644 index 000000000..7cabda10d --- /dev/null +++ b/services/gam/README.md @@ -0,0 +1,129 @@ +# Graphical Abstraction Manager (GAM) + +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. + +## Structure + +### 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 +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. + +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. + +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 +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` has a `trust_level` associated with it. Higher numbers are more +trusted; 255 is the highest level of trust. More trusted `Canvas` objects always +render on top of lower trusted object; furthermore, when a higher trusted +`Canvas` object overlaps a lower trusted object, the lower trusted object is +defaced using hatched lines with a random angle and spacing, and further updates +are disallowed. Thus, a `Canvas` should *not* be thought of like a "window", as +windows in typical UIs are allowed to freely overlap and clipping is handled +by simply drawing over lower layers of content. + +In the case that both trusted and untrusted data should be rendered on the same +screen, `Canvas` makes it strongly preferred to render them next to each other, rather +than one on top of each other. This policy is partially to help users be very +clear as to e.g. where a password box is vs. an image that looks a lot like +a password box; but the policy is also informed by the limitations of the underlying +hardware. In particular, the underlying memory LCD strongly +relies on "dirty bits" for good performance, and doing full-region redraws to +handle dirty rectangles on window movement is not an efficient use of dirty +bits. Reducing time spent redrawing partially obscured windows is also good +for performance and helps to simplify the code base, but these last two considerations +are quite minor compared to the primary concern of a "least confusing" UI when +it comes to differentiating between trustable and less trustable regions of the +screen. + +Thus, the simple rule is: don't stack content types of different trust levels. +If you require content stacking, this can be done for content within a single +trust level by using multiple objects within a `Canvas`, as they have a `draw_order` +attribute and can handle content stacking; but between trust domains, it's both +a trust and complexity issue to allow for simultaneous stacking of trust domains +with live, full-content update of the underlying layers. + +### TextView + +A `TextView` object is a heavy data structure that contains both a `xous::String` +and metadata which guides the GAM on how to render the string. Please note +the philosophy of the GAM is to hide the exact details of how anything is +rendered to the calling application. This both allows users to have greater +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 a `xous::ipc::Sendable.lend()` wrapper; +the calling thread then blocks until the GAM completes the rendering operation. + +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), +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. + +`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`. + + + +-------------------- + + + +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? diff --git a/services/gam/build.rs b/services/gam/build.rs new file mode 100644 index 000000000..43c3deb4f --- /dev/null +++ b/services/gam/build.rs @@ -0,0 +1,17 @@ +// NOTE: Adapted from cortex-m/build.rs +use std::env; + +fn main() { + let target = env::var("TARGET").unwrap(); + + let target_os = target.split('-').nth(2).unwrap_or("none"); + + // If we're not running on a desktop-class operating system, emit the "baremetal" + // config setting. This will enable software to do tasks such as + // managing memory. + if target_os == "none" { + println!("cargo:rustc-cfg=baremetal"); + } + + println!("cargo:rerun-if-changed=build.rs"); +} diff --git a/services/gam/src/api.rs b/services/gam/src/api.rs new file mode 100644 index 000000000..37d81ec2a --- /dev/null +++ b/services/gam/src/api.rs @@ -0,0 +1,96 @@ +use xous::{Message, ScalarMessage}; +use graphics_server::{Point, Rectangle}; +use blitstr::{GlyphStyle, Cursor}; + +#[derive(Debug, Copy, Clone)] +pub enum TextAlignment { + Left, + Center, + Right, +} + +#[derive(Debug, Copy, Clone)] +pub enum TextBounds { + // fixed width and height in a rectangle + BoundingBox(Rectangle), + // fixed width, grows up from bottom right + GrowableFromBr(Point, u16), + // fixed width, grows down from top left + GrowableFromTl(Point, u16), + // fixed width, grows up from bottom left + GrowableFromBl(Point, u16), +} + +#[repr(C)] +pub struct TextView<'a> { + untrusted: bool, // render content with random stipples to indicate the strings within are untrusted + token: Option<[u32; 4]>, // optional 128-bit token which is presented to prove a field's trustability + invert: bool, // only trusted, token-validated TextViews will have the invert bit respected + + // lower numbers are drawn last + draw_order: usize, + + // offsets for text drawing -- exactly one of the following options should be specified + bounds: TextBounds, + computed_bounds: Option, // is Some(Rectangle) if bounds have been computed and text has not been modified + + style: GlyphStyle, + text: xous::String<'a>, + alignment: TextAlignment, + + draw_border: bool, + border_width: u16, + rounded_border: bool, + x_margin: u16, + y_margin: u16, + + // this field specifies the beginning and end of a "selected" region of text + selected: Option<[usize; 2]>, + + canvas: [u32; 4], // GID of the canvas to draw on +} + +//#[derive(Debug)] +pub enum Opcode<'a> { + // clears a canvas with a given GID + ClearCanvas([u32; 4]), + + // renders a TextView + RenderTextView(TextView<'a>), + + // returns a GID to the "content" Canvas; requires an authentication token + RequestContentCanvas([u32; 4]), + + // hides a canvas with a given GID + HideCanvas([u32; 4]), + + // requests the GID to the "input" Canvas; call only works once (for the IME server), then maps out + RequestInputCanvas(), + + // indicates if the current UI layout requires an input field + HasInput(bool), +} + +impl<'a> core::convert::TryFrom<&'a Message> for Opcode<'a> { + type Error = &'static str; + fn try_from(message: &'a Message) -> Result { + match message { + Message::Scalar(m) => match m.id { + 0 => Ok(Opcode::ClearCanvas([m.arg1 as _, m.arg2 as _, m.arg3 as _, m.arg4 as _])), + _ => Err("GAM api: unknown Scalar ID"), + }, + _ => Err("GAM api: unhandled message type"), + } + } +} + +impl<'a> Into for Opcode<'a> { + fn into(self) -> Message { + match self { + Opcode::ClearCanvas(gid) => Message::Scalar(ScalarMessage { + id: 0, arg1: gid[0] as _, arg2: gid[1] as _, arg3: gid[2] as _, arg4: gid[3] as _ + }), + _ => panic!("GAM api: Opcode type not handled by Into(), maybe you meant to use a helper method?"), + } + } +} diff --git a/services/gam/src/canvas.rs b/services/gam/src/canvas.rs new file mode 100644 index 000000000..e3cb4e77a --- /dev/null +++ b/services/gam/src/canvas.rs @@ -0,0 +1,128 @@ +use core::cmp::Ordering; +use heapless::binary_heap::{BinaryHeap, Max}; +use heapless::FnvIndexMap; +use heapless::Vec; +use heapless::consts::*; +use graphics_server::{Rectangle, Point}; + +#[derive(Debug, Copy, Clone)] +pub enum CanvasState { + // the initial state of every Canvas. Not drawable. + Created, + // this state indicates the Canvas can be drawn, but has yet to be. + DrawableDirty, + // this state indicates the Canvas has been drawn. + DrawableDrawn, + // indicates that the Canvas is not drawable, but needs to be defaced + NotDrawableDirty, + // indicates that the Canvas is not drawable, and has been defaced + NotDrawableDefaced, +} + +/// 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 { + // 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: [u32; 4], + + // enables scroll/pan of objects within a region + pan_offset: Point, +} + +// we need the "screen" parameter so we can turn off drawing to canvases that are off-screen +pub fn recompute_canvases(mut canvases: BinaryHeap, screen: Rectangle) -> (BinaryHeap, FnvIndexMap<[u32; 4], Canvas, U32>) { + let mut higher_clipregions: BinaryHeap = BinaryHeap::new(); + + let mut trust_level: u8 = 255; + // canvases is a Max heap keyed on trust, so popping the elements off will return them sorted from most to least trusted + if let Some(c) = canvases.pop() { + let mut canvas = c.clone(); + + let mut drawable: bool = true; + let clip_region = canvas.clip_rect(); + if trust_level < canvas.trust_level() { + trust_level = canvas.trust_level(); + } + // note that this .iter() is *not* sorted by trust level, but all elements will be of greater than or equal to the current trust level + for ®ion in higher_clipregions.iter() { + // regions of the same trust level can draw over each other. Draw order is arbitrary. + if region.clip_rect().intersects(clip_region) && (region.trust_level() < trust_level) || + !region.clip_rect().intersects(screen) { + drawable = false; + } + } + match canvas.state() { + CanvasState::Created => + if drawable { canvas.set_state(CanvasState::DrawableDirty) } + else { canvas.set_state(CanvasState::NotDrawableDirty) }, + CanvasState::DrawableDirty | CanvasState::DrawableDrawn => + if !drawable { canvas.set_state(CanvasState::NotDrawableDirty) }, + CanvasState::NotDrawableDefaced | CanvasState::NotDrawableDirty => + if drawable { canvas.set_state(CanvasState::DrawableDirty) } + } + higher_clipregions.push(canvas).unwrap(); + } + + let mut map: FnvIndexMap<[u32; 4], Canvas, U32> = FnvIndexMap::new(); + for &c in higher_clipregions.iter() { + map.insert(c.gid(), c).unwrap(); + } + + (higher_clipregions, map) +} + +impl Canvas { + pub fn new(clip_rect: Rectangle, trust_level: u8, + trng_conn: xous::CID, pan_offset: Option) -> Result { + + let mut gid: [u32; 4] = [0; 4]; + let g: u64 = trng::get_u64(trng_conn)?; + gid[0] = g as u32; + gid[1] = (g >> 32) as u32; + let g: u64 = trng::get_u64(trng_conn)?; + gid[2] = g as u32; + gid[3] = (g >> 32) as u32; + + Ok(if pan_offset.is_some() { + Canvas { + clip_rect, trust_level, state: CanvasState::Created, gid, pan_offset: pan_offset.unwrap() + } + } else { + Canvas { + clip_rect, trust_level, state: CanvasState::Created, gid, pan_offset: Point::new(0, 0) + } + }) + } + pub fn clip_rect(&self) -> Rectangle { self.clip_rect } + pub fn gid(&self) -> [u32; 4] { self.gid } + pub fn trust_level(&self) -> u8 { self.trust_level } + pub fn state(&self) -> CanvasState { self.state } + pub fn set_state(&mut self, state: CanvasState) { self.state = state; } +} + +impl Ord for Canvas { + fn cmp(&self, other: &Self) -> Ordering { + self.trust_level.cmp(&other.trust_level) + } +} +impl PartialOrd for Canvas { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} +impl PartialEq for Canvas { + fn eq(&self, other: &Self) -> bool { + self.trust_level == other.trust_level + } +} +impl Eq for Canvas {} diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs new file mode 100644 index 000000000..b8f844226 --- /dev/null +++ b/services/gam/src/main.rs @@ -0,0 +1,118 @@ +#![cfg_attr(baremetal, no_main)] +#![cfg_attr(baremetal, no_std)] + +mod api; +use api::*; +mod status; +use status::*; +mod canvas; +use canvas::*; + +use blitstr::{Cursor, GlyphStyle}; +use com::*; +use core::fmt::Write; +use graphics_server::{Circle, DrawStyle, Line, PixelColor, Point, Rectangle}; + +use log::{error, info}; +use xous::String; + +use core::convert::TryFrom; + +use heapless::binary_heap::{BinaryHeap, Max}; +use heapless::FnvIndexMap; +use heapless::consts::*; + +#[xous::xous_main] +fn xmain() -> ! { + log_server::init_wait().unwrap(); + + info!("GAM: starting up..."); + let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); + let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); + + let gfx_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_GFX).expect("GAM: can't connect to COM"); + let trng_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_TRNG).expect("GAM: can't connect to TRNG"); + + let screensize = graphics_server::screen_size(gfx_conn).expect("GAM: Couldn't get screen size"); + + graphics_server::set_glyph_style(gfx_conn, GlyphStyle::Small).expect("GAM: couldn't set glyph style"); + let (_, small_height_tuple) = graphics_server::query_glyph(gfx_conn).expect("GAM: couldn't get glyph height"); + let small_height: i16 = small_height_tuple as i16; + graphics_server::set_glyph_style(gfx_conn, GlyphStyle::Regular).expect("GAM: couldn't set glyph style"); + let (_, regular_height_tuple) = graphics_server::query_glyph(gfx_conn).expect("GAM: couldn't get glyph height"); + let regular_height: i16 = regular_height_tuple as i16; + + let mut canvases: BinaryHeap = BinaryHeap::new(); + let mut status_canvas = Canvas::new( + Rectangle::new_coords(0, 0, screensize.x, small_height), + 0, trng_conn, None + ).expect("GAM: couldn't create status canvas"); + canvases.push(status_canvas).expect("GAM: can't store status canvus"); + + let mut password_canvas = Canvas::new( + Rectangle::new_coords(-1, -1, -1, -1), + 0, trng_conn, None + ).expect("GAM: couldn't create password canvas"); + canvases.push(password_canvas).expect("GAM: can't store password canvas"); + + let mut predictive_canvas = Canvas::new( + Rectangle::new_coords(0, screensize.y - regular_height, screensize.x, screensize.y), + 1, + trng_conn, None + ).expect("GAM: couldn't create predictive text canvas"); + canvases.push(predictive_canvas).expect("GAM: couldn't store predictive canvas"); + + let mut input_canvas = Canvas::new( + Rectangle::new_v_stack(predictive_canvas.clip_rect(), -regular_height), + 1, trng_conn, None + ).expect("GAM: couldn't create input text canvas"); + canvases.push(input_canvas).expect("GAM: couldn't store input canvas"); + + let mut content_canvas = Canvas::new( + Rectangle::new_v_span(status_canvas.clip_rect(), input_canvas.clip_rect()), + 2, trng_conn, None + ).expect("GAM: couldn't create content canvas"); + canvases.push(content_canvas).expect("GAM: can't store content canvas"); + + let mut canvas_map: FnvIndexMap<[u32;4], Canvas, U32>; + // this is broken into two steps because of https://github.com/rust-lang/rust/issues/71126 + let (c_tuple, m_tuple) = recompute_canvases(canvases, Rectangle::new(Point::new(0, 0), screensize)); + canvases = c_tuple; canvas_map = m_tuple; + + // make a thread to manage the status bar + xous::create_thread_simple(status_thread, status_canvas.gid()).expect("GAM: couldn't create status thread"); + + let gam_sid = xous_names::register_name(xous::names::SERVER_NAME_GAM).expect("GAM: can't register server"); + + info!("GAM: entering main loop"); + loop { + let maybe_env = xous::try_receive_message(gam_sid).unwrap(); + match maybe_env { + Some(envelope) => { + info!("GAM: Message: {:?}", envelope); + if let Ok(opcode) = Opcode::try_from(&envelope.body) { + match opcode { + Opcode::ClearCanvas(gid) => { + match canvas_map.get(&gid) { + Some(c) => { + let mut rect = c.clip_rect(); + rect.style = DrawStyle { + fill_color: Some(PixelColor::Light), + stroke_color: Some(PixelColor::Light), + stroke_width: 1, + }; + graphics_server::draw_rectangle(gfx_conn, rect).expect("GAM: can't clear canvas"); + }, + None => info!("GAM: attempt to clear bogus canvas, ignored."), + } + }, + _ => todo!("GAM: opcode not yet implemented"), + } + } + } + _ => xous::yield_slice(), + } + + graphics_server::flush(gfx_conn).expect("GAM: couldn't flush buffer to screen"); + } +} diff --git a/services/gam/src/status.rs b/services/gam/src/status.rs new file mode 100644 index 000000000..8dd5d50e7 --- /dev/null +++ b/services/gam/src/status.rs @@ -0,0 +1,4 @@ + +pub fn status_thread(status_gid: [u32; 4]) { + +} \ No newline at end of file diff --git a/services/graphics-server/src/api.rs b/services/graphics-server/src/api.rs index 1f55ddda1..8b342168d 100644 --- a/services/graphics-server/src/api.rs +++ b/services/graphics-server/src/api.rs @@ -1,5 +1,17 @@ #![allow(dead_code)] +/* + Primitives needed: + + - clipping rectangles (for drawing) + - rounded rectangles + - inverse text + - icons/sprites + - width of a text string with a given font (to compute alignments) + - untrusted backgrounds + - bitmaps + +*/ use crate::op::{HEIGHT, WIDTH}; use blitstr::{ClipRect, Cursor, GlyphStyle}; use core::cmp::{max, min}; @@ -271,6 +283,43 @@ impl Rectangle { style: DrawStyle::default(), } } + // stack a new rectangle on top of the current one (same width) + // positive widths go *below*, negative go *above* in screen coordinate space. borders are non-overlapping. + pub fn new_v_stack(reference: Rectangle, width: i16) -> Rectangle { + if width >= 0 { // rectangle below + Rectangle::new_coords(reference.tl.x, reference.br.y + 1, + reference.br.x, reference.br.y + width + 1) + } else { // rectangle above + Rectangle::new_coords(reference.tl.x, reference.tl.y + width - 1, + reference.br.x, reference.tl.y - 1) + } + } + // make a new rectangle than spans between the above and below rectangles. the borders are non-overlapping. + pub fn new_v_span(above: Rectangle, below: Rectangle) -> Rectangle { + Rectangle::new_coords(above.tl.x, above.br.y + 1, below.br.x, below.tl.y - 1) + } + // "stack" a rectangle to the left or right of the current one (same height) + // positive widths go to the right, negative to the left. borders are non-overlapping + pub fn new_h_stack(reference: Rectangle, width: i16) -> Rectangle { + if width >= 0 { // stack to the right + Rectangle::new_coords(reference.br.x + 1, reference.tl.y, + reference.br.x + width + 1, reference.br.y) + } else { // stack to the left + Rectangle::new_coords(reference.tl.x + width - 1, reference.tl.y, + reference.tl.x - 1, reference.br.y) + } + } + // make a new rectangle than spans between the left and right rectangles. borders are non-overlapping + pub fn new_h_span(left: Rectangle, right: Rectangle) -> Rectangle { + Rectangle::new_coords(left.br.x + 1, left.tl.y, right.tl.x - 1, right.br.y) + } + pub fn intersects(&self, other: Rectangle) -> bool { + ((other.tl.x >= self.tl.x) && (other.tl.x <= self.br.x)) && + ((other.tl.y >= self.tl.y) && (other.tl.y <= self.br.y)) + || + ((other.br.x >= self.tl.x) && (other.br.x <= self.br.x)) && + ((other.br.y >= self.tl.y) && (other.br.y <= self.br.y)) + } pub fn new_coords_with_style( x0: i16, y0: i16, diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 65de1f574..6488cc575 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -8,6 +8,9 @@ use xous::ipc::Sendable; use heapless::Vec; use heapless::consts::*; +#[cfg(not(target_os = "none"))] +use heapless::spsc::Queue; + use core::convert::TryFrom; use log::{error, info}; @@ -801,7 +804,10 @@ fn xmain() -> ! { let mut raw_conns: Vec = Vec::new(); info!("KBD: starting main loop"); - let mut injected_keys: Vec = Vec::new(); + #[cfg(not(target_os = "none"))] + let mut injected_keys: Queue = Queue::u8(); + #[cfg(not(target_os = "none"))] + let (mut key_enqueue, mut key_dequeue) = injected_keys.split(); loop { let maybe_env = xous::try_receive_message(kbd_sid).unwrap(); match maybe_env { @@ -830,7 +836,9 @@ fn xmain() -> ! { error!("KBD: somehow received an outgoing event code, this shouldn't happen!"); }, Opcode::HostModeInjectKey(key) => { - injected_keys.push(key).unwrap(); + info!("KBD: injecting emulation key press '{}'", key); + #[cfg(not(target_os = "none"))] + key_enqueue.enqueue(key).unwrap(); } } } else { @@ -884,30 +892,25 @@ fn xmain() -> ! { }, }; - // send keys, if any - if kc.len() > 0 || injected_keys.len() > 0 { - // this is used for hosted mode emulation injection of keys - if injected_keys.len() > 0 { - let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}']; - let mut i = 0; - while i < injected_keys.len() && i < 4 { - keys[i] = injected_keys[i]; - i = i + 1; - } - if injected_keys.len() < 4 { - injected_keys.clear(); - } else { - let mut temp: Vec = Vec::new(); - for i in 4..injected_keys.len() { - temp.push(injected_keys[i]).unwrap(); - } - injected_keys = temp; - } + // this is used for hosted mode emulation injection of keys + #[cfg(not(target_os = "none"))] + { + let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}']; + let mut i = 0; + while let Some(c) = key_dequeue.dequeue() { + keys[i] = c; + i = i + 1; + if i == 4 { break; } // see https://github.com/rust-lang/rfcs/pull/2497 for why this can't be at the top of the loop conditional + }; + if i != 0 { for conn in normal_conns.iter() { xous::send_message(*conn, api::Opcode::KeyboardEvent(keys).into()).map(|_| ()).expect("KBD: Couldn't send event to listener"); } } + } + // send keys, if any + if kc.len() > 0 { let mut keys: [char; 4] = ['\u{0000}', '\u{0000}', '\u{0000}', '\u{0000}']; for i in 0..kc.len() { // info!("KBD: sending key '{}'", kc[i]); diff --git a/services/log-server/src/main.rs b/services/log-server/src/main.rs index 48217ca55..3c0ae4ca0 100644 --- a/services/log-server/src/main.rs +++ b/services/log-server/src/main.rs @@ -312,6 +312,21 @@ fn reader_thread(mut output: implementation::OutputWriter) { #[xous::xous_main] fn some_main() -> ! { + #[cfg(baremetal)] + { + // use this to select which UART to monitor in the main loop + use utralib::generated::*; + let gpio_base = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::gpio::HW_GPIO_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map GPIO CSR range"); + let mut gpio = CSR::new(gpio_base.as_mut_ptr() as *mut u32); + gpio.wfo(utra::gpio::UARTSEL_UARTSEL, 1); // 0 = kernel, 1 = log, 2 = app_uart + } + let mut output = implementation::init(); let writer = output.get_writer(); println!("LOG: Creating the reader thread"); diff --git a/services/shell/src/main.rs b/services/shell/src/main.rs index 54ded9bd5..d5a3ed50f 100644 --- a/services/shell/src/main.rs +++ b/services/shell/src/main.rs @@ -186,21 +186,6 @@ fn shell_main() -> ! { ); bouncyball.update(trng_conn); - #[cfg(baremetal)] - { - // use this to select which UART to monitor in the main loop - use utralib::generated::*; - let gpio_base = xous::syscall::map_memory( - xous::MemoryAddress::new(utra::gpio::HW_GPIO_BASE), - None, - 4096, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("couldn't map GPIO CSR range"); - let mut gpio = CSR::new(gpio_base.as_mut_ptr() as *mut u32); - gpio.wfo(utra::gpio::UARTSEL_UARTSEL, 1); // 0 = kernel, 1 = log, 2 = app_uart - } - let style_dark = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1); let style_light = DrawStyle::new(PixelColor::Light, PixelColor::Light, 1); @@ -307,6 +292,22 @@ fn shell_main() -> ! { //////////////// work area if INCOMING_FRESH.load(Ordering::Relaxed) { INCOMING_FRESH.store(false, Ordering::Relaxed); + if INCOMING_CHAR.load(Ordering::Relaxed) == 0x14 { + power_off_soc(com_conn).expect("SHELL: can't power down"); + #[cfg(baremetal)] + { + use utralib::generated::*; + let power_base = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::power::HW_POWER_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map POWER CSR range"); + let mut power = CSR::new(power_base.as_mut_ptr() as *mut u32); + power.wo(utra::power::POWER, 0); + } + } write!(&mut input_buf, "{}", core::char::from_u32(INCOMING_CHAR.load(Ordering::Relaxed)).unwrap()).expect("unable to copy to Xous string"); graphics_server::set_glyph_style(graphics_conn, GlyphStyle::Regular) diff --git a/xous-rs/src/names.rs b/xous-rs/src/names.rs index cf4ccb267..2b11b2e8e 100644 --- a/xous-rs/src/names.rs +++ b/xous-rs/src/names.rs @@ -14,6 +14,7 @@ pub const SERVER_NAME_GFX: &str = "_Graphics_"; pub const SERVER_NAME_FCCAGENT: &str = "_Agent for EMC Testing_"; pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_"; pub const SERVER_NAME_TRNG: &str = "_TRNG manager_"; +pub const SERVER_NAME_GAM: &str = "_Graphical Abstraction Manager_"; /* diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 11c7a879e..bc88c0f44 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -1139,6 +1139,8 @@ pub fn create_server() -> core::result::Result { /// by the kernel and returned to the caller. This address can then be registered /// to a namserver by the caller in their memory space. /// +/// The implementation is just a call to the kernel-exclusive TRNG to fetch random numbers. +/// /// # Errors /// pub fn create_server_id() -> core::result::Result { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ef4c6aad6..da77d182d 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -79,7 +79,8 @@ fn build_hw_image(debug: bool, svd: Option) -> Result<(), DynError> { let kernel = build_kernel(debug)?; let mut init = vec![]; for pkg in &[ - "shell", + //"shell", + "gam", "graphics-server", "ticktimer-server", "log-server",