From 30ff598696eb2116860b0f236c46fee8410f0dad Mon Sep 17 00:00:00 2001 From: Johan Euphrosine Date: Wed, 6 Apr 2022 00:42:46 +0900 Subject: [PATCH 01/16] README: add note about renode version --- emulation/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/emulation/README.md b/emulation/README.md index d93ac505e..66838a100 100644 --- a/emulation/README.md +++ b/emulation/README.md @@ -4,7 +4,7 @@ Platonic is an ideal system useful for developing an operating system. It does ## Usage -For emulation, you will need to install Renode. Then, run `renode` on `xous-release.resc`. For example: +For emulation, you will need to install Renode (use the [nightly](https://dl.antmicro.com/projects/renode/builds/) to get `SPI.NORFlash` peripheral support). Then, run `renode` on `xous-release.resc`. For example: ``` renode emulation/xous-resc.repl From 5ac7bd8b23cac06f73ee0194b4c629d1b398dbc4 Mon Sep 17 00:00:00 2001 From: nworbnhoj Date: Wed, 6 Apr 2022 06:42:01 +1000 Subject: [PATCH 02/16] Link repl readme to wiki Push Events and Listeners --- apps/repl/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/repl/README.md b/apps/repl/README.md index fdc2d4007..3e62ef973 100644 --- a/apps/repl/README.md +++ b/apps/repl/README.md @@ -20,6 +20,9 @@ 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` +[Push Events and Listeners](../../wiki/Push-Events-and-Listeners) provides an overview of the flow of +messages between an Xous application and the Xous Services. + The one demo command provisioned in the `repl` app plays a tone via the `codec` service. This was chosen because it is about one of the most complicated and comprehensive things you can do in the `repl` environment, as it requires From 5b0ecb6d274777154a63461019374c742df54f9e Mon Sep 17 00:00:00 2001 From: nworbnhoj Date: Wed, 6 Apr 2022 07:26:40 +1000 Subject: [PATCH 03/16] link to rkyv & bincode in API.md --- API.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/API.md b/API.md index d6e6c9d9f..556080415 100644 --- a/API.md +++ b/API.md @@ -1,6 +1,10 @@ ## Xous Messaging API In Practice +All Messages passed between Xous Servers undergo serialization and de-serialization. +- Internal `struct` are readily serialized with [rkyv](https://docs.rs/rkyv/0.7.37/rkyv/) and `#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]`with manual serialization as an alternative ([example](services/net/src/std_udp.rs)) +- External `struct` may employ [bincode](https://docs.rs/bincode/latest/bincode/) + Here are the idioms for building servers and passing messages. ### api.rs From d862e25a559d57ada9bae59a14c84d58a36c441e Mon Sep 17 00:00:00 2001 From: nworbnhoj Date: Wed, 6 Apr 2022 21:48:20 +1000 Subject: [PATCH 04/16] Correct rkyv link to v0.4.3 in API.md --- API.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/API.md b/API.md index 556080415..867ce5cac 100644 --- a/API.md +++ b/API.md @@ -2,7 +2,7 @@ ## Xous Messaging API In Practice All Messages passed between Xous Servers undergo serialization and de-serialization. -- Internal `struct` are readily serialized with [rkyv](https://docs.rs/rkyv/0.7.37/rkyv/) and `#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]`with manual serialization as an alternative ([example](services/net/src/std_udp.rs)) +- Internal `struct` are readily serialized with [rkyv](https://docs.rs/rkyv/0.4.3/rkyv/) and `#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]`with manual serialization as an alternative ([example](services/net/src/std_udp.rs)) - External `struct` may employ [bincode](https://docs.rs/bincode/latest/bincode/) Here are the idioms for building servers and passing messages. From eecc1fe22a8e2592c1127b594a6f07fd45ea25b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Thu, 7 Apr 2022 15:00:22 +0200 Subject: [PATCH 05/16] chore: ignore anything called "target" --- .gitignore | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index c1c7e9bd3..e6eaea1e7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,4 @@ -/target -/kernel/target -/loader/target -/locales/target +target **/*.rs.bk /emulation/peripherals.csproj /emulation/obj From 2a957e55cd8de22940f560d2c4f9452aef3b9150 Mon Sep 17 00:00:00 2001 From: nworbnhoj Date: Fri, 8 Apr 2022 14:16:15 +1000 Subject: [PATCH 06/16] add as_qrcode to Notification modal --- services/gam/Cargo.toml | 2 + services/gam/src/modal.rs | 5 +- services/gam/src/modal/notification.rs | 171 +++++++++++++++++++------ services/modals/src/api.rs | 1 + services/modals/src/lib.rs | 16 ++- services/modals/src/main.rs | 30 +++-- services/modals/src/tests.rs | 5 + 7 files changed, 174 insertions(+), 56 deletions(-) diff --git a/services/gam/Cargo.toml b/services/gam/Cargo.toml index dbb7691b5..f5ca41651 100644 --- a/services/gam/Cargo.toml +++ b/services/gam/Cargo.toml @@ -32,6 +32,8 @@ locales = {path = "../../locales"} tts-frontend = {path="../tts"} +qrcode = { version = "0.12", default-features = false } + [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = {path = "../../utralib"} diff --git a/services/gam/src/modal.rs b/services/gam/src/modal.rs index ea687254f..bed5da424 100644 --- a/services/gam/src/modal.rs +++ b/services/gam/src/modal.rs @@ -14,6 +14,8 @@ mod progressbar; pub use progressbar::*; mod consoleinput; pub use consoleinput::*; +mod qrcode; +pub use self::qrcode::*; use enum_dispatch::enum_dispatch; @@ -37,6 +39,7 @@ pub enum ActionType { CheckBoxes, Slider, Notification, + Qrcode, ConsoleInput } @@ -578,4 +581,4 @@ General form for modals: - radio buttons - has an explicit "okay" button to close the modal; up/down arrows + select/enter pick the radio - check boxes - has an explicit "okay" button to close the modal; up/down arrows + select/enter checks boxes - slider - left/right moves the slider, enter/select closes the modal -*/ \ No newline at end of file +*/ diff --git a/services/gam/src/modal/notification.rs b/services/gam/src/modal/notification.rs index 3724c600b..384ad1e37 100644 --- a/services/gam/src/modal/notification.rs +++ b/services/gam/src/modal/notification.rs @@ -5,12 +5,19 @@ use graphics_server::api::*; use locales::t; use core::fmt::Write; -#[derive(Debug, Copy, Clone)] +use qrcode::{Color, QrCode}; +use std::convert::TryInto; + +pub(crate) const QUIET_MODULES: i16 = 2; + +#[derive(Debug)] pub struct Notification { pub action_conn: xous::CID, pub action_opcode: u32, pub is_password: bool, pub manual_dismiss: bool, + pub qrcode: Vec, + pub qrwidth: usize, } impl Notification { pub fn new(action_conn: xous::CID, action_opcode: u32) -> Self { @@ -19,6 +26,8 @@ impl Notification { action_opcode, is_password: false, manual_dismiss: true, + qrcode: Vec::new(), + qrwidth: 0, } } pub fn set_is_password(&mut self, setting: bool) { @@ -30,49 +39,119 @@ impl Notification { pub fn set_manual_dismiss(&mut self, setting: bool) { self.manual_dismiss = setting; } + pub fn set_as_qrcode(&mut self, setting: Option<&str>) { + match setting { + Some(setting) => { + let qrcode = QrCode::new(setting).unwrap(); + self.qrwidth = qrcode.width(); + self.qrcode = Vec::new(); + for color in qrcode.to_colors().iter() { + match color { + Color::Dark => self.qrcode.push(true), + Color::Light => self.qrcode.push(false), + } + } + }, + None => { + self.qrcode = Vec::new(); + self.qrwidth = 0; + }, + } + } + fn draw_text(&self, at_height: i16, modal: &Modal) { + // prime a textview with the correct general style parameters + let mut tv = TextView::new( + modal.canvas, + TextBounds::BoundingBox(Rectangle::new_coords(0, 0, 1, 1)), + ); + tv.ellipsis = true; + tv.style = modal.style; + tv.invert = self.is_password; + tv.draw_border = false; + tv.margin = Point::new(0, 0); + tv.insertion = None; + + tv.bounds_computed = None; + tv.bounds_hint = TextBounds::GrowableFromTl( + Point::new(modal.margin, at_height + modal.margin * 2), + (modal.canvas_width - modal.margin * 2) as u16, + ); + write!(tv, "{}", t!("notification.dismiss", xous::LANG)).unwrap(); + modal + .gam + .bounds_compute_textview(&mut tv) + .expect("couldn't simulate text size"); + let textwidth = if let Some(bounds) = tv.bounds_computed { + bounds.br.x - bounds.tl.x + } else { + modal.canvas_width - modal.margin * 2 + }; + let offset = (modal.canvas_width - textwidth) / 2; + tv.bounds_computed = None; + tv.bounds_hint = TextBounds::BoundingBox(Rectangle::new( + Point::new(offset, at_height + modal.margin * 2), + Point::new( + modal.canvas_width - modal.margin, + at_height + modal.line_height + modal.margin * 2, + ), + )); + modal.gam.post_textview(&mut tv).expect("couldn't post tv"); + } + fn draw_qrcode(&self, at_height: i16, modal: &Modal) { + // calculate pixel size of each module in the qrcode + let qrcode_modules: i16 = self.qrwidth.try_into().unwrap(); + let modules: i16 = qrcode_modules + 2 * QUIET_MODULES; + let canvas_width = modal.canvas_width - 2 * modal.margin; + let mod_size_px: i16 = canvas_width / modules; + let qrcode_width_px = qrcode_modules * mod_size_px; + let quiet_px: i16 = (canvas_width - qrcode_width_px) / 2; + + // Iterate thru qrcode and draw each module as a rectangle (square) + let black = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1); + let top = at_height + 4 * modal.margin + quiet_px; + let left = modal.margin + quiet_px; + let mut top_left; + let mut bot_right; + let mut x: i16; + let mut y: i16; + let mut j: i16; + for (i, module) in self.qrcode.iter().enumerate() { + j = i.try_into().unwrap(); + x = left + (j % qrcode_modules) * mod_size_px; + y = top + (j / qrcode_modules) * mod_size_px; + if *module { + top_left = Point::new(x, y); + bot_right = Point::new(x + mod_size_px, y + mod_size_px); + modal + .gam + .draw_rectangle( + modal.canvas, + Rectangle::new_with_style(top_left, bot_right, black), + ) + .expect("couldn't draw qrcode module"); + } + } + } } impl ActionApi for Notification { - fn set_action_opcode(&mut self, op: u32) {self.action_opcode = op} + fn set_action_opcode(&mut self, op: u32) { + self.action_opcode = op + } fn height(&self, glyph_height: i16, margin: i16) -> i16 { if self.manual_dismiss { - glyph_height + margin * 2 + 5 + let qr_height = if self.qrwidth > 0 { 300 } else { 0 }; + glyph_height + margin * 2 + 5 + qr_height } else { margin + 5 } } fn redraw(&self, at_height: i16, modal: &Modal) { if self.manual_dismiss { - // prime a textview with the correct general style parameters - let mut tv = TextView::new( - modal.canvas, - TextBounds::BoundingBox(Rectangle::new_coords(0, 0, 1, 1)) - ); - tv.ellipsis = true; - tv.style = modal.style; - tv.invert = self.is_password; - tv.draw_border= false; - tv.margin = Point::new(0, 0,); - tv.insertion = None; + self.draw_text(at_height, modal); - tv.bounds_computed = None; - tv.bounds_hint = TextBounds::GrowableFromTl( - Point::new(modal.margin, at_height + modal.margin * 2), - (modal.canvas_width - modal.margin * 2) as u16 - ); - write!(tv, "{}", t!("notification.dismiss", xous::LANG)).unwrap(); - modal.gam.bounds_compute_textview(&mut tv).expect("couldn't simulate text size"); - let textwidth = if let Some(bounds) = tv.bounds_computed { - bounds.br.x - bounds.tl.x - } else { - modal.canvas_width - modal.margin * 2 - }; - let offset = (modal.canvas_width - textwidth) / 2; - tv.bounds_computed = None; - tv.bounds_hint = TextBounds::BoundingBox(Rectangle::new( - Point::new(offset, at_height + modal.margin * 2), - Point::new(modal.canvas_width - modal.margin, at_height + modal.line_height + modal.margin * 2) - )); - modal.gam.post_textview(&mut tv).expect("couldn't post tv"); + if self.qrwidth > 0 { + self.draw_qrcode(at_height, modal); + } // divider lines let color = if self.is_password { @@ -81,11 +160,17 @@ impl ActionApi for Notification { PixelColor::Dark }; - modal.gam.draw_line(modal.canvas, Line::new_with_style( - Point::new(modal.margin, at_height + modal.margin), - Point::new(modal.canvas_width - modal.margin, at_height + modal.margin), - DrawStyle::new(color, color, 1)) - ).expect("couldn't draw entry line"); + modal + .gam + .draw_line( + modal.canvas, + Line::new_with_style( + Point::new(modal.margin, at_height + modal.margin), + Point::new(modal.canvas_width - modal.margin, at_height + modal.margin), + DrawStyle::new(color, color, 1), + ), + ) + .expect("couldn't draw entry line"); } } fn key_action(&mut self, k: char) -> (Option, bool) { @@ -96,11 +181,15 @@ impl ActionApi for Notification { } _ => { if self.manual_dismiss { - send_message(self.action_conn, xous::Message::new_scalar(self.action_opcode as usize, 0, 0, 0, 0)).expect("couldn't pass on dismissal"); - return(None, true) + send_message( + self.action_conn, + xous::Message::new_scalar(self.action_opcode as usize, 0, 0, 0, 0), + ) + .expect("couldn't pass on dismissal"); + return (None, true); } } } (None, false) } -} \ No newline at end of file +} diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs index 3838b9d51..9e3a3fecc 100644 --- a/services/modals/src/api.rs +++ b/services/modals/src/api.rs @@ -36,6 +36,7 @@ pub struct ManagedPromptWithTextResponse { pub struct ManagedNotification { pub token: [u32; 4], pub message: xous_ipc::String::<1024>, + pub as_qrcode: bool, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct ManagedProgress { diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 325fc7e92..e99d842b7 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -92,6 +92,20 @@ impl Modals { let spec = ManagedNotification { token: self.token, message: xous_ipc::String::from_str(notification), + as_qrcode: false, + }; + let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; + buf.lend(self.conn, Opcode::Notification.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + Ok(()) + } + + /// this blocks until the qrcode has been acknowledged. + pub fn show_qrcode(&self, text: &str) -> Result<(), xous::Error> { + self.lock(); + let spec = ManagedNotification { + token: self.token, + message: xous_ipc::String::from_str(text), + as_qrcode: true, }; let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::Notification.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; @@ -256,4 +270,4 @@ impl Drop for Modals { // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), // de-allocate those items here. They don't need a reference count because they are object-specific } -} \ No newline at end of file +} diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index fc0e3796b..b76ca34ad 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -100,15 +100,6 @@ fn xmain() -> ! { validator: None, }; let mut fixed_items = Vec::::new(); - let notification = gam::modal::Notification::new( - renderer_cid, - RendererOp::NotificationReturn.to_u32().unwrap() - ); - let mut gutter = gam::modal::Notification::new( - renderer_cid, - RendererOp::Gutter.to_u32().unwrap() - ); - gutter.set_manual_dismiss(false); let mut progress_action = Slider::new(renderer_cid, RendererOp::Gutter.to_u32().unwrap(), 0, 100, 1, Some("%"), 0, true, true ); @@ -151,11 +142,19 @@ fn xmain() -> ! { log::debug!("should be active!"); }, RendererState::RunNotification(config) => { + let mut notification = gam::modal::Notification::new( + renderer_cid, + RendererOp::NotificationReturn.to_u32().unwrap() + ); + let text = config.message.as_str().unwrap(); + if config.as_qrcode { + notification.set_as_qrcode(Some(text)); + } #[cfg(feature="tts")] tts.tts_simple(config.message.as_str().unwrap()).unwrap(); renderer_modal.modify( Some(ActionType::Notification(notification)), - Some(config.message.as_str().unwrap()), false, + Some(text), false, None, true, None ); renderer_modal.activate(); @@ -230,8 +229,13 @@ fn xmain() -> ! { #[cfg(feature="tts")] tts.tts_simple(text.as_str().unwrap()).unwrap(); bot_text.push_str(text.as_str().unwrap()); - } - renderer_modal.modify( + } + let mut gutter = gam::modal::Notification::new( + renderer_cid, + RendererOp::Gutter.to_u32().unwrap() + ); + gutter.set_manual_dismiss(false); + renderer_modal.modify( Some(ActionType::Notification(gutter)), Some(&top_text), config.title.is_none(), Some(&bot_text), config.text.is_none(), @@ -676,4 +680,4 @@ fn compute_checked_percentage(current: u32, start: u32, end: u32) -> u32 { (((current as u64 - start as u64) * 100) / (end as u64 - start as u64)) as u32 } } -} \ No newline at end of file +} diff --git a/services/modals/src/tests.rs b/services/modals/src/tests.rs index edbffa562..56c2dc54f 100644 --- a/services/modals/src/tests.rs +++ b/services/modals/src/tests.rs @@ -95,6 +95,11 @@ pub(crate) fn spawn_test() { log::info!("testing notification"); modals.show_notification("这是一个测验!").expect("notification failed"); log::info!("notification test done"); + + // 4. test qrcode + log::info!("testing qrcode"); + modals.show_qrcode("https://github.com/betrusted-io/xous-core").expect("qrcode failed"); + log::info!("qrcode test done"); } }); } From cd8c762c55b64b5da222bf1881bf0e4dac1bdc64 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 8 Apr 2022 15:19:56 +0800 Subject: [PATCH 07/16] patch up QR code PR, change method signature as discussed now any modal notification can also render as a QR code --- Cargo.lock | 16 +++++++ services/gam/src/modal.rs | 3 -- services/gam/src/modal/notification.rs | 6 +-- services/modals/src/lib.rs | 18 +------- services/modals/src/tests.rs | 6 +-- services/net/src/connection_manager.rs | 2 +- services/pddb/src/backend/hw.rs | 6 +-- services/pddb/src/main.rs | 6 +-- services/root-keys/src/main.rs | 58 +++++++++++++------------- services/status/src/main.rs | 4 +- services/status/src/time.rs | 6 +-- 11 files changed, 65 insertions(+), 66 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bc7c2ea2d..a25dc0534 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -395,6 +395,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "checked_int_cast" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17cc5e6b5ab06331c33589842070416baa137e8b0eb912b008cfd4a78ada7919" + [[package]] name = "chrono" version = "0.4.19" @@ -1059,6 +1065,7 @@ dependencies = [ "log-server", "num-derive", "num-traits", + "qrcode", "rkyv", "susres", "ticktimer-server", @@ -1944,6 +1951,15 @@ dependencies = [ "syn", ] +[[package]] +name = "qrcode" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16d2f1455f3630c6e5107b4f2b94e74d76dea80736de0981fd27644216cff57f" +dependencies = [ + "checked_int_cast", +] + [[package]] name = "quick-error" version = "1.2.3" diff --git a/services/gam/src/modal.rs b/services/gam/src/modal.rs index bed5da424..604b78cdd 100644 --- a/services/gam/src/modal.rs +++ b/services/gam/src/modal.rs @@ -14,8 +14,6 @@ mod progressbar; pub use progressbar::*; mod consoleinput; pub use consoleinput::*; -mod qrcode; -pub use self::qrcode::*; use enum_dispatch::enum_dispatch; @@ -39,7 +37,6 @@ pub enum ActionType { CheckBoxes, Slider, Notification, - Qrcode, ConsoleInput } diff --git a/services/gam/src/modal/notification.rs b/services/gam/src/modal/notification.rs index 384ad1e37..00f6ab563 100644 --- a/services/gam/src/modal/notification.rs +++ b/services/gam/src/modal/notification.rs @@ -55,7 +55,7 @@ impl Notification { None => { self.qrcode = Vec::new(); self.qrwidth = 0; - }, + }, } } fn draw_text(&self, at_height: i16, modal: &Modal) { @@ -105,7 +105,7 @@ impl Notification { let mod_size_px: i16 = canvas_width / modules; let qrcode_width_px = qrcode_modules * mod_size_px; let quiet_px: i16 = (canvas_width - qrcode_width_px) / 2; - + // Iterate thru qrcode and draw each module as a rectangle (square) let black = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1); let top = at_height + 4 * modal.margin + quiet_px; @@ -114,7 +114,7 @@ impl Notification { let mut bot_right; let mut x: i16; let mut y: i16; - let mut j: i16; + let mut j: i16; for (i, module) in self.qrcode.iter().enumerate() { j = i.try_into().unwrap(); x = left + (j % qrcode_modules) * mod_size_px; diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 87ff14d42..f10b434cf 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -80,32 +80,18 @@ impl Modals { } /// this blocks until the notification has been acknowledged. - pub fn show_notification(&self, notification: &str) -> Result<(), xous::Error> { + pub fn show_notification(&self, notification: &str, as_qrcode: bool) -> Result<(), xous::Error> { self.lock(); let spec = ManagedNotification { token: self.token, message: xous_ipc::String::from_str(notification), - as_qrcode: false, + as_qrcode, }; let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::Notification.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; Ok(()) } - /// this blocks until the qrcode has been acknowledged. - pub fn show_qrcode(&self, text: &str) -> Result<(), xous::Error> { - self.lock(); - let spec = ManagedNotification { - token: self.token, - message: xous_ipc::String::from_str(text), - as_qrcode: true, - }; - let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; - buf.lend(self.conn, Opcode::Notification.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; - self.unlock(); - Ok(()) - } - pub fn start_progress(&self, title: &str, start: u32, end: u32, current: u32) -> Result<(), xous::Error> { self.lock(); let spec = ManagedProgress { diff --git a/services/modals/src/tests.rs b/services/modals/src/tests.rs index 37d57c4f4..301df9905 100644 --- a/services/modals/src/tests.rs +++ b/services/modals/src/tests.rs @@ -60,7 +60,7 @@ pub(crate) fn spawn_test() { // 3. test notificatons log::info!("testing notification"); - modals.show_notification("This is a test!").expect("notification failed"); + modals.show_notification("This is a test!", false).expect("notification failed"); log::info!("notification test done"); } }); @@ -93,12 +93,12 @@ pub(crate) fn spawn_test() { // 3. test notificatons log::info!("testing notification"); - modals.show_notification("这是一个测验!").expect("notification failed"); + modals.show_notification("这是一个测验!", false).expect("notification failed"); log::info!("notification test done"); // 4. test qrcode log::info!("testing qrcode"); - modals.show_qrcode("https://github.com/betrusted-io/xous-core").expect("qrcode failed"); + modals.show_notification("https://github.com/betrusted-io/xous-core", true).expect("qrcode failed"); log::info!("qrcode test done"); } }); diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs index a72932f78..bfd5601c6 100644 --- a/services/net/src/connection_manager.rs +++ b/services/net/src/connection_manager.rs @@ -79,7 +79,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc ! { for basis in bases.iter() { note.push_str(basis); } - modals.show_notification(¬e).expect("couldn't show basis list"); + modals.show_notification(¬e, false).expect("couldn't show basis list"); }, #[cfg(not(any(target_os = "none", target_os = "xous")))] Some(Opcode::DangerousDebug) => { @@ -1281,7 +1281,7 @@ fn try_mount_or_format(modals: &modals::Modals, pddb_os: &mut PddbOs, basis_cach log::error!("Despite formatting, no PDDB was found!"); let mut err = String::from(t!("pddb.internalerror", xous::LANG)); err.push_str(" #1"); // punt and leave an error code, because this "should" be rare - modals.show_notification(err.as_str()).expect("notification failed"); + modals.show_notification(err.as_str(), false).expect("notification failed"); false } } else { @@ -1306,7 +1306,7 @@ fn try_mount_or_format(modals: &modals::Modals, pddb_os: &mut PddbOs, basis_cach log::error!("Despite formatting, no PDDB was found!"); let mut err = String::from(t!("pddb.internalerror", xous::LANG)); err.push_str(" #1"); // punt and leave an error code, because this "should" be rare - modals.show_notification(err.as_str()).expect("notification failed"); + modals.show_notification(err.as_str(), false).expect("notification failed"); false } } diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index a4a40bfdd..d78f8d5c6 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -463,7 +463,7 @@ fn xmain() -> ! { // - pepper if keys.is_initialized() { - modals.show_notification(t!("rootkeys.already_init", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.already_init", xous::LANG), false).expect("modals error"); #[cfg(feature="tts")] tts.tts_blocking(t!("rootkeys.already_init", xous::LANG)).unwrap(); keys.set_ux_password_type(None); @@ -552,16 +552,16 @@ fn xmain() -> ! { ).expect("couldn't initiate dialog box"); } Err(RootkeyResult::AlignmentError) => { - modals.show_notification(t!("rootkeys.init.fail_alignment", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_alignment", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::KeyError) => { - modals.show_notification(t!("rootkeys.init.fail_key", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_key", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::IntegrityError) => { - modals.show_notification(t!("rootkeys.init.fail_verify", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_verify", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::FlashError) => { - modals.show_notification(t!("rootkeys.init.fail_burn", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_burn", xous::LANG), false).expect("modals error"); } } }, @@ -576,7 +576,7 @@ fn xmain() -> ! { log::info!("Vbus is: {:.3}V", vbus); if vbus > 1.5 { // if power is plugged in, request that it be removed - modals.show_notification(t!("rootkeys.init.unplug_power", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.unplug_power", xous::LANG), false).expect("modals error"); log::info!("vbus is high, holding off on reboot"); send_message(main_cid, xous::Message::new_scalar(Opcode::UxTryReboot.to_usize().unwrap(), 0, 0, 0, 0) @@ -629,7 +629,7 @@ fn xmain() -> ! { SignatureResult::DevKeyOk => t!("rootkeys.gwup.viewinfo_dk", xous::LANG), _ => { modals.dynamic_notification_close().expect("modals error"); - modals.show_notification(t!("rootkeys.gwup.no_update_found", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.gwup.no_update_found", xous::LANG), false).expect("modals error"); continue; } }; @@ -659,18 +659,18 @@ fn xmain() -> ! { match modals.get_radiobutton(prompt) { Ok(response) => { if response == t!("rootkeys.gwup.short", xous::LANG) { - modals.show_notification(info.as_str()).expect("modals error"); + modals.show_notification(info.as_str(), false).expect("modals error"); } else if response == t!("rootkeys.gwup.details", xous::LANG) { - modals.show_notification(info.as_str()).expect("modals error"); + modals.show_notification(info.as_str(), false).expect("modals error"); let gw_info = keys.fetch_gw_metadata(GatewareRegion::Staging); // truncate the message to better fit in the rendering box let info_len = if gw_info.log_len > 256 { 256 } else {gw_info.log_len}; let info = format!("{}", str::from_utf8(&gw_info.log_str[..info_len as usize]).unwrap()); - modals.show_notification(info.as_str()).expect("modals error"); + modals.show_notification(info.as_str(), false).expect("modals error"); // truncate the message to better fit in the rendering box let status_len = if gw_info.status_len > 256 { 256 } else {gw_info.status_len}; let info = format!("{}", str::from_utf8(&gw_info.status_str[..status_len as usize]).unwrap()); - modals.show_notification(info.as_str()).expect("modals error"); + modals.show_notification(info.as_str(), false).expect("modals error"); } else { skip_confirmation = true; } @@ -760,21 +760,21 @@ fn xmain() -> ! { match result { Ok(_) => { - modals.show_notification(t!("rootkeys.gwup.finished", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.gwup.finished", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::AlignmentError) => { - modals.show_notification(t!("rootkeys.init.fail_alignment", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_alignment", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::KeyError) => { // probably a bad password, purge it, so the user can try again keys.purge_password(PasswordType::Update); - modals.show_notification(t!("rootkeys.init.fail_key", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_key", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::IntegrityError) => { - modals.show_notification(t!("rootkeys.init.fail_verify", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_verify", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::FlashError) => { - modals.show_notification(t!("rootkeys.init.fail_burn", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_burn", xous::LANG), false).expect("modals error"); } } } @@ -834,21 +834,21 @@ fn xmain() -> ! { match result { Ok(_) => { - modals.show_notification(t!("rootkeys.signxous.finished", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.signxous.finished", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::AlignmentError) => { - modals.show_notification(t!("rootkeys.init.fail_alignment", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_alignment", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::KeyError) => { // probably a bad password, purge it, so the user can try again keys.purge_password(PasswordType::Update); - modals.show_notification(t!("rootkeys.init.fail_key", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_key", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::IntegrityError) => { - modals.show_notification(t!("rootkeys.init.fail_verify", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_verify", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::FlashError) => { - modals.show_notification(t!("rootkeys.init.fail_burn", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_burn", xous::LANG), false).expect("modals error"); } } } @@ -885,7 +885,7 @@ fn xmain() -> ! { // more keys with more passwords, this policy may need to become markedly more complicated! // otherwise, an invalid password request - modals.show_notification(t!("rootkeys.bad_password_request", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.bad_password_request", xous::LANG), false).expect("modals error"); xous::return_scalar(msg.sender, 0).unwrap(); } @@ -978,7 +978,7 @@ fn xmain() -> ! { } Some(Opcode::BbramProvision) => { - modals.show_notification(t!("rootkeys.bbram.confirm", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.bbram.confirm", xous::LANG), false).expect("modals error"); let console_input = gam::modal::ConsoleInput::new( main_cid, Opcode::UxBbramCheckReturn.to_u32().unwrap() @@ -1016,7 +1016,7 @@ fn xmain() -> ! { rootkeys_modal.activate(); } } else { - modals.show_notification(t!("rootkeys.bbram.no_helper", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.bbram.no_helper", xous::LANG), false).expect("modals error"); continue; } } @@ -1039,21 +1039,21 @@ fn xmain() -> ! { match result { Ok(_) => { - modals.show_notification(t!("rootkeys.bbram.finished", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.bbram.finished", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::AlignmentError) => { - modals.show_notification(t!("rootkeys.init.fail_alignment", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_alignment", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::KeyError) => { // probably a bad password, purge it, so the user can try again keys.purge_password(PasswordType::Update); - modals.show_notification(t!("rootkeys.init.fail_key", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_key", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::IntegrityError) => { - modals.show_notification(t!("rootkeys.init.fail_verify", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_verify", xous::LANG), false).expect("modals error"); } Err(RootkeyResult::FlashError) => { - modals.show_notification(t!("rootkeys.init.fail_burn", xous::LANG)).expect("modals error"); + modals.show_notification(t!("rootkeys.init.fail_burn", xous::LANG), false).expect("modals error"); } } } diff --git a/services/status/src/main.rs b/services/status/src/main.rs index d6da4f6ce..a1771471c 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -639,14 +639,14 @@ fn xmain() -> ! { }), Some(StatusOpcode::TrySuspend) => { if ((llio.adc_vbus().unwrap() as f64) * 0.005033) > 1.5 { - modals.show_notification(t!("mainmenu.cant_sleep", xous::LANG)).expect("couldn't notify that power is plugged in"); + modals.show_notification(t!("mainmenu.cant_sleep", xous::LANG), false).expect("couldn't notify that power is plugged in"); } else { susres.initiate_suspend().expect("couldn't initiate suspend op"); } }, Some(StatusOpcode::BatteryDisconnect) => { if ((llio.adc_vbus().unwrap() as f64) * 0.005033) > 1.5 { - modals.show_notification(t!("mainmenu.cant_sleep", xous::LANG)).expect("couldn't notify that power is plugged in"); + modals.show_notification(t!("mainmenu.cant_sleep", xous::LANG), false).expect("couldn't notify that power is plugged in"); } else { gam.shipmode_blank_request().ok(); ticktimer.sleep_ms(500).unwrap(); diff --git a/services/status/src/time.rs b/services/status/src/time.rs index 1a2d03aaf..e535d830f 100644 --- a/services/status/src/time.rs +++ b/services/status/src/time.rs @@ -493,7 +493,7 @@ pub fn start_time_ux(sid: xous::SID) { match FromPrimitive::from_usize(msg.body.id()) { Some(TimeUxOp::SetTime) => xous::msg_scalar_unpack!(msg, _, _, _, _, { if !pddb_poller.is_mounted_nonblocking() { - modals.show_notification(t!("stats.please_mount", xous::LANG)).expect("couldn't show notification"); + modals.show_notification(t!("stats.please_mount", xous::LANG), false).expect("couldn't show notification"); continue; } let mut tz_set_handle = pddb::Pddb::new(); @@ -573,7 +573,7 @@ pub fn start_time_ux(sid: xous::SID) { } Err(err) => { log::info!("Err: {:?}", err); - modals.show_notification(t!("rtc.ntp_fail", xous::LANG)).expect("couldn't show NTP error"); + modals.show_notification(t!("rtc.ntp_fail", xous::LANG), false).expect("couldn't show NTP error"); }, } } @@ -641,7 +641,7 @@ pub fn start_time_ux(sid: xous::SID) { }), Some(TimeUxOp::SetTimeZone) => xous::msg_scalar_unpack!(msg, _, _, _, _, { if !pddb_poller.is_mounted_nonblocking() { - modals.show_notification(t!("stats.please_mount", xous::LANG)).expect("couldn't show notification"); + modals.show_notification(t!("stats.please_mount", xous::LANG), false).expect("couldn't show notification"); continue; } let tz = modals.get_text( From fb4ce334c4460ef12cdbb51f23dd8bd17c12e689 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 8 Apr 2022 15:27:40 +0800 Subject: [PATCH 08/16] missed an instance in a demo app --- apps/ball/src/ball.rs | 2 +- services/modals/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/ball/src/ball.rs b/apps/ball/src/ball.rs index ae4f40895..0dadf00f3 100644 --- a/apps/ball/src/ball.rs +++ b/apps/ball/src/ball.rs @@ -161,7 +161,7 @@ impl Ball { keys[0], t!("ballapp.notification_b", xous::LANG), ).unwrap(); - self.modals.show_notification(¬e).unwrap(); + self.modals.show_notification(¬e, false).unwrap(); self.modals.add_list_item(t!("ballapp.random", xous::LANG)).unwrap(); self.modals.add_list_item(t!("ballapp.tilt", xous::LANG)).unwrap(); let mode = self.modals.get_radiobutton(t!("ballapp.mode_prompt", xous::LANG)).unwrap(); diff --git a/services/modals/Cargo.toml b/services/modals/Cargo.toml index 23c063a5e..43466a4ec 100644 --- a/services/modals/Cargo.toml +++ b/services/modals/Cargo.toml @@ -27,4 +27,4 @@ utralib = { path = "../../utralib"} [features] ux_tests = [] tts = [] -default = [] +default = ["ux_tests"] From b4dad543159a55dfb58f9d8006666b858e110918 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 8 Apr 2022 15:58:59 +0800 Subject: [PATCH 09/16] fix missing unlock() statement at end of modals --- services/modals/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index f10b434cf..825ab3801 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -89,6 +89,7 @@ impl Modals { }; let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::Notification.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + self.unlock(); Ok(()) } From 3ef2dae2f0a79b9b65afa716664f43063802774f Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 8 Apr 2022 16:05:42 +0800 Subject: [PATCH 10/16] revert test config and make chinese text also render qr code --- services/modals/Cargo.toml | 2 +- services/modals/src/tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/modals/Cargo.toml b/services/modals/Cargo.toml index 43466a4ec..23c063a5e 100644 --- a/services/modals/Cargo.toml +++ b/services/modals/Cargo.toml @@ -27,4 +27,4 @@ utralib = { path = "../../utralib"} [features] ux_tests = [] tts = [] -default = ["ux_tests"] +default = [] diff --git a/services/modals/src/tests.rs b/services/modals/src/tests.rs index 301df9905..e2f73135e 100644 --- a/services/modals/src/tests.rs +++ b/services/modals/src/tests.rs @@ -93,7 +93,7 @@ pub(crate) fn spawn_test() { // 3. test notificatons log::info!("testing notification"); - modals.show_notification("这是一个测验!", false).expect("notification failed"); + modals.show_notification("这是一个测验!", true).expect("notification failed"); log::info!("notification test done"); // 4. test qrcode From 3f962b6bb021b69bdbe09b482353073c5cf554f2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 8 Apr 2022 18:55:56 +0800 Subject: [PATCH 11/16] make progress updates fail gracefully on server queue full Progress updates can come at a right too high for the renderer to keep up, so instead of deadlocking, we discard update messages that are too frequent. --- services/modals/src/api.rs | 3 +- services/modals/src/lib.rs | 14 ++++++++-- services/modals/src/main.rs | 55 +++++++++++++++++-------------------- 3 files changed, 37 insertions(+), 35 deletions(-) diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs index a6ba1494e..f459bdd17 100644 --- a/services/modals/src/api.rs +++ b/services/modals/src/api.rs @@ -81,7 +81,7 @@ pub(crate) enum Opcode { /// raise a progress bar StartProgress, /// update the progress bar - UpdateProgress, + DoUpdateProgress, /// lower a progress bar StopProgress, /// update a dynamic notification's text @@ -99,7 +99,6 @@ pub(crate) enum Opcode { // box because it's a convenience routine used by "everyone"; password boxes are always handled within // a given secured server so that the attack surface for these do not extend into the modals boundary. InitiateOp, - DoUpdateProgress, FinishProgress, TextEntryReturn, diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 825ab3801..b0c50bccf 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -111,9 +111,17 @@ impl Modals { /// but, progress updates are meant to be fast and frequent, and generally if a progress bar shows /// something whacky it's not going to affect a security outcome pub fn update_progress(&self, current: u32) -> Result<(), xous::Error> { - send_message(self.conn, - Message::new_scalar(Opcode::UpdateProgress.to_usize().unwrap(), current as usize, 0, 0, 0) - ).expect("couldn't update progress"); + match xous::try_send_message(self.conn, + Message::new_scalar(Opcode::DoUpdateProgress.to_usize().unwrap(), current as usize, 0, 0, 0) + ) { + Ok(_) => (), + Err(e) => { + log::warn!("update_progress failed with {:?}, skipping request", e); + // most likely issue is that the server queue is overfull because too many progress updates were sent + // sleep the sending thread to rate-limit requests, while discarding the current request. + xous::yield_slice() + } + } Ok(()) } diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index 2f638bc5e..16125ef42 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -224,12 +224,6 @@ fn xmain() -> ! { Message::new_scalar(Opcode::InitiateOp.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't initiate UX op"); }, - Some(Opcode::UpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, { - send_message( - renderer_cid, - Message::new_scalar(Opcode::DoUpdateProgress.to_usize().unwrap(), current, 0, 0, 0) - ).expect("couldn't update progress bar"); - }), Some(Opcode::StopProgress) => msg_scalar_unpack!(msg, t0, t1, t2, t3, { let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32]; if token != token_lock.unwrap_or(default_nonce) { @@ -289,6 +283,30 @@ fn xmain() -> ! { Message::new_scalar(Opcode::DoCloseDynamicNotification.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't close dynamic notification"); }), + // this got promoted to an external API during the deferred response refactor to eliminate an intermediate state + Some(Opcode::DoUpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, { + let new_percentage = compute_checked_percentage( + current as u32, start_work, end_work); + log::trace!("percentage: {}, current: {}, start: {}, end: {}", new_percentage, current, start_work, end_work); + if new_percentage != last_percentage { + last_percentage = new_percentage; + progress_action.set_state(last_percentage); + #[cfg(feature="tts")] + { + if tt.elapsed_ms() - last_tick > TICK_INTERVAL { + tts.tts_blocking(t!("progress.increment", xous::LANG)).unwrap(); + last_tick = tt.elapsed_ms(); + } + } + renderer_modal.modify( + Some(ActionType::Slider(progress_action)), + None, false, + None, false, None + ); + renderer_modal.redraw(); + xous::yield_slice(); // give time for the GAM to redraw + } + }), // ------------------ INTERNAL APIS -------------------- Some(Opcode::InitiateOp) => { @@ -394,7 +412,7 @@ fn xmain() -> ! { #[cfg(feature="tts")] tts.tts_simple(text.as_str().unwrap()).unwrap(); bot_text.push_str(text.as_str().unwrap()); - } + } let mut gutter = gam::modal::Notification::new( renderer_cid, Opcode::Gutter.to_u32().unwrap() @@ -414,29 +432,6 @@ fn xmain() -> ! { } } }, - Some(Opcode::DoUpdateProgress) => msg_scalar_unpack!(msg, current, _, _, _, { - let new_percentage = compute_checked_percentage( - current as u32, start_work, end_work); - log::trace!("percentage: {}, current: {}, start: {}, end: {}", new_percentage, current, start_work, end_work); - if new_percentage != last_percentage { - last_percentage = new_percentage; - progress_action.set_state(last_percentage); - #[cfg(feature="tts")] - { - if tt.elapsed_ms() - last_tick > TICK_INTERVAL { - tts.tts_blocking(t!("progress.increment", xous::LANG)).unwrap(); - last_tick = tt.elapsed_ms(); - } - } - renderer_modal.modify( - Some(ActionType::Slider(progress_action)), - None, false, - None, false, None - ); - renderer_modal.redraw(); - xous::yield_slice(); // give time for the GAM to redraw - } - }), Some(Opcode::FinishProgress) => { renderer_modal.gam.relinquish_focus().unwrap(); op = RendererState::None; From 7353c3ab9c18dac67b9006d44210bf29ebcb7e1b Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 10 Apr 2022 04:42:02 +0800 Subject: [PATCH 12/16] add guru meditations --- .../graphics-server/src/backend/betrusted.rs | 21 + services/graphics-server/src/main.rs | 787 +++++++++--------- services/graphics-server/src/panic.rs | 233 ++++++ 3 files changed, 656 insertions(+), 385 deletions(-) create mode 100644 services/graphics-server/src/panic.rs diff --git a/services/graphics-server/src/backend/betrusted.rs b/services/graphics-server/src/backend/betrusted.rs index ed28b8d01..2b8c22613 100644 --- a/services/graphics-server/src/backend/betrusted.rs +++ b/services/graphics-server/src/backend/betrusted.rs @@ -80,6 +80,27 @@ impl XousDisplay { display } + /// This should only be called to initialize the panic handler with its own + /// copy of hardware registers. + /// + /// # Safety + /// + /// The addresses of these structures are passed as `u32` and unsafely cast back + /// into pointers on the user's side. We do this because the panic handler is special: + /// it grabs ahold of the low-level hardware, yanking control from the higher level + /// control functons, without having to map its own separate pages. + /// + /// Of course, "anyone" with a copy of this data can clobber existing graphics operations. Thus, + /// any access to these registers have to be protected with a mutex of some form. In the case of + /// the panic handler, the `is_panic` `AtomicBool` will suppress graphics loop operation + /// in the case of a panic. + pub unsafe fn hw_regs(&self) -> (u32, u32) { + ( + self.hwfb.as_mut_ptr() as u32, + self.csr.base as u32 + ) + } + pub fn suspend(&mut self) { while self.busy() { // just wait until any pending FB operations are done diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index c1935550c..e55e1a3f3 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -27,6 +27,10 @@ use xous_ipc::Buffer; mod fontmap; use api::BulkRead; +mod panic; +use core::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + use crate::wordwrap::*; use core::ops::Add; @@ -65,7 +69,6 @@ fn map_fonts() -> MemoryRange { "mapping regular font to 0x{:08x}", fontregion.as_ptr() as usize + fontmap::REGULAR_OFFSET as usize ); - use core::sync::atomic::Ordering; blitstr2::fonts::bold::GLYPH_LOCATION.store((fontregion.as_ptr() as usize + fontmap::BOLD_OFFSET as usize) as u32, Ordering::SeqCst); blitstr2::fonts::emoji::GLYPH_LOCATION.store((fontregion.as_ptr() as usize + fontmap::EMOJI_OFFSET as usize) as u32, Ordering::SeqCst); blitstr2::fonts::ja::GLYPH_LOCATION.store((fontregion.as_ptr() as usize + fontmap::JA_OFFSET as usize) as u32, Ordering::SeqCst); @@ -94,6 +97,21 @@ fn xmain() -> ! { log::set_max_level(log::LevelFilter::Info); log::info!("my PID is {}", xous::process::id()); + let mut display = XousDisplay::new(); + let fontregion = map_fonts(); + + // install the graphical panic handler. It won't catch really early panics, or panics in this crate, + // but it'll do the job 90% of the time and it's way better than having none at all. + let is_panic = Arc::new(AtomicBool::new(false)); + #[cfg(any(target_os = "none", target_os = "xous"))] // only install for hardware targets; hosted mode uses host's panic handler + { + let (hwfb, control) = unsafe{ + // this is safe because we are extracting these for use in a Mutex-protected panic handler + display.hw_regs() + }; + panic::panic_handler_thread(is_panic.clone(), hwfb, control); + } + let xns = xous_names::XousNames::new().unwrap(); // these connections should be established: // - GAM @@ -102,15 +120,8 @@ fn xmain() -> ! { .register_name(api::SERVER_NAME_GFX, Some(2)) .expect("can't register server"); - // Create a new monochrome simulator display. - let mut display = XousDisplay::new(); - //let mut fb = display.native_buffer(); - //let mut b2cursor = blitstr2::Cursor::new(0, 0, 16); - //blitstr2::paint_str(&mut fb, blitstr2::ClipRect::new(0, 0, 100, 100), &mut b2cursor, "test"); - draw_boot_logo(&mut display); - let fontregion = map_fonts(); let screen_clip = Rectangle::new(Point::new(0, 0), display.screen_size()); display.redraw(); @@ -122,420 +133,426 @@ fn xmain() -> ! { let mut bulkread = BulkRead::default(); // holding buffer for bulk reads; wastes ~8k when not in use, but saves a lot of copy/init for each iteration of the read + let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); + #[cfg(feature = "testing")] testing::tests(); loop { - let mut msg = xous::receive_message(sid).unwrap(); - log::trace!("Message: {:?}", msg); - match FromPrimitive::from_usize(msg.body.id()) { - Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, { - display.suspend(); - susres - .suspend_until_resume(token) - .expect("couldn't execute suspend/resume"); - display.resume(); - }), - Some(Opcode::DrawClipObject) => { - let buffer = - unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let obj = buffer.to_original::().unwrap(); - log::trace!("DrawClipObject {:?}", obj); - match obj.obj { - ClipObjectType::Line(line) => { - op::line(display.native_buffer(), line, Some(obj.clip), false); - } - ClipObjectType::XorLine(line) => { - op::line(display.native_buffer(), line, Some(obj.clip), true); - } - ClipObjectType::Circ(circ) => { - op::circle(display.native_buffer(), circ, Some(obj.clip)); - } - ClipObjectType::Rect(rect) => { - op::rectangle(display.native_buffer(), rect, Some(obj.clip)); - } - ClipObjectType::RoundRect(rr) => { - op::rounded_rectangle(display.native_buffer(), rr, Some(obj.clip)); - } - } - } - Some(Opcode::DrawClipObjectList) => { - let buffer = - unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - let list_ipc = buffer.to_original::().unwrap(); - for maybe_item in list_ipc.list.iter() { - if let Some(obj) = maybe_item { - match obj.obj { - ClipObjectType::Line(line) => { - op::line(display.native_buffer(), line, Some(obj.clip), false); - } - ClipObjectType::XorLine(line) => { - op::line(display.native_buffer(), line, Some(obj.clip), true); - } - ClipObjectType::Circ(circ) => { - op::circle(display.native_buffer(), circ, Some(obj.clip)); - } - ClipObjectType::Rect(rect) => { - op::rectangle(display.native_buffer(), rect, Some(obj.clip)); - } - ClipObjectType::RoundRect(rr) => { - op::rounded_rectangle(display.native_buffer(), rr, Some(obj.clip)); - } + if !is_panic.load(Ordering::Relaxed) { // non-panic graphics operations if we are in a panic situation + let mut msg = xous::receive_message(sid).unwrap(); + log::trace!("Message: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, { + display.suspend(); + susres + .suspend_until_resume(token) + .expect("couldn't execute suspend/resume"); + display.resume(); + }), + Some(Opcode::DrawClipObject) => { + let buffer = + unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let obj = buffer.to_original::().unwrap(); + log::trace!("DrawClipObject {:?}", obj); + match obj.obj { + ClipObjectType::Line(line) => { + op::line(display.native_buffer(), line, Some(obj.clip), false); + } + ClipObjectType::XorLine(line) => { + op::line(display.native_buffer(), line, Some(obj.clip), true); + } + ClipObjectType::Circ(circ) => { + op::circle(display.native_buffer(), circ, Some(obj.clip)); + } + ClipObjectType::Rect(rect) => { + op::rectangle(display.native_buffer(), rect, Some(obj.clip)); + } + ClipObjectType::RoundRect(rr) => { + op::rounded_rectangle(display.native_buffer(), rr, Some(obj.clip)); } - } else { - // stop at the first None entry -- if the sender packed the list with a hole in it, that's their bad - break; } } - } - Some(Opcode::DrawTextView) => { - let mut buffer = unsafe { - Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) - }; - let mut tv = buffer.to_original::().unwrap(); - - if tv.clip_rect.is_none() { - continue; - } // if no clipping rectangle is specified, nothing to draw - - // this is the clipping rectangle of the canvas in screen coordinates - let clip_rect = tv.clip_rect.unwrap(); - // this is the translation vector to and from screen space - let screen_offset: Point = tv.clip_rect.unwrap().tl; - - let typeset_extent = match tv.bounds_hint { - TextBounds::BoundingBox(r) => - Pt::new(r.br().x - r.tl().x - tv.margin.x * 2, r.br().y - r.tl().y - tv.margin.y * 2), - TextBounds::GrowableFromBr(br, width) => - Pt::new(width as i16 - tv.margin.x * 2, br.y - tv.margin.y * 2), - TextBounds::GrowableFromBl(bl, width) => - Pt::new(width as i16 - tv.margin.x * 2, bl.y - tv.margin.y * 2), - TextBounds::GrowableFromTl(tl, width) => - Pt::new(width as i16 - tv.margin.x * 2, (clip_rect.br().y - clip_rect.tl().y - tl.y) - tv.margin.y * 2), - TextBounds::GrowableFromTr(tr, width) => - Pt::new(width as i16 - tv.margin.x * 2, (clip_rect.br().y - clip_rect.tl().y - tr.y) - tv.margin.y * 2), - }; - let mut typesetter = Typesetter::setup( - tv.to_str(), - &typeset_extent, - &tv.style, - if let Some(i) = tv.insertion { Some(i as usize) } else { None } - ); - let composition = typesetter.typeset( - if tv.ellipsis { - OverflowStrategy::Ellipsis - } else { - OverflowStrategy::Abort + Some(Opcode::DrawClipObjectList) => { + let buffer = + unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let list_ipc = buffer.to_original::().unwrap(); + for maybe_item in list_ipc.list.iter() { + if let Some(obj) = maybe_item { + match obj.obj { + ClipObjectType::Line(line) => { + op::line(display.native_buffer(), line, Some(obj.clip), false); + } + ClipObjectType::XorLine(line) => { + op::line(display.native_buffer(), line, Some(obj.clip), true); + } + ClipObjectType::Circ(circ) => { + op::circle(display.native_buffer(), circ, Some(obj.clip)); + } + ClipObjectType::Rect(rect) => { + op::rectangle(display.native_buffer(), rect, Some(obj.clip)); + } + ClipObjectType::RoundRect(rr) => { + op::rounded_rectangle(display.native_buffer(), rr, Some(obj.clip)); + } + } + } else { + // stop at the first None entry -- if the sender packed the list with a hole in it, that's their bad + break; + } } - ); - - let composition_top_left = match tv.bounds_hint { - TextBounds::BoundingBox(r) => - r.tl().add(tv.margin), - TextBounds::GrowableFromBr(br, _width) => - Point::new(br.x - (composition.bb_width() as i16 + tv.margin.x), - br.y - (composition.bb_height() as i16 + tv.margin.y)), - TextBounds::GrowableFromBl(bl, _width) => - Point::new(bl.x + tv.margin.x, bl.y - (composition.bb_height() as i16 + tv.margin.y)), - TextBounds::GrowableFromTl(tl, _width) => - tl.add(tv.margin), - TextBounds::GrowableFromTr(tr, _width) => - Point::new(tr.x - (composition.bb_width() as i16 + tv.margin.x), tr.y + tv.margin.y), } - .add(screen_offset); + Some(Opcode::DrawTextView) => { + let mut buffer = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + let mut tv = buffer.to_original::().unwrap(); - // compute the clear rectangle -- the border is already in screen coordinates, just add the margin around it - let mut clear_rect = match tv.bounds_hint { - TextBounds::BoundingBox(mut r) => { - r.translate(screen_offset); - r - } - _ => { - // composition_top_left already had a screen_offset added when it was computed. just margin it out - let mut r = Rectangle::new( - composition_top_left, - composition_top_left.add(Point::new(composition.bb_width() as _, composition.bb_height() as _)) - ); - r.margin_out(tv.margin); - r + if tv.clip_rect.is_none() { + continue; + } // if no clipping rectangle is specified, nothing to draw + + // this is the clipping rectangle of the canvas in screen coordinates + let clip_rect = tv.clip_rect.unwrap(); + // this is the translation vector to and from screen space + let screen_offset: Point = tv.clip_rect.unwrap().tl; + + let typeset_extent = match tv.bounds_hint { + TextBounds::BoundingBox(r) => + Pt::new(r.br().x - r.tl().x - tv.margin.x * 2, r.br().y - r.tl().y - tv.margin.y * 2), + TextBounds::GrowableFromBr(br, width) => + Pt::new(width as i16 - tv.margin.x * 2, br.y - tv.margin.y * 2), + TextBounds::GrowableFromBl(bl, width) => + Pt::new(width as i16 - tv.margin.x * 2, bl.y - tv.margin.y * 2), + TextBounds::GrowableFromTl(tl, width) => + Pt::new(width as i16 - tv.margin.x * 2, (clip_rect.br().y - clip_rect.tl().y - tl.y) - tv.margin.y * 2), + TextBounds::GrowableFromTr(tr, width) => + Pt::new(width as i16 - tv.margin.x * 2, (clip_rect.br().y - clip_rect.tl().y - tr.y) - tv.margin.y * 2), + }; + let mut typesetter = Typesetter::setup( + tv.to_str(), + &typeset_extent, + &tv.style, + if let Some(i) = tv.insertion { Some(i as usize) } else { None } + ); + let composition = typesetter.typeset( + if tv.ellipsis { + OverflowStrategy::Ellipsis + } else { + OverflowStrategy::Abort + } + ); + + let composition_top_left = match tv.bounds_hint { + TextBounds::BoundingBox(r) => + r.tl().add(tv.margin), + TextBounds::GrowableFromBr(br, _width) => + Point::new(br.x - (composition.bb_width() as i16 + tv.margin.x), + br.y - (composition.bb_height() as i16 + tv.margin.y)), + TextBounds::GrowableFromBl(bl, _width) => + Point::new(bl.x + tv.margin.x, bl.y - (composition.bb_height() as i16 + tv.margin.y)), + TextBounds::GrowableFromTl(tl, _width) => + tl.add(tv.margin), + TextBounds::GrowableFromTr(tr, _width) => + Point::new(tr.x - (composition.bb_width() as i16 + tv.margin.x), tr.y + tv.margin.y), } - }; + .add(screen_offset); - log::trace!("clip_rect: {:?}", clip_rect); - log::trace!("composition_top_left: {:?}", composition_top_left); - log::trace!("clear_rect: {:?}", clear_rect); - // draw the bubble/border and/or clear the background area - let bordercolor = if tv.draw_border { - Some(PixelColor::Dark) - } else { - None - }; - let borderwidth: i16 = if tv.draw_border { - tv.border_width as i16 - } else { - 0 - }; - let fillcolor = if tv.clear_area || tv.invert { - if tv.invert { + // compute the clear rectangle -- the border is already in screen coordinates, just add the margin around it + let mut clear_rect = match tv.bounds_hint { + TextBounds::BoundingBox(mut r) => { + r.translate(screen_offset); + r + } + _ => { + // composition_top_left already had a screen_offset added when it was computed. just margin it out + let mut r = Rectangle::new( + composition_top_left, + composition_top_left.add(Point::new(composition.bb_width() as _, composition.bb_height() as _)) + ); + r.margin_out(tv.margin); + r + } + }; + + log::trace!("clip_rect: {:?}", clip_rect); + log::trace!("composition_top_left: {:?}", composition_top_left); + log::trace!("clear_rect: {:?}", clear_rect); + // draw the bubble/border and/or clear the background area + let bordercolor = if tv.draw_border { Some(PixelColor::Dark) } else { - Some(PixelColor::Light) - } - } else { - None - }; - - clear_rect.style = DrawStyle { - fill_color: fillcolor, - stroke_color: bordercolor, - stroke_width: borderwidth, - }; - if !tv.dry_run() { - if tv.rounded_border.is_some() { - op::rounded_rectangle( - display.native_buffer(), - RoundedRectangle::new(clear_rect, tv.rounded_border.unwrap() as _), - tv.clip_rect, - ); + None + }; + let borderwidth: i16 = if tv.draw_border { + tv.border_width as i16 } else { - op::rectangle(display.native_buffer(), clear_rect, tv.clip_rect); + 0 + }; + let fillcolor = if tv.clear_area || tv.invert { + if tv.invert { + Some(PixelColor::Dark) + } else { + Some(PixelColor::Light) + } + } else { + None + }; + + clear_rect.style = DrawStyle { + fill_color: fillcolor, + stroke_color: bordercolor, + stroke_width: borderwidth, + }; + if !tv.dry_run() { + if tv.rounded_border.is_some() { + op::rounded_rectangle( + display.native_buffer(), + RoundedRectangle::new(clear_rect, tv.rounded_border.unwrap() as _), + tv.clip_rect, + ); + } else { + op::rectangle(display.native_buffer(), clear_rect, tv.clip_rect); + } } - } - // for now, if we're in braille mode, emit all text to the debug log so we can see it - //if cfg!(feature = "braille") { - // log::info!("{}", tv); - //} + // for now, if we're in braille mode, emit all text to the debug log so we can see it + //if cfg!(feature = "braille") { + // log::info!("{}", tv); + //} - if !tv.dry_run() { - // note: make the clip rect `tv.clip_rect.unwrap()` if you want to debug wordwrapping artifacts; otherwise smallest_rect masks some problems - let smallest_rect = clear_rect.clip_with(tv.clip_rect.unwrap()) - .unwrap_or(Rectangle::new(Point::new(0, 0), Point::new(0, 0,))); - composition.render(display.native_buffer(), composition_top_left, tv.invert, smallest_rect); - } - // type mismatch for now, replace this with a simple equals once we sort that out - tv.cursor.pt.x = composition.final_cursor().pt.x; - tv.cursor.pt.y = composition.final_cursor().pt.y; - tv.cursor.line_height = composition.final_cursor().line_height; + if !tv.dry_run() { + // note: make the clip rect `tv.clip_rect.unwrap()` if you want to debug wordwrapping artifacts; otherwise smallest_rect masks some problems + let smallest_rect = clear_rect.clip_with(tv.clip_rect.unwrap()) + .unwrap_or(Rectangle::new(Point::new(0, 0), Point::new(0, 0,))); + composition.render(display.native_buffer(), composition_top_left, tv.invert, smallest_rect); + } + // type mismatch for now, replace this with a simple equals once we sort that out + tv.cursor.pt.x = composition.final_cursor().pt.x; + tv.cursor.pt.y = composition.final_cursor().pt.y; + tv.cursor.line_height = composition.final_cursor().line_height; - tv.bounds_computed = Some( - clear_rect - ); - log::trace!("cursor ret {:?}, bounds ret {:?}", tv.cursor, tv.bounds_computed); - // pack our data back into the buffer to return - buffer.replace(tv).unwrap(); - } - Some(Opcode::Flush) => { - log::trace!("***gfx flush*** redraw##"); - display.update(); - display.redraw(); - } - Some(Opcode::Clear) => { - let mut r = Rectangle::full_screen(); - r.style = DrawStyle::new(PixelColor::Light, PixelColor::Light, 0); - op::rectangle(display.native_buffer(), r, screen_clip.into()) - } - Some(Opcode::Line) => msg_scalar_unpack!(msg, p1, p2, style, _, { - let l = - Line::new_with_style(Point::from(p1), Point::from(p2), DrawStyle::from(style)); - op::line(display.native_buffer(), l, screen_clip.into(), false); - }), - Some(Opcode::Rectangle) => msg_scalar_unpack!(msg, tl, br, style, _, { - let r = Rectangle::new_with_style( - Point::from(tl), - Point::from(br), - DrawStyle::from(style), - ); - op::rectangle(display.native_buffer(), r, screen_clip.into()); - }), - Some(Opcode::RoundedRectangle) => msg_scalar_unpack!(msg, tl, br, style, r, { - let rr = RoundedRectangle::new( - Rectangle::new_with_style( + tv.bounds_computed = Some( + clear_rect + ); + log::trace!("cursor ret {:?}, bounds ret {:?}", tv.cursor, tv.bounds_computed); + // pack our data back into the buffer to return + buffer.replace(tv).unwrap(); + } + Some(Opcode::Flush) => { + log::trace!("***gfx flush*** redraw##"); + display.update(); + display.redraw(); + } + Some(Opcode::Clear) => { + let mut r = Rectangle::full_screen(); + r.style = DrawStyle::new(PixelColor::Light, PixelColor::Light, 0); + op::rectangle(display.native_buffer(), r, screen_clip.into()) + } + Some(Opcode::Line) => msg_scalar_unpack!(msg, p1, p2, style, _, { + let l = + Line::new_with_style(Point::from(p1), Point::from(p2), DrawStyle::from(style)); + op::line(display.native_buffer(), l, screen_clip.into(), false); + }), + Some(Opcode::Rectangle) => msg_scalar_unpack!(msg, tl, br, style, _, { + let r = Rectangle::new_with_style( Point::from(tl), Point::from(br), DrawStyle::from(style), - ), - r as _, - ); - op::rounded_rectangle(display.native_buffer(), rr, screen_clip.into()); - }), - Some(Opcode::Circle) => msg_scalar_unpack!(msg, center, radius, style, _, { - let c = Circle::new_with_style( - Point::from(center), - radius as _, - DrawStyle::from(style), - ); - op::circle(display.native_buffer(), c, screen_clip.into()); - }), - Some(Opcode::ScreenSize) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { - let pt = display.screen_size(); - xous::return_scalar2(msg.sender, pt.x as usize, pt.y as usize) - .expect("couldn't return ScreenSize request"); - }), - Some(Opcode::QueryGlyphProps) => msg_blocking_scalar_unpack!(msg, style, _, _, _, { - let glyph = GlyphStyle::from(style); - xous::return_scalar2( - msg.sender, - glyph.into(), - glyph_to_height_hint(glyph), - ) - .expect("could not return QueryGlyphProps request"); - }), - Some(Opcode::DrawSleepScreen) => msg_scalar_unpack!(msg, _, _, _, _, { - display.blit_screen(&logo::LOGO_MAP); - display.update(); - display.redraw(); - }), - Some(Opcode::Devboot) => msg_scalar_unpack!(msg, ena, _, _, _, { - if ena != 0 { - display.set_devboot(true); - } else { - display.set_devboot(false); - } - }), - Some(Opcode::RestartBulkRead) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { - bulkread.from_offset = 0; - xous::return_scalar(msg.sender, 0) - .expect("couldn't ack that bulk read pointer was reset"); - }), - Some(Opcode::BulkReadFonts) => { - let fontlen = fontmap::FONT_TOTAL_LEN as u32 + 8; - let mut buf = unsafe { - Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) - }; - //let mut bulkread = buf.as_flat::().unwrap(); // try to skip the copy/init step by using a persistent structure - let fontslice = fontregion.as_slice::(); - assert!(fontlen <= fontslice.len() as u32); - if bulkread.from_offset >= fontlen { - log::error!( - "BulkReadFonts attempt to read out of bound on the font area; ignoring!" ); - continue; - } - let readlen = if bulkread.from_offset + bulkread.buf.len() as u32 > fontlen { - // returns what is readable of the last bit; anything longer than the fontlen is undefined/invalid - fontlen as usize - bulkread.from_offset as usize - } else { - bulkread.buf.len() - }; - for (&src, dst) in fontslice - [bulkread.from_offset as usize..bulkread.from_offset as usize + readlen] - .iter() - .zip(bulkread.buf.iter_mut()) - { - *dst = src; - } - bulkread.len = readlen as u32; - bulkread.from_offset += readlen as u32; - buf.replace(bulkread).unwrap(); - } - Some(Opcode::TestPattern) => msg_blocking_scalar_unpack!(msg, duration, _, _, _, { - let mut stashmem = xous::syscall::map_memory( - None, - None, - ((backend::FB_SIZE * 4) + 4096) & !4095, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ).expect("couldn't map stash frame buffer"); - let stash = &mut stashmem.as_slice_mut()[..backend::FB_SIZE]; - for (&src, dst) in display.as_slice().iter().zip(stash.iter_mut()) { - *dst = src; - } - for lines in 0..backend::FB_LINES { // mark all lines dirty - stash[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000; - } - - let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); - let start_time = ticktimer.elapsed_ms(); - let mut testmem = xous::syscall::map_memory( - None, - None, - ((backend::FB_SIZE * 4) + 4096) & !4095, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ).expect("couldn't map stash frame buffer"); - let testpat = &mut testmem.as_slice_mut()[..backend::FB_SIZE]; - const DWELL: usize = 1000; - while ticktimer.elapsed_ms() - start_time < duration as u64 { - // all black - for w in testpat.iter_mut() { - *w = 0; - } - for lines in 0..backend::FB_LINES { // mark dirty bits - testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000; - } - display.blit_screen(testpat); + op::rectangle(display.native_buffer(), r, screen_clip.into()); + }), + Some(Opcode::RoundedRectangle) => msg_scalar_unpack!(msg, tl, br, style, r, { + let rr = RoundedRectangle::new( + Rectangle::new_with_style( + Point::from(tl), + Point::from(br), + DrawStyle::from(style), + ), + r as _, + ); + op::rounded_rectangle(display.native_buffer(), rr, screen_clip.into()); + }), + Some(Opcode::Circle) => msg_scalar_unpack!(msg, center, radius, style, _, { + let c = Circle::new_with_style( + Point::from(center), + radius as _, + DrawStyle::from(style), + ); + op::circle(display.native_buffer(), c, screen_clip.into()); + }), + Some(Opcode::ScreenSize) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + let pt = display.screen_size(); + xous::return_scalar2(msg.sender, pt.x as usize, pt.y as usize) + .expect("couldn't return ScreenSize request"); + }), + Some(Opcode::QueryGlyphProps) => msg_blocking_scalar_unpack!(msg, style, _, _, _, { + let glyph = GlyphStyle::from(style); + xous::return_scalar2( + msg.sender, + glyph.into(), + glyph_to_height_hint(glyph), + ) + .expect("could not return QueryGlyphProps request"); + }), + Some(Opcode::DrawSleepScreen) => msg_scalar_unpack!(msg, _, _, _, _, { + display.blit_screen(&logo::LOGO_MAP); display.update(); display.redraw(); - ticktimer.sleep_ms(DWELL).unwrap(); - - // all white - for w in testpat.iter_mut() { - *w = 0xFFFF_FFFF; + }), + Some(Opcode::Devboot) => msg_scalar_unpack!(msg, ena, _, _, _, { + if ena != 0 { + display.set_devboot(true); + } else { + display.set_devboot(false); + } + }), + Some(Opcode::RestartBulkRead) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + bulkread.from_offset = 0; + xous::return_scalar(msg.sender, 0) + .expect("couldn't ack that bulk read pointer was reset"); + }), + Some(Opcode::BulkReadFonts) => { + let fontlen = fontmap::FONT_TOTAL_LEN as u32 + 8; + let mut buf = unsafe { + Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) + }; + //let mut bulkread = buf.as_flat::().unwrap(); // try to skip the copy/init step by using a persistent structure + let fontslice = fontregion.as_slice::(); + assert!(fontlen <= fontslice.len() as u32); + if bulkread.from_offset >= fontlen { + log::error!( + "BulkReadFonts attempt to read out of bound on the font area; ignoring!" + ); + continue; + } + let readlen = if bulkread.from_offset + bulkread.buf.len() as u32 > fontlen { + // returns what is readable of the last bit; anything longer than the fontlen is undefined/invalid + fontlen as usize - bulkread.from_offset as usize + } else { + bulkread.buf.len() + }; + for (&src, dst) in fontslice + [bulkread.from_offset as usize..bulkread.from_offset as usize + readlen] + .iter() + .zip(bulkread.buf.iter_mut()) + { + *dst = src; + } + bulkread.len = readlen as u32; + bulkread.from_offset += readlen as u32; + buf.replace(bulkread).unwrap(); + } + Some(Opcode::TestPattern) => msg_blocking_scalar_unpack!(msg, duration, _, _, _, { + let mut stashmem = xous::syscall::map_memory( + None, + None, + ((backend::FB_SIZE * 4) + 4096) & !4095, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map stash frame buffer"); + let stash = &mut stashmem.as_slice_mut()[..backend::FB_SIZE]; + for (&src, dst) in display.as_slice().iter().zip(stash.iter_mut()) { + *dst = src; + } + for lines in 0..backend::FB_LINES { // mark all lines dirty + stash[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000; } - // dirty bits already set - display.blit_screen(testpat); - display.update(); - display.redraw(); - ticktimer.sleep_ms(DWELL).unwrap(); - // vertical bars - for lines in 0..backend::FB_LINES { - for words in 0..backend::FB_WIDTH_WORDS { - testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xaaaa_aaaa; + let start_time = ticktimer.elapsed_ms(); + let mut testmem = xous::syscall::map_memory( + None, + None, + ((backend::FB_SIZE * 4) + 4096) & !4095, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map stash frame buffer"); + let testpat = &mut testmem.as_slice_mut()[..backend::FB_SIZE]; + const DWELL: usize = 1000; + while ticktimer.elapsed_ms() - start_time < duration as u64 { + // all black + for w in testpat.iter_mut() { + *w = 0; } - } - display.blit_screen(testpat); - display.update(); - display.redraw(); - ticktimer.sleep_ms(DWELL).unwrap(); - - for lines in 0..backend::FB_LINES { - for words in 0..backend::FB_WIDTH_WORDS { - testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x5555_5555; + for lines in 0..backend::FB_LINES { // mark dirty bits + testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000; } - } - display.blit_screen(testpat); - display.update(); - display.redraw(); - ticktimer.sleep_ms(DWELL).unwrap(); + display.blit_screen(testpat); + display.update(); + display.redraw(); + ticktimer.sleep_ms(DWELL).unwrap(); - // horiz bars - for lines in 0..backend::FB_LINES { - for words in 0..backend::FB_WIDTH_WORDS { - if lines % 2 == 0 { - testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x0; - } else { - testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xffff_ffff; + // all white + for w in testpat.iter_mut() { + *w = 0xFFFF_FFFF; + } + // dirty bits already set + display.blit_screen(testpat); + display.update(); + display.redraw(); + ticktimer.sleep_ms(DWELL).unwrap(); + + // vertical bars + for lines in 0..backend::FB_LINES { + for words in 0..backend::FB_WIDTH_WORDS { + testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xaaaa_aaaa; } } - testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000; - } - display.blit_screen(testpat); - display.update(); - display.redraw(); - ticktimer.sleep_ms(DWELL).unwrap(); + display.blit_screen(testpat); + display.update(); + display.redraw(); + ticktimer.sleep_ms(DWELL).unwrap(); - for lines in 0..backend::FB_LINES { - for words in 0..backend::FB_WIDTH_WORDS { - if lines % 2 == 1 { - testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x0; - } else { - testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xffff_ffff; + for lines in 0..backend::FB_LINES { + for words in 0..backend::FB_WIDTH_WORDS { + testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x5555_5555; } } - testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000; + display.blit_screen(testpat); + display.update(); + display.redraw(); + ticktimer.sleep_ms(DWELL).unwrap(); + + // horiz bars + for lines in 0..backend::FB_LINES { + for words in 0..backend::FB_WIDTH_WORDS { + if lines % 2 == 0 { + testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x0; + } else { + testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xffff_ffff; + } + } + testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000; + } + display.blit_screen(testpat); + display.update(); + display.redraw(); + ticktimer.sleep_ms(DWELL).unwrap(); + + for lines in 0..backend::FB_LINES { + for words in 0..backend::FB_WIDTH_WORDS { + if lines % 2 == 1 { + testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x0; + } else { + testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xffff_ffff; + } + } + testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000; + } + display.blit_screen(testpat); + display.update(); + display.redraw(); + ticktimer.sleep_ms(DWELL).unwrap(); + } - display.blit_screen(testpat); - display.update(); - display.redraw(); - ticktimer.sleep_ms(DWELL).unwrap(); + display.blit_screen(stash); + xous::return_scalar(msg.sender, duration).expect("couldn't ack test pattern"); + }), + Some(Opcode::Quit) => break, + None => { + log::error!("received opcode scalar that is not handled"); } - display.blit_screen(stash); - - xous::return_scalar(msg.sender, duration).expect("couldn't ack test pattern"); - }), - Some(Opcode::Quit) => break, - None => { - log::error!("received opcode scalar that is not handled"); } + } else { + // this is effectively an abort, because this is long enough for the WDT to fire and reboot the system + ticktimer.sleep_ms(10_000).unwrap(); } } log::trace!("main loop exit, destroying servers"); diff --git a/services/graphics-server/src/panic.rs b/services/graphics-server/src/panic.rs new file mode 100644 index 000000000..8f5af1c27 --- /dev/null +++ b/services/graphics-server/src/panic.rs @@ -0,0 +1,233 @@ +use std::thread; +use core::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use utralib::generated::*; + +const PANIC_STD_SERVER: &[u8; 16] = b"panic-to-screen!"; + +/// We can have no allocations inside this, and ideally, it's as minimal as possible. +/// +/// The graphics handler code and font renderer code are duplicated into this module to +/// minimize cross-thread dependencies. +/// +/// Some simplifying assumptions include: +/// - Only Latin, monospace (16-px wide) characters from the `mono` font set. +/// - Panics occupy a fixed area in the center of the screen, that can only hold +/// a limited amount of text: 304-px x 384-px text area = 40 char x 24 lines = 960 chars +/// - The Panic frame is slightly larger to give a cosmetic border, a total of 320 x 400 px +/// - Panics are black background with white text to distinguish them as secured system messages. +/// - The glyph set is passed into the handler as a static structure. +/// - Panics can't be dismissed, and should persist even if other threads are capable of running. +/// Thus there is a variable shared with the parent thread to stop redraws permanently in the +/// case of a panic. +/// +/// Frame buffer is 336 px wide, which is 10.5 32-bit words. The excess 16 bits are the dirty bit field. + +use crate::{ + backend::{FB_WIDTH_PIXELS, FB_WIDTH_WORDS, FB_SIZE}, + api::{PixelColor, GlyphSprite}, blitstr2::NULL_GLYPH_SPRITE +}; +const TOP_OFFSET: usize = 48; +const WIDTH_CHARS: usize = 40; +const HEIGHT_CHARS: usize = 24; +const TOTAL_CHARS: usize = WIDTH_CHARS * HEIGHT_CHARS; +// these are fixed by the monospace font +const GLYPH_HEIGHT: usize = 15; +const GLYPH_WIDTH: usize = 7; +// this can be adjusted to create more border around the panic box +const TEXT_MARGIN: usize = 8; + +// some derived constants to help with layout +const BOTTOM_LINE: usize = TOP_OFFSET + HEIGHT_CHARS * GLYPH_HEIGHT + TEXT_MARGIN * 2; +const LEFT_EDGE: usize = (FB_WIDTH_PIXELS - (WIDTH_CHARS * GLYPH_WIDTH + TEXT_MARGIN * 2)) / 2; // 24 +const RIGHT_EDGE: usize = FB_WIDTH_PIXELS - LEFT_EDGE; // 312 + +pub(crate) fn panic_handler_thread( + is_panic: Arc::, + hwfb: u32, + control: u32, +) { + thread::spawn({ + move || { + let panic_server = xous::create_server_with_address(PANIC_STD_SERVER) + .expect("Couldn't create panic server"); + + let mut display = unsafe { PanicDisplay::new(hwfb, control) }; + let mut panic_text = xous_ipc::String::::new(); + loop { + let msg = xous::receive_message(panic_server).unwrap(); + + // this will put the graphics renderer in panic mode. + if !is_panic.load(Ordering::Relaxed) { + // this locks out updates from the main loop + is_panic.store(true, Ordering::Relaxed); + display.panic_rectangle(); + display.append_string(" ~~Guru Meditation~~\n\n"); + display.update_dirty(); + } + let body = match msg.body.memory_message() { + Some(body) => body, + None => { + log::error!("Incorrect message type to panic renderer"); + return; + } + }; + let len = match body.valid { + Some(v) => v, + None => continue, // ignore, don't fail + }.get(); + let s = unsafe{core::str::from_utf8_unchecked( + &body.buf.as_slice()[..len] + )}; + display.append_string(s); + panic_text.append( + unsafe{ + core::str::from_utf8_unchecked( + &body.buf.as_slice()[..len] + ) + } + ).ok(); + } + + } + }); +} + +/// All-in-one object to manage a framebuffer and layout text. +struct PanicDisplay<'a> { + fb: &'a mut [u32], + csr: CSR::, + x: usize, + y: usize, +} +impl<'a> PanicDisplay<'a> { + /// # Safety + /// + /// This function takes "plain old 32-bit numbers" and transforms them + /// into hardware pointers to the frame buffer and CSR offsets. It's meant + /// to be pared with the `hw_regs` output from the XousDisplay object, and + /// there will be frame buffer conflicts unless some kind of mutex is wrapped + /// around any other code that might compete for access to these resources. + unsafe fn new(raw_fb: u32, control: u32) -> Self { + PanicDisplay { + fb: core::slice::from_raw_parts_mut(raw_fb as *mut u32, FB_SIZE), + csr: CSR::new(control as *mut u32), + x: TEXT_MARGIN, + y: TEXT_MARGIN, + } + } + fn update_dirty(&mut self) { + self.csr.wfo(utra::memlcd::COMMAND_UPDATEDIRTY, 1); + while self.busy() {} + } + fn busy(&self) -> bool { + self.csr.rf(utra::memlcd::BUSY_BUSY) == 1 + } + fn put_pixel(&mut self, x: usize, y: usize, color: PixelColor) { + if color == PixelColor::Light { + self.fb[(x + y * FB_WIDTH_WORDS * 32) / 32] |= 1 << (x % 32) + } else { + self.fb[(x + y * FB_WIDTH_WORDS * 32) / 32] &= !(1 << (x % 32)) + } + // set the dirty bit on the line that contains the pixel + self.fb[y * FB_WIDTH_WORDS + (FB_WIDTH_WORDS - 1)] |= 0x1_0000; + } + /// draw a black rectangle into which all the characters are placed. + fn panic_rectangle(&mut self) { + for y in TOP_OFFSET..BOTTOM_LINE { + for x in LEFT_EDGE..RIGHT_EDGE { + self.put_pixel(x, y, PixelColor::Dark); + } + } + } + /// Blit a glyph + /// Examples of word alignment for destination frame buffer: + /// 1. Fits in word: xr:1..7 => (data[0].bit_30)->(data[0].bit_26), mask:0x7c00_0000 + /// 2. Spans words: xr:30..36 => (data[0].bit_01)->(data[1].bit_29), mask:[0x0000_0003,0xe000_000] + /// + fn draw_glyph(&mut self, x: usize, y: usize, gs: GlyphSprite) { + const SPRITE_PX: i16 = 16; + const SPRITE_WORDS: i16 = 8; + if gs.glyph.len() < SPRITE_WORDS as usize { + // Fail silently if the glyph slice was too small + // TODO: Maybe return an error? Not sure which way is better. + return; + } + let high = gs.high as i16; + let wide = gs.wide as i16; + if high > SPRITE_PX || wide > SPRITE_PX { + // Fail silently if glyph height or width is out of spec + // TODO: Maybe return an error? + return; + } + // Calculate word alignment for destination buffer + let x0 = (x + LEFT_EDGE) as i16; + let x1 = (x + LEFT_EDGE) as i16 + wide - 1; + let dest_low_word = x0 >> 5; + let dest_high_word = x1 >> 5; + let px_in_dest_low_word = 32 - (x0 & 0x1f); + // Blit it (use glyph height to avoid blitting empty rows) + let mut row_base = (y + TOP_OFFSET) as i16 * FB_WIDTH_WORDS as i16; + let row_upper_limit = BOTTOM_LINE as i16 * FB_WIDTH_WORDS as i16; + let row_lower_limit = TOP_OFFSET as i16 * FB_WIDTH_WORDS as i16; + let glyph = gs.glyph; + for y in 0..high as usize { + if row_base >= row_upper_limit { + // Clip anything that would run off the end of the frame buffer + break; + } + if row_base >= row_lower_limit { + // Unpack pixels for this glyph row. + // CAUTION: some math magic happening here... + // when y==0, this does (glyph[0] >> 0) & mask, + // when y==1, this does (glyph[0] >> 16) & mask, + // when y==2, this does (glyph[1] >> 0) & mask, + // ... + let mask = 0x0000ffff as u32; + let shift = (y as u32 & 1) << 4; + let pattern = (glyph[y >> 1] >> shift) & mask; + + // compute partial masks to prevent glyphs from "spilling over" the clip rectangle + let mut partial_mask_lo = 0xffff_ffff; + let mut partial_mask_hi = 0xffff_ffff; + if x0 < LEFT_EDGE as i16 || x1 >= RIGHT_EDGE as i16 { + let x0a = if x0 < LEFT_EDGE as i16 { RIGHT_EDGE as i16 } else { x0 }; + let x1a = if x1 >= LEFT_EDGE as i16 { RIGHT_EDGE as i16 } else { x1 }; + let mut ones = (1u64 << ((x1a - x0a) as u64 + 1)) - 1; + ones <<= x0a as u64 & 0x1f; + partial_mask_lo = ones as u32; + partial_mask_hi = (ones >> 32) as u32; + } + // XOR glyph pixels onto destination buffer. Note that despite the masks above, we will not render + // partial glyphs that cross the absolute bounds of the left and right edge of the screen. + if x0 >= 0 && x1 < FB_WIDTH_PIXELS as i16 { + self.fb[(row_base + dest_low_word) as usize] ^= (pattern << (32 - px_in_dest_low_word)) & partial_mask_lo; + if wide > px_in_dest_low_word { + self.fb[(row_base + dest_high_word) as usize] ^= (pattern >> px_in_dest_low_word) & partial_mask_hi; + } + } + self.fb[(row_base as usize + FB_WIDTH_WORDS - 1) as usize] |= 0x1_0000; // set the dirty bit on the line + } + + // Advance destination offset using + instead of * to maybe save some CPU cycles + row_base += FB_WIDTH_WORDS as i16; + } + } + /// start laying out the string from the top left and just wrap character by character, considering newlines + fn append_string(&mut self, s: &str) { + for ch in s.chars() { + if ch == '\n' { + self.y += GLYPH_HEIGHT; + self.x = TEXT_MARGIN; + continue; + } + self.draw_glyph(self.x, self.y, crate::blitstr2::mono_glyph(ch).unwrap_or(NULL_GLYPH_SPRITE)); + self.x += GLYPH_WIDTH; + if self.x >= WIDTH_CHARS * GLYPH_WIDTH { + self.x = TEXT_MARGIN; + self.y += GLYPH_HEIGHT; + } + } + } +} \ No newline at end of file From 9254d6830a97ebb628b75cdfa2f5bdb9569dfe69 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 10 Apr 2022 04:47:34 +0800 Subject: [PATCH 13/16] your host desires not your guru meditations ommmmmmmmm --- services/graphics-server/src/main.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index e55e1a3f3..95cb37afb 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -27,7 +27,9 @@ use xous_ipc::Buffer; mod fontmap; use api::BulkRead; +#[cfg(any(target_os = "none", target_os = "xous"))] // only install for hardware targets; hosted mode uses host's panic handler mod panic; + use core::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; From cb9ef127ce5fe29a1b6584e5610115a3b9da2f90 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 10 Apr 2022 15:52:31 +0800 Subject: [PATCH 14/16] add an off-line config reminder option in .config --- .cargo/config | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.cargo/config b/.cargo/config index 35049cbcb..67000f6e8 100644 --- a/.cargo/config +++ b/.cargo/config @@ -1,2 +1,5 @@ [alias] xtask = "run --package xtask --" + +# [net] +# offline = true # do not access the network From 46624addd0e068402d02d913a1057f3401977936 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 10 Apr 2022 15:52:57 +0800 Subject: [PATCH 15/16] clean up comments and review panic handler before push --- services/graphics-server/src/panic.rs | 30 +++++++++++++++++++-------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/services/graphics-server/src/panic.rs b/services/graphics-server/src/panic.rs index 8f5af1c27..75f14ae90 100644 --- a/services/graphics-server/src/panic.rs +++ b/services/graphics-server/src/panic.rs @@ -15,30 +15,33 @@ const PANIC_STD_SERVER: &[u8; 16] = b"panic-to-screen!"; /// - Only Latin, monospace (16-px wide) characters from the `mono` font set. /// - Panics occupy a fixed area in the center of the screen, that can only hold /// a limited amount of text: 304-px x 384-px text area = 40 char x 24 lines = 960 chars -/// - The Panic frame is slightly larger to give a cosmetic border, a total of 320 x 400 px +/// - The Panic frame is slightly larger to give a cosmetic border /// - Panics are black background with white text to distinguish them as secured system messages. -/// - The glyph set is passed into the handler as a static structure. /// - Panics can't be dismissed, and should persist even if other threads are capable of running. -/// Thus there is a variable shared with the parent thread to stop redraws permanently in the -/// case of a panic. +/// - The Panic handler can conflict with the regular display routines because it unsafely +/// creates a copy of all the hardware access structures. Thus there is a variable +/// shared with the parent thread to stop redraws permanently in the case of a panic. /// -/// Frame buffer is 336 px wide, which is 10.5 32-bit words. The excess 16 bits are the dirty bit field. +/// Note that the frame buffer is 336 px wide, which is 10.5 32-bit words. +/// The excess 16 bits are the dirty bit field. use crate::{ backend::{FB_WIDTH_PIXELS, FB_WIDTH_WORDS, FB_SIZE}, api::{PixelColor, GlyphSprite}, blitstr2::NULL_GLYPH_SPRITE }; +/// How far down the screen the panic box draws const TOP_OFFSET: usize = 48; +/// Width and height of the panic box in characters const WIDTH_CHARS: usize = 40; const HEIGHT_CHARS: usize = 24; const TOTAL_CHARS: usize = WIDTH_CHARS * HEIGHT_CHARS; -// these are fixed by the monospace font +/// these are fixed by the monospace font const GLYPH_HEIGHT: usize = 15; const GLYPH_WIDTH: usize = 7; -// this can be adjusted to create more border around the panic box +/// this can be adjusted to create more border around the panic box const TEXT_MARGIN: usize = 8; -// some derived constants to help with layout +/// some derived constants to help with layout const BOTTOM_LINE: usize = TOP_OFFSET + HEIGHT_CHARS * GLYPH_HEIGHT + TEXT_MARGIN * 2; const LEFT_EDGE: usize = (FB_WIDTH_PIXELS - (WIDTH_CHARS * GLYPH_WIDTH + TEXT_MARGIN * 2)) / 2; // 24 const RIGHT_EDGE: usize = FB_WIDTH_PIXELS - LEFT_EDGE; // 312 @@ -96,8 +99,11 @@ pub(crate) fn panic_handler_thread( /// All-in-one object to manage a framebuffer and layout text. struct PanicDisplay<'a> { + /// hardware framebuffer (no double buffering) fb: &'a mut [u32], + /// hardware register copy (very dangerous) csr: CSR::, + /// current x/y position of the latest character to add to the panic box x: usize, y: usize, } @@ -113,14 +119,17 @@ impl<'a> PanicDisplay<'a> { PanicDisplay { fb: core::slice::from_raw_parts_mut(raw_fb as *mut u32, FB_SIZE), csr: CSR::new(control as *mut u32), + // initialize to top left of panic box's margin x: TEXT_MARGIN, y: TEXT_MARGIN, } } + /// commits the data in the framebuffer to the screen fn update_dirty(&mut self) { self.csr.wfo(utra::memlcd::COMMAND_UPDATEDIRTY, 1); while self.busy() {} } + /// indicates if a commit is in progress fn busy(&self) -> bool { self.csr.rf(utra::memlcd::BUSY_BUSY) == 1 } @@ -133,7 +142,8 @@ impl<'a> PanicDisplay<'a> { // set the dirty bit on the line that contains the pixel self.fb[y * FB_WIDTH_WORDS + (FB_WIDTH_WORDS - 1)] |= 0x1_0000; } - /// draw a black rectangle into which all the characters are placed. + /// draw a black rectangle into which all the characters are placed. This could + /// probably be optimized to do its work in words instead of as pixels, but it works. fn panic_rectangle(&mut self) { for y in TOP_OFFSET..BOTTOM_LINE { for x in LEFT_EDGE..RIGHT_EDGE { @@ -146,6 +156,8 @@ impl<'a> PanicDisplay<'a> { /// 1. Fits in word: xr:1..7 => (data[0].bit_30)->(data[0].bit_26), mask:0x7c00_0000 /// 2. Spans words: xr:30..36 => (data[0].bit_01)->(data[1].bit_29), mask:[0x0000_0003,0xe000_000] /// + /// This is copied out of the blitstr2 module and adapted for the panic handler. + /// fn draw_glyph(&mut self, x: usize, y: usize, gs: GlyphSprite) { const SPRITE_PX: i16 = 16; const SPRITE_WORDS: i16 = 8; From 5d2c65cb6c271e85852da91a27a3dea2e915c182 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 10 Apr 2022 16:57:04 +0800 Subject: [PATCH 16/16] fix missing update to display in panic handler --- services/graphics-server/src/panic.rs | 11 +---------- services/shellchat/src/cmds/test.rs | 3 +++ 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/services/graphics-server/src/panic.rs b/services/graphics-server/src/panic.rs index 75f14ae90..fbf5ca86a 100644 --- a/services/graphics-server/src/panic.rs +++ b/services/graphics-server/src/panic.rs @@ -34,7 +34,6 @@ const TOP_OFFSET: usize = 48; /// Width and height of the panic box in characters const WIDTH_CHARS: usize = 40; const HEIGHT_CHARS: usize = 24; -const TOTAL_CHARS: usize = WIDTH_CHARS * HEIGHT_CHARS; /// these are fixed by the monospace font const GLYPH_HEIGHT: usize = 15; const GLYPH_WIDTH: usize = 7; @@ -57,7 +56,6 @@ pub(crate) fn panic_handler_thread( .expect("Couldn't create panic server"); let mut display = unsafe { PanicDisplay::new(hwfb, control) }; - let mut panic_text = xous_ipc::String::::new(); loop { let msg = xous::receive_message(panic_server).unwrap(); @@ -67,7 +65,6 @@ pub(crate) fn panic_handler_thread( is_panic.store(true, Ordering::Relaxed); display.panic_rectangle(); display.append_string(" ~~Guru Meditation~~\n\n"); - display.update_dirty(); } let body = match msg.body.memory_message() { Some(body) => body, @@ -84,13 +81,7 @@ pub(crate) fn panic_handler_thread( &body.buf.as_slice()[..len] )}; display.append_string(s); - panic_text.append( - unsafe{ - core::str::from_utf8_unchecked( - &body.buf.as_slice()[..len] - ) - } - ).ok(); + display.update_dirty(); } } diff --git a/services/shellchat/src/cmds/test.rs b/services/shellchat/src/cmds/test.rs index 33acf70f7..2abad0a3c 100644 --- a/services/shellchat/src/cmds/test.rs +++ b/services/shellchat/src/cmds/test.rs @@ -106,6 +106,9 @@ impl<'a> ShellCmdApi<'a> for Test { if let Some(sub_cmd) = tokens.next() { match sub_cmd { + "panic" => { + assert!(1 == 0, "Panic test: 1 == 0 failure!"); + } "instant" => { write!(ret, "start elapsed_ms {}\n", env.ticktimer.elapsed_ms()).unwrap(); let now = Instant::now();