From e2594a300025d043984c7de17194cc8296f53f8c Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 20 Oct 2023 00:39:03 +0800 Subject: [PATCH 01/16] fix visibility of default font --- services/graphics-server/src/api/text.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/graphics-server/src/api/text.rs b/services/graphics-server/src/api/text.rs index 75b32bfa1..6b9bea76b 100644 --- a/services/graphics-server/src/api/text.rs +++ b/services/graphics-server/src/api/text.rs @@ -79,7 +79,7 @@ impl From for TextOp { // roughly 168 bytes to represent the rest of the struct, and we want to fill out the 4096 byte page with text const TEXTVIEW_LEN: usize = 3072; -const TEXTVIEW_DEFAULT_STYLE: GlyphStyle = GlyphStyle::Regular; +pub const TEXTVIEW_DEFAULT_STYLE: GlyphStyle = GlyphStyle::Regular; #[derive(Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] pub struct TextView { From 8401d924e0ccac88794a00dc443edd7e33816096 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 20 Oct 2023 00:40:26 +0800 Subject: [PATCH 02/16] add opcodes for updating status bar and running busy animations --- libs/chat/src/api.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/libs/chat/src/api.rs b/libs/chat/src/api.rs index 2547a1892..41b29fab9 100644 --- a/libs/chat/src/api.rs +++ b/libs/chat/src/api.rs @@ -36,10 +36,20 @@ pub enum ChatOp { /// Find a Post by timestamp and Author PostFind, PostFlag, + /// Run or stop the busy animation. + SetBusyAnimationState, + /// Update just the state of the busy animation, if any. Internal opcode. + UpdateBusy, /// exit the application Quit, } +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum BusyAnimOp { + Start, + Pump, +} + #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub enum IconOp { PostMenu = 0, @@ -120,3 +130,11 @@ pub enum AuthorFlag { Hidden, Right, } + +#[derive(Archive, Serialize, Deserialize, Debug)] +pub struct BusyMessage { + /// If None, restores the last non-busy status bar message, and stops the animation. + /// If Some, updates the status bar to contain the busy message and + /// starts the animation running. + pub busy_msg: Option>, +} From 355425726d165b8ed4047bb8bcced4c65b8820ef Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 20 Oct 2023 00:41:19 +0800 Subject: [PATCH 03/16] add data structures to track status bar state - status bar gets some initial text on boot - previous status message is saved when entering a busy state, and restored on exit - add routines for hopefully making the redraw a bit more efficient if the only thing happening is a busy-wait update. --- libs/chat/src/ui.rs | 101 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 98 insertions(+), 3 deletions(-) diff --git a/libs/chat/src/ui.rs b/libs/chat/src/ui.rs index 869936265..a5e44df00 100644 --- a/libs/chat/src/ui.rs +++ b/libs/chat/src/ui.rs @@ -4,21 +4,25 @@ use crate::icontray::Icontray; use dialogue::{post::Post, Dialogue}; use gam::{menu_matic, MenuMatic, UxRegistration}; use graphics_server::api::GlyphStyle; -use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView}; +use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView, Line}; use locales::t; use modals::Modals; use rkyv::de::deserializers::AllocDeserializer; use rkyv::ser::serializers::WriteSerializer; use rkyv::ser::Serializer; use rkyv::Deserialize; +use ticktimer_server::Ticktimer; use std::cmp::min; use std::convert::TryFrom; +use std::fmt::Write as TextWrite; use std::io::{Error, ErrorKind, Read, Write}; use xous::{MessageEnvelope, CID}; use xous_names::XousNames; +pub const BUSY_ANIMATION_RATE_MS: usize = 50; + #[allow(dead_code)] pub(crate) struct Ui { // optional structures that indicate new input to the Chat loop per iteration @@ -42,6 +46,7 @@ pub(crate) struct Ui { canvas: Gid, gam: gam::Gam, modals: Modals, + tt: Ticktimer, // variables regarding the posts currently onscreen // the selected post is hilighted onscreen and the focus of the msg menu F4 @@ -53,6 +58,14 @@ pub(crate) struct Ui { // variables that define our graphical attributes screensize: Point, + /// height of the status bar. This is subtracted from screensize. + status_height: u16, + /// TextView for the status bar. This encapsulates the state of the busy animation, and the text within. + status_tv: TextView, + /// track the last time we update the status bar; use this avoid double-updating busy animations + status_last_update_ms: u64, + /// track the last non-busy message so we can restore it when the busy state stops + status_last_msg: Option, bubble_width: u16, margin: Point, // margin to edge of canvas bubble_margin: Point, // margin of text in bubbles @@ -114,6 +127,24 @@ impl Ui { .expect("couldn't create MenuMatic manager"); let pddb = pddb::Pddb::new(); pddb.try_mount(); + + // setup the initial status bar contents + let margin = Point::new(4, 4); + let status_height = gam.glyph_height_hint( + graphics_server::api::text::TEXTVIEW_DEFAULT_STYLE).unwrap() as u16 + + margin.y as u16 * 2; + let mut status_tv = TextView::new(canvas, + TextBounds::BoundingBox(Rectangle::new( + Point::new(0, 0), + Point::new(screensize.x, status_height as i16) + )) + ); + status_tv.margin = margin; + status_tv.draw_border = false; + status_tv.clear_area = true; + write!(status_tv, "{}", t!("chat.status.initial", locales::LANG).to_string()).ok(); + let tt = ticktimer_server::Ticktimer::new().unwrap(); + let status_last_update_ms = tt.elapsed_ms(); Ui { input: None, msg: None, @@ -126,7 +157,12 @@ impl Ui { canvas, gam, modals, + tt, screensize, + status_height, + status_tv, + status_last_update_ms, + status_last_msg: None, post_selected: None, post_anchor: None, post_topdown: false, @@ -517,6 +553,12 @@ impl Ui { } else { bubble_tv.border_width = 1; } + bubble_tv.clip_rect = Some( + Rectangle::new( + Point::new(0, self.status_height as i16 + self.margin.y), + self.screensize + ) + ); bubble_tv.draw_border = true; bubble_tv.clear_area = true; bubble_tv.rounded_border = Some(self.bubble_radius); @@ -535,7 +577,7 @@ impl Ui { .draw_rectangle( self.canvas, Rectangle::new_with_style( - Point::new(0, 0), + Point::new(0, self.status_height as i16), self.screensize, DrawStyle { fill_color: Some(PixelColor::Light), @@ -574,6 +616,7 @@ impl Ui { while !self.layout().unwrap_or(true) && attempt < 3 { attempt += 1; } + self.status_last_update_ms = self.tt.elapsed_ms(); } else { self.clear_area(); // no dialogue so clear screen } @@ -582,6 +625,49 @@ impl Ui { Ok(()) } + /// Update the busy state. Does not touch any other aspect of the screen layout. + pub(crate) fn redraw_busy(&mut self) -> Result<(), xous::Error> { + let curtime = self.tt.elapsed_ms(); + if curtime - self.status_last_update_ms > BUSY_ANIMATION_RATE_MS as u64 { + self.gam.post_textview(&mut self.status_tv)?; + self.gam.redraw().expect("couldn't redraw screen"); + self.status_last_update_ms = curtime; + } + Ok(()) + } + + /// Returns `true` if the status bar is currently set for the busy animation + pub(crate) fn is_busy(&self) -> bool { + self.status_tv.busy_animation_state.is_some() + } + + /// If not currently busy, save the current status bar message and kick off the animation. + /// Updates the text of the status bar in all cases. + pub(crate) fn set_busy(&mut self, msg: &str) { + if self.status_tv.busy_animation_state.is_none() { + // stash a copy of the last message that wasn't a busy message + self.status_last_msg = Some( + self.status_tv.to_str().to_owned() + ); + self.status_tv.busy_animation_state = Some(0); + } + self.status_tv.clear_str(); + write!(self.status_tv, "{}", msg).ok(); + xous::send_message(self.app_cid.unwrap(), + xous::Message::new_scalar( + ChatOp::UpdateBusy as usize, 0, 0, 0, 0) + ).ok(); + } + + /// Stops the busy animation state + pub(crate) fn clear_busy(&mut self) { + self.status_tv.busy_animation_state = None; + if let Some(prev_msg) = self.status_last_msg.take() { + self.status_tv.clear_str(); + write!(self.status_tv, "{}", prev_msg).ok(); + } + } + /// Layout the post bubbles on the screen. /// /// The layout proceeds from top-down or bottom-up (starting with the @@ -599,6 +685,15 @@ impl Ui { /// fn layout(&mut self) -> Result { self.clear_area(); + self.gam.post_textview(&mut self.status_tv) + .expect("couldn't render status bar"); + let status_border = Line::new( + Point::new(0, self.status_height as i16), + Point::new(self.screensize.x, self.status_height as i16) + ); + self.gam.draw_line(self.canvas, + status_border + ).expect("couldn't draw status lower border"); match (&self.dialogue, &self.post_anchor) { (Some(dialogue), Some(post_anchor)) => { log::info!("redrawing dialogue: {}", dialogue.title); @@ -608,7 +703,7 @@ impl Ui { // initialise the first post index AND the vertical position on the screen let mut post_index = *post_anchor; let mut anchor_y = match self.post_topdown { - true => 0, + true => self.status_height as i16 + self.margin.y, false => self.screensize.y - self.margin.y, }; From b456bfaf3be3d9237e702709bd5ead82917c45df Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 20 Oct 2023 00:43:09 +0800 Subject: [PATCH 04/16] add busy-wait animation server and hooks for managing the same Busy-wait animaitions are handled by a helper server that is normally blocked. A single shared `bool` indicates whether the animation should run or not. When woken up, the busy-wait animator will check if the shared `bool` is set, and if so, send a message to the main loop to update the animation, then send wait an appropriate timeout and send itself a message to re-check the animation status. This particular format of server is fairly compact but can be vulnerable to a "message storm" if busy state updates happen in rapid succession without allowing the server to unblock and handle messages. Thus, all messages to this server use a `try_send` method, with a silent failure if the message can't be sent. In other words, if the animator is already super busy and its queue is full, don't send it more messages, just drop the existing updates so we can fail without a panic or deadlock. The typical consequence of this is some UX inconsistency, which is not a critical error. --- libs/chat/src/lib.rs | 120 ++++++++++++++++++++++++++++++++++++++++++ libs/chat/src/main.rs | 16 +++++- 2 files changed, 135 insertions(+), 1 deletion(-) diff --git a/libs/chat/src/lib.rs b/libs/chat/src/lib.rs index e2a4b58dd..5b7b3dd36 100644 --- a/libs/chat/src/lib.rs +++ b/libs/chat/src/lib.rs @@ -4,11 +4,13 @@ pub mod icontray; pub mod ui; pub use api::*; +pub use ui::BUSY_ANIMATION_RATE_MS; use gam::MenuItem; use num_traits::FromPrimitive; use std::convert::TryInto; use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; +use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering}; use xous::{Error, CID, SID}; use xous_ipc::Buffer; @@ -40,6 +42,18 @@ impl Chat { let chat_sid = xous::create_server().unwrap(); let chat_cid = xous::connect(chat_sid).unwrap(); + let busy_bumper = xous::create_server().unwrap(); + let busy_bumper_cid = xous::connect(busy_bumper).unwrap(); + + log::info!("starting idle animation runner"); + let run_busy_animation = Arc::new(AtomicBool::new(false)); + thread::spawn({ + let run_busy_animation = run_busy_animation.clone(); + move || { + busy_animator(busy_bumper, busy_bumper_cid, chat_cid, run_busy_animation); + } + }); + log::info!("Starting chat UI server",); thread::spawn({ move || { @@ -51,6 +65,8 @@ impl Chat { opcode_post, opcode_event, opcode_rawkeys, + run_busy_animation, + busy_bumper_cid, ); } }); @@ -222,6 +238,78 @@ impl Chat { .map(|_| ()) .expect("failed to Redraw Chat UI"); } + + /// Run or stop the busy/waiting animation. + /// + /// # Arguments + /// + /// `msg` - If `Some()`, updates the status bar to show the `msg` and start the animation running + /// If `None`, restores the last status message before being busy and stops the animation. + pub fn set_busy_state(&self, msg: Option) -> Result<(), Error> { + let bm = BusyMessage { + busy_msg: match msg { + None => None, + Some(m) => { + Some( + xous_ipc::String::from_str(&m) + ) + } + } + }; + match Buffer::into_buf(bm) { + Ok(buf) => match buf.send(self.cid, ChatOp::SetBusyAnimationState as u32) { + Ok(..) => { + Ok(()) + } + Err(_) => Err(xous::Error::InternalError), + }, + Err(_) => Err(xous::Error::InternalError), + } + } +} + +/// Helper server that pumps the busy animation state until instructed to stop. +/// +/// # Arguments +/// +/// * `busy_bumper` - the server ID to use for the helper server +/// * `busy_bumper_cid` - the corresponding connection ID +/// * `chat_cid` - the CID to the main chat loop, used to initiate redraw events as necessary +/// * `run_busy_animation` - a shared `AtomicBool` which, when `true`, causes the loop to reschedule itself to run. +pub fn busy_animator( + busy_bumper: SID, + busy_bumper_cid : CID, + chat_cid: CID, + run_busy_animation: Arc) { + let tt = ticktimer_server::Ticktimer::new().unwrap(); + loop { + let msg = xous::receive_message(busy_bumper).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(BusyAnimOp::Start) => { + tt.sleep_ms(crate::BUSY_ANIMATION_RATE_MS).unwrap(); + xous::try_send_message(busy_bumper_cid, + xous::Message::new_scalar( + BusyAnimOp::Pump as usize, 0, 0, 0, 0) + ).ok(); + } + Some(BusyAnimOp::Pump) => { + if run_busy_animation.load(Ordering::SeqCst) { + xous::try_send_message(chat_cid, + xous::Message::new_scalar( + ChatOp::UpdateBusy as usize, 0, 0, 0, 0) + ).ok(); + tt.sleep_ms(crate::BUSY_ANIMATION_RATE_MS).unwrap(); + xous::try_send_message(busy_bumper_cid, + xous::Message::new_scalar( + BusyAnimOp::Pump as usize, 0, 0, 0, 0) + ).ok(); + } + } + _ => { + log::warn!("Unexpected message: {:?}", msg); + } + } + } } /// The Chat UI server a manages a Chat UI to read a display and navigate a @@ -245,6 +333,8 @@ pub fn server( opcode_post: Option, opcode_event: Option, opcode_rawkeys: Option, + run_busy_animation: Arc, + busy_bumper_cid: CID, ) -> ! { //log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Info); @@ -256,7 +346,37 @@ pub fn server( loop { let msg = xous::receive_message(sid).unwrap(); log::debug!("got message {:?}", msg); + if ui.is_busy() { + if !run_busy_animation.swap(true, Ordering::SeqCst) { + // only send off the Pump request on the transition from false->true; this causes the machine to run + xous::try_send_message(busy_bumper_cid, + xous::Message::new_scalar( + BusyAnimOp::Pump as usize, 0, 0, 0, 0) + ).ok(); + } + } else { + // make sure the animation stops running. Not sure if this is the most efficient way to handle this, + // but I think an atomic bool set is just a couple dozen CPU cycles...? + run_busy_animation.store(false, Ordering::SeqCst); + } match FromPrimitive::from_usize(msg.body.id()) { + Some(ChatOp::UpdateBusy) => { + ui.redraw_busy().expect("CHAT couldn't redraw"); + } + Some(ChatOp::SetBusyAnimationState) => { + let buffer = unsafe { + Buffer::from_memory_message(msg.body.memory_message().unwrap()) + }; + let s = buffer.to_original::().unwrap(); + match s.busy_msg { + Some(msg) => { + ui.set_busy(msg.as_str().unwrap()); + } + None => { + ui.clear_busy(); + } + } + } Some(ChatOp::DialogueSave) => { log::info!("ChatOp::DialogueSave"); ui.dialogue_save().expect("failed to save Dialogue"); diff --git a/libs/chat/src/main.rs b/libs/chat/src/main.rs index a3ed51114..a5b4838b2 100644 --- a/libs/chat/src/main.rs +++ b/libs/chat/src/main.rs @@ -3,9 +3,12 @@ mod api; use api::*; +use num_traits::FromPrimitive; use std::thread; use xous::{Error, CID, SID}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; pub fn main() -> ! { let xns = xous_names::XousNames::new().unwrap(); @@ -17,10 +20,21 @@ pub fn main() -> ! { let chat_sid = xous::create_server().unwrap(); let chat_cid = xous::connect(chat_sid).unwrap(); + let busy_bumper = xous::create_server().unwrap(); + let busy_bumper_cid = xous::connect(busy_bumper).unwrap(); + + log::info!("starting idle animation runner"); + let run_busy_animation = Arc::new(AtomicBool::new(false)); + thread::spawn({ + let run_busy_animation = run_busy_animation.clone(); + move || { + busy_animator(busy_bumper, busy_bumper_cid, chat_cid, run_busy_animation); + } + }); log::info!("Starting chat server",); thread::spawn({ move || { - server(chat_sid, None, None); + server(chat_sid, None, None, run_busy_animation, busy_bumper_cid); } }); xous::terminate_process(0) From be39c44b17cd456736c577eead9145e6b9ed5b25 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 20 Oct 2023 00:48:10 +0800 Subject: [PATCH 05/16] add a stand-in initial startup message This prompts users on how to raise the menu. Not sure if it's the right thing, but it's something. --- libs/chat/locales/i18n.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libs/chat/locales/i18n.json b/libs/chat/locales/i18n.json index 21546394f..d8a49f26c 100644 --- a/libs/chat/locales/i18n.json +++ b/libs/chat/locales/i18n.json @@ -19,6 +19,10 @@ "en": "no dialogues available to read", "en-tts": "no dialogues available to read" }, + "chat.status.initial" : { + "en": "use ← for login menu", + "en-tts": "use ← for login menu" + }, "chat.help.navigation": { "en": "use ↑ & ↓ to scroll thru old posts\nuse ← & → to show menus\nF1-F4 dont do anything yet.", "en-tts": "use ↑ & ↓ to scroll thru old posts\nuse ← & → to show menus\nF1-F4 dont do anything yet." From 4142549804b69ce6e0b8722c3dd68cbc72643013 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 20 Oct 2023 00:50:29 +0800 Subject: [PATCH 06/16] try to lay in some hooks for how to interact with the busy API this is just an example, want to get this up for review before debugging all the problems --- apps/mtxchat/locales/i18n.json | 12 ++++++++++++ apps/mtxchat/src/lib.rs | 10 ++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/apps/mtxchat/locales/i18n.json b/apps/mtxchat/locales/i18n.json index e7d1166c2..eb368f85e 100644 --- a/apps/mtxchat/locales/i18n.json +++ b/apps/mtxchat/locales/i18n.json @@ -1,4 +1,16 @@ { + "mtxchat.busy.connecting": { + "en": "Connecting...", + "en-tts": "Connecting..." + }, + "mtxchat.busy.updating": { + "en": "Updating...", + "en-tts": "Updating..." + }, + "mtxchat.busy.sending": { + "en": "Sending...", + "en-tts": "Sending..." + }, "mtxchat.clock.warning": { "en": "WARNING: clock not set", "en-tts": "WARNING: clock not set", diff --git a/apps/mtxchat/src/lib.rs b/apps/mtxchat/src/lib.rs index bee9672b2..d78b66569 100644 --- a/apps/mtxchat/src/lib.rs +++ b/apps/mtxchat/src/lib.rs @@ -241,6 +241,7 @@ impl<'a> MtxChat<'a> { pub fn connect(&mut self) -> bool { log::info!("Attempting connect to Matrix server"); + self.chat.set_busy_state(Some(t!("mtxchat.busy.connecting", locales::LANG).to_owned())).expect("couldn't set busy state"); if self.wifi() { if self.login() { if let Some(_room_id) = self.get_room_id() { @@ -252,6 +253,7 @@ impl<'a> MtxChat<'a> { .show_notification(t!("mtxchat.listen.patience", locales::LANG), None) .expect("notification failed"); } + self.chat.set_busy_state(None).expect("couldn't clear busy state"); return true; } else { self.modals @@ -273,6 +275,7 @@ impl<'a> MtxChat<'a> { .expect("notification failed"); } self.dialogue_set(None); + self.chat.set_busy_state(None).expect("couldn't clear busy state"); false } @@ -626,14 +629,17 @@ impl<'a> MtxChat<'a> { &self.room_id, ) { (true, Some(token), Some(user_domain), Some(room_id)) => { + self.chat.set_busy_state(Some(t!("mtxchat.busy.sending", locales::LANG).to_owned())).expect("couldn't set busy state"); log::info!("txn_id = {}", txn_id); let mut url = Url::parse("https://matrix.org").unwrap(); url.set_host(Some(user_domain)).expect("failed to set host"); - if web::send_message(&mut url, &room_id, &text, &txn_id, token, &mut self.agent) { + let r = if web::send_message(&mut url, &room_id, &text, &txn_id, token, &mut self.agent) { "SENT" } else { "FAILED TO SEND" - } + }; + self.chat.set_busy_state(None).expect("couldn't clear busy state"); + r } (false, _, _, _) => "Not logged in", (_, None, _, _) => "No token set", From 8f549b30318157ab6a1dc7ae483f284d7ef4309e Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 28 Oct 2023 22:48:52 +0800 Subject: [PATCH 07/16] pick a more "happens to be aesthetic" setting for the XOR op defacing XOR op should not be usable to create fake security boxes but it also looks really ugly to have it defaced. This small tweak makes the XOR function look decent for the initial purpose of the function (chat status bar wait indicator). Eventually, this will be a controversial decision, but I'll kick that down the road. --- services/graphics-server/src/op.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/graphics-server/src/op.rs b/services/graphics-server/src/op.rs index 43bdc9e43..f293203b4 100644 --- a/services/graphics-server/src/op.rs +++ b/services/graphics-server/src/op.rs @@ -275,7 +275,7 @@ pub fn rectangle(fb: &mut LcdFB, rect: Rectangle, clip: Option, xor: // This is to make it annoying for someone using an XOR rectangle to synthesize inverted // text on an otherwise untrusted dialog box (I suspect it's not impossible, but introduces // a likelihood of drawing artifacts especially across translations and font size selections). - if pixel.0.y % 20 < 18 { + if pixel.0.y % 25 != 5 { xor_pixel(fb, pixel.0.x, pixel.0.y); } else { // don't allow XOR on some pixels to avoid this being used as a primitive to synthesize secure boxes From d844c4306c5582e91b99cc87ffe0798d64556aad Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 28 Oct 2023 22:50:23 +0800 Subject: [PATCH 08/16] reduce size of chat status bar to match status bars above --- libs/chat/src/ui.rs | 7 ++++--- services/graphics-server/src/testing.rs | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/libs/chat/src/ui.rs b/libs/chat/src/ui.rs index a5e44df00..9e37365aa 100644 --- a/libs/chat/src/ui.rs +++ b/libs/chat/src/ui.rs @@ -131,17 +131,18 @@ impl Ui { // setup the initial status bar contents let margin = Point::new(4, 4); let status_height = gam.glyph_height_hint( - graphics_server::api::text::TEXTVIEW_DEFAULT_STYLE).unwrap() as u16 - + margin.y as u16 * 2; + GlyphStyle::Regular).unwrap() as u16; let mut status_tv = TextView::new(canvas, TextBounds::BoundingBox(Rectangle::new( Point::new(0, 0), - Point::new(screensize.x, status_height as i16) + Point::new(screensize.x, status_height as _), )) ); + status_tv.style = GlyphStyle::Regular; status_tv.margin = margin; status_tv.draw_border = false; status_tv.clear_area = true; + status_tv.margin = Point::new(0, 0); write!(status_tv, "{}", t!("chat.status.initial", locales::LANG).to_string()).ok(); let tt = ticktimer_server::Ticktimer::new().unwrap(); let status_last_update_ms = tt.elapsed_ms(); diff --git a/services/graphics-server/src/testing.rs b/services/graphics-server/src/testing.rs index 716ef9bfe..8ea7e7635 100644 --- a/services/graphics-server/src/testing.rs +++ b/services/graphics-server/src/testing.rs @@ -56,7 +56,7 @@ pub fn tests() { let mut tv = TextView::new(Gid::new([0, 0, 0, 0]), TextBounds::BoundingBox(anim_rect)); tv.clip_rect = Some(clipping_area); - tv.style = TEST_STYLE; + tv.style = GlyphStyle::Small; tv.ellipsis = false; write!(tv, "Test of busy animation").unwrap(); tv.insertion = None; From 4e027b676cc88af3cf6fdfa4fc12333cf3a7f9ce Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 29 Oct 2023 01:08:38 +0800 Subject: [PATCH 09/16] remove logic from status primitive and make the interface simpler - status bar text is just status bar text now - idle animation runs/stops based on an explicit run/stop message Note that at the moment if one starts the busy bar and a modal pops up, you might overflow the queue of the ui drawing thread with animation requests, because the thread blocks when the modal is summoned. Modals "take the screen" anyways, so maybe the solution to this is to add an additional interlock around any modal calls within the UI main thread. Need to think about it a bit more. --- apps/mtxchat/locales/i18n.json | 4 ++ apps/mtxchat/src/lib.rs | 17 +++++-- libs/chat/locales/i18n.json | 4 +- libs/chat/src/api.rs | 7 ++- libs/chat/src/lib.rs | 83 ++++++++++++++++------------------ libs/chat/src/ui.rs | 28 ++++-------- 6 files changed, 68 insertions(+), 75 deletions(-) diff --git a/apps/mtxchat/locales/i18n.json b/apps/mtxchat/locales/i18n.json index eb368f85e..53ba2621a 100644 --- a/apps/mtxchat/locales/i18n.json +++ b/apps/mtxchat/locales/i18n.json @@ -18,6 +18,10 @@ "ja": "WARNING: clock not set *EN*", "zh": "WARNING: clock not set *EN*" }, + "mtxchat.status.default" : { + "en": "Use ← for login menu", + "en-tts": "Use ← for login menu" + }, "mtxchat.filter.failed": { "en": "error: could not create filter", "en-tts": "error: could not create filter", diff --git a/apps/mtxchat/src/lib.rs b/apps/mtxchat/src/lib.rs index d78b66569..35e18b256 100644 --- a/apps/mtxchat/src/lib.rs +++ b/apps/mtxchat/src/lib.rs @@ -83,6 +83,7 @@ pub struct MtxChat<'a> { modals: Modals, new_username: bool, new_room: bool, + status: String, } impl<'a> MtxChat<'a> { pub fn new(chat: &Chat) -> MtxChat { @@ -91,6 +92,8 @@ impl<'a> MtxChat<'a> { let trng = Trng::new(&xns).unwrap(); let pddb = pddb::Pddb::new(); pddb.try_mount(); + let status = t!("mtxchat.status.default", locales::LANG).to_owned(); + chat.set_status_text(&status); MtxChat { chat: chat, trng: trng, @@ -113,6 +116,7 @@ impl<'a> MtxChat<'a> { modals: modals, new_username: false, new_room: false, + status, } } @@ -241,7 +245,6 @@ impl<'a> MtxChat<'a> { pub fn connect(&mut self) -> bool { log::info!("Attempting connect to Matrix server"); - self.chat.set_busy_state(Some(t!("mtxchat.busy.connecting", locales::LANG).to_owned())).expect("couldn't set busy state"); if self.wifi() { if self.login() { if let Some(_room_id) = self.get_room_id() { @@ -253,7 +256,6 @@ impl<'a> MtxChat<'a> { .show_notification(t!("mtxchat.listen.patience", locales::LANG), None) .expect("notification failed"); } - self.chat.set_busy_state(None).expect("couldn't clear busy state"); return true; } else { self.modals @@ -275,11 +277,12 @@ impl<'a> MtxChat<'a> { .expect("notification failed"); } self.dialogue_set(None); - self.chat.set_busy_state(None).expect("couldn't clear busy state"); false } pub fn login(&mut self) -> bool { + self.chat.set_status_text(t!("mtxchat.busy.connecting", locales::LANG)); + self.chat.set_busy_state(true); self.token = self.get(TOKEN_KEY).unwrap_or(None); self.logged_in = false; @@ -338,6 +341,8 @@ impl<'a> MtxChat<'a> { self.unset(USER_DOMAIN_KEY) .expect("failed to unset user domain"); } + self.chat.set_status_text(&self.status); + self.chat.set_busy_state(false); self.logged_in } @@ -629,7 +634,8 @@ impl<'a> MtxChat<'a> { &self.room_id, ) { (true, Some(token), Some(user_domain), Some(room_id)) => { - self.chat.set_busy_state(Some(t!("mtxchat.busy.sending", locales::LANG).to_owned())).expect("couldn't set busy state"); + self.chat.set_status_text(t!("mtxchat.busy.sending", locales::LANG)); + self.chat.set_busy_state(true); log::info!("txn_id = {}", txn_id); let mut url = Url::parse("https://matrix.org").unwrap(); url.set_host(Some(user_domain)).expect("failed to set host"); @@ -638,7 +644,8 @@ impl<'a> MtxChat<'a> { } else { "FAILED TO SEND" }; - self.chat.set_busy_state(None).expect("couldn't clear busy state"); + self.chat.set_status_text(&self.status); + self.chat.set_busy_state(false); r } (false, _, _, _) => "Not logged in", diff --git a/libs/chat/locales/i18n.json b/libs/chat/locales/i18n.json index d8a49f26c..ede28f36f 100644 --- a/libs/chat/locales/i18n.json +++ b/libs/chat/locales/i18n.json @@ -20,8 +20,8 @@ "en-tts": "no dialogues available to read" }, "chat.status.initial" : { - "en": "use ← for login menu", - "en-tts": "use ← for login menu" + "en": "Idle", + "en-tts": "Idle" }, "chat.help.navigation": { "en": "use ↑ & ↓ to scroll thru old posts\nuse ← & → to show menus\nF1-F4 dont do anything yet.", diff --git a/libs/chat/src/api.rs b/libs/chat/src/api.rs index 41b29fab9..091e04870 100644 --- a/libs/chat/src/api.rs +++ b/libs/chat/src/api.rs @@ -36,6 +36,8 @@ pub enum ChatOp { /// Find a Post by timestamp and Author PostFind, PostFlag, + /// Set status bar text + SetStatusText, /// Run or stop the busy animation. SetBusyAnimationState, /// Update just the state of the busy animation, if any. Internal opcode. @@ -133,8 +135,5 @@ pub enum AuthorFlag { #[derive(Archive, Serialize, Deserialize, Debug)] pub struct BusyMessage { - /// If None, restores the last non-busy status bar message, and stops the animation. - /// If Some, updates the status bar to contain the busy message and - /// starts the animation running. - pub busy_msg: Option>, + pub busy_msg: xous_ipc::String<128>, } diff --git a/libs/chat/src/lib.rs b/libs/chat/src/lib.rs index 5b7b3dd36..a95272bab 100644 --- a/libs/chat/src/lib.rs +++ b/libs/chat/src/lib.rs @@ -12,7 +12,7 @@ use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering}; -use xous::{Error, CID, SID}; +use xous::{Error, CID, SID, msg_scalar_unpack}; use xous_ipc::Buffer; pub struct Chat { @@ -239,32 +239,31 @@ impl Chat { .expect("failed to Redraw Chat UI"); } - /// Run or stop the busy/waiting animation. + /// Set the status bar text. /// /// # Arguments /// - /// `msg` - If `Some()`, updates the status bar to show the `msg` and start the animation running - /// If `None`, restores the last status message before being busy and stops the animation. - pub fn set_busy_state(&self, msg: Option) -> Result<(), Error> { + /// `msg` - the text to show + /// + /// This method implements the latest recommendation of panicing on internal errors. + pub fn set_status_text(&self, msg: &str) { let bm = BusyMessage { - busy_msg: match msg { - None => None, - Some(m) => { - Some( - xous_ipc::String::from_str(&m) - ) - } - } + busy_msg: xous_ipc::String::from_str(msg) }; - match Buffer::into_buf(bm) { - Ok(buf) => match buf.send(self.cid, ChatOp::SetBusyAnimationState as u32) { - Ok(..) => { - Ok(()) - } - Err(_) => Err(xous::Error::InternalError), - }, - Err(_) => Err(xous::Error::InternalError), - } + Buffer::into_buf(bm).expect("internal error").send( + self.cid, ChatOp::SetStatusText as u32 + ).expect("internal error"); + } + + pub fn set_busy_state(&self, run: bool) { + xous::send_message( + self.cid, + xous::Message::new_scalar(ChatOp::SetBusyAnimationState as usize, + if run { 1 } else { 0 }, + 0, 0, 0), + ) + .map(|_| ()) + .expect("internal error"); } } @@ -299,6 +298,7 @@ pub fn busy_animator( ChatOp::UpdateBusy as usize, 0, 0, 0, 0) ).ok(); tt.sleep_ms(crate::BUSY_ANIMATION_RATE_MS).unwrap(); + log::info!("busy!"); xous::try_send_message(busy_bumper_cid, xous::Message::new_scalar( BusyAnimOp::Pump as usize, 0, 0, 0, 0) @@ -346,37 +346,32 @@ pub fn server( loop { let msg = xous::receive_message(sid).unwrap(); log::debug!("got message {:?}", msg); - if ui.is_busy() { - if !run_busy_animation.swap(true, Ordering::SeqCst) { - // only send off the Pump request on the transition from false->true; this causes the machine to run - xous::try_send_message(busy_bumper_cid, - xous::Message::new_scalar( - BusyAnimOp::Pump as usize, 0, 0, 0, 0) - ).ok(); - } - } else { - // make sure the animation stops running. Not sure if this is the most efficient way to handle this, - // but I think an atomic bool set is just a couple dozen CPU cycles...? - run_busy_animation.store(false, Ordering::SeqCst); - } match FromPrimitive::from_usize(msg.body.id()) { Some(ChatOp::UpdateBusy) => { ui.redraw_busy().expect("CHAT couldn't redraw"); } - Some(ChatOp::SetBusyAnimationState) => { + Some(ChatOp::SetStatusText) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let s = buffer.to_original::().unwrap(); - match s.busy_msg { - Some(msg) => { - ui.set_busy(msg.as_str().unwrap()); - } - None => { - ui.clear_busy(); - } - } + ui.set_status_text(s.busy_msg.as_str().unwrap()); } + Some(ChatOp::SetBusyAnimationState) => msg_scalar_unpack!(msg, state, _, _, _, { + if state != 0 { + ui.set_busy_state(true); + if !run_busy_animation.swap(true, Ordering::SeqCst) { + // only send off the Pump request on the transition from false->true; this causes the machine to run + xous::try_send_message(busy_bumper_cid, + xous::Message::new_scalar( + BusyAnimOp::Pump as usize, 0, 0, 0, 0) + ).ok(); + } + } else { + ui.set_busy_state(false); + run_busy_animation.store(false, Ordering::SeqCst) + } + }), Some(ChatOp::DialogueSave) => { log::info!("ChatOp::DialogueSave"); ui.dialogue_save().expect("failed to save Dialogue"); diff --git a/libs/chat/src/ui.rs b/libs/chat/src/ui.rs index 9e37365aa..4cd883036 100644 --- a/libs/chat/src/ui.rs +++ b/libs/chat/src/ui.rs @@ -64,8 +64,6 @@ pub(crate) struct Ui { status_tv: TextView, /// track the last time we update the status bar; use this avoid double-updating busy animations status_last_update_ms: u64, - /// track the last non-busy message so we can restore it when the busy state stops - status_last_msg: Option, bubble_width: u16, margin: Point, // margin to edge of canvas bubble_margin: Point, // margin of text in bubbles @@ -163,7 +161,6 @@ impl Ui { status_height, status_tv, status_last_update_ms, - status_last_msg: None, post_selected: None, post_anchor: None, post_topdown: false, @@ -642,16 +639,8 @@ impl Ui { self.status_tv.busy_animation_state.is_some() } - /// If not currently busy, save the current status bar message and kick off the animation. - /// Updates the text of the status bar in all cases. - pub(crate) fn set_busy(&mut self, msg: &str) { - if self.status_tv.busy_animation_state.is_none() { - // stash a copy of the last message that wasn't a busy message - self.status_last_msg = Some( - self.status_tv.to_str().to_owned() - ); - self.status_tv.busy_animation_state = Some(0); - } + /// Set the status bar text + pub(crate) fn set_status_text(&mut self, msg: &str) { self.status_tv.clear_str(); write!(self.status_tv, "{}", msg).ok(); xous::send_message(self.app_cid.unwrap(), @@ -659,13 +648,12 @@ impl Ui { ChatOp::UpdateBusy as usize, 0, 0, 0, 0) ).ok(); } - - /// Stops the busy animation state - pub(crate) fn clear_busy(&mut self) { - self.status_tv.busy_animation_state = None; - if let Some(prev_msg) = self.status_last_msg.take() { - self.status_tv.clear_str(); - write!(self.status_tv, "{}", prev_msg).ok(); + /// Sets the status bar to animate the busy animation + pub(crate) fn set_busy_state(&mut self, run: bool) { + if run { + self.status_tv.busy_animation_state = Some(0); // the "glitch" to 0 is intentional, gives an indicator that a new op has started + } else { + self.status_tv.busy_animation_state = None; } } From 44233390590c66e0d28f2a06f14e383f98dc4940 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 29 Oct 2023 16:33:03 +0800 Subject: [PATCH 10/16] move wifi delay hook to the correct area - remove modal pop-up for wifi connection, and replace with busy animation - specify units of delay in the constants (_MS to indicate milliseconds; this is a convention I'm trying to adhere to) - partial progress on debugging why the animation isn't running (value of animation variable is not being passed back at the GAM layer). Also a general note on coding styles that probably is going to cause confusion now that more people are contributing to the code base. Generally, when a lot of "generic" library functions fail, we've been passing an error message up the stack. However, these functions are actually meant to be infalliable, and when you kick the error up the stack you just end up with a panic at an unhelpful location (because you finally catch the error only at the main loop or something and by that point there's nothing you can really do about it but panic, since it's supposed to be an infalliable operation). As a result I have been trying to tamp down on needless error propagations and having them fail with a unwrap or expect at the point where the abstraction should be infalliable. This helps in debugging the actual failure root cause because you're closer to the line of code that actually broke, instead of just some line at a generic error handler. Of course if you build with stack unwinding the top-level unwraps are more useful because you can peer down into the call chain, but even then, with the limited screen real estate I think deeply nested failures would probably overflow any panic display. So even with panic unwinding I think we stil want to keep the root cause within a few stack frames, instead of errors being passed up sixteen levels of abstraction before finally dying. This only applies to things that are meant to be truly infalliable, like syscalls that should not fail, or like unpacking a buffer or memory message that has already been allocated. In this case the errors are more like asserts, and are helpful if they fail at the line where they break instead of being passed up the call stack (which was the original architecture). Probably I should add a note about this to the Xous Book. --- apps/mtxchat/locales/i18n.json | 4 ++++ apps/mtxchat/src/lib.rs | 29 +++++++++++++++-------------- apps/mtxchat/src/listen.rs | 6 +++--- libs/chat/src/ui.rs | 3 ++- services/gam/src/lib.rs | 1 + 5 files changed, 25 insertions(+), 18 deletions(-) diff --git a/apps/mtxchat/locales/i18n.json b/apps/mtxchat/locales/i18n.json index 53ba2621a..d5d3edfea 100644 --- a/apps/mtxchat/locales/i18n.json +++ b/apps/mtxchat/locales/i18n.json @@ -241,6 +241,10 @@ "ja": "WiFi not connected. Entering read-only mode *EN*", "zh": "WiFi not connected. Entering read-only mode *EN*" }, + "mtxchat.wifi.warning_status": { + "en": "No connection! Read-only.", + "en-tts": "No connection! Read-only." + }, "mtxchat.listen.patience": { "en": "It takes a while to get new events from the [matrix] server.\nPlease be patient :-)", "en-tts": "It takes a while to get new events from the [matrix] server.\nPlease be patient." diff --git a/apps/mtxchat/src/lib.rs b/apps/mtxchat/src/lib.rs index 35e18b256..3bf47b132 100644 --- a/apps/mtxchat/src/lib.rs +++ b/apps/mtxchat/src/lib.rs @@ -9,6 +9,7 @@ use listen::listen; use locales::t; use modals::Modals; use pddb::Pddb; +use ticktimer_server::Ticktimer; use std::fmt::Write as _; use std::io::{Error, ErrorKind, Read, Write as StdWrite}; use std::sync::Arc; @@ -35,8 +36,8 @@ const USER_DOMAIN_KEY: &str = "user_domain"; const DOMAIN_MATRIX: &str = "matrix.org"; -const MTX_LONG_TIMEOUT: i32 = 60000; // ms -const WIFI_TIMEOUT: u32 = 10; // seconds +const MTX_LONG_TIMEOUT_MS: i32 = 60000; // ms +const WIFI_TIMEOUT_MS: u32 = 30_000; // ms pub const CLOCK_NOT_SET_ID: usize = 1; pub const PDDB_NOT_MOUNTED_ID: usize = 2; @@ -84,6 +85,7 @@ pub struct MtxChat<'a> { new_username: bool, new_room: bool, status: String, + tt: Ticktimer, } impl<'a> MtxChat<'a> { pub fn new(chat: &Chat) -> MtxChat { @@ -117,6 +119,7 @@ impl<'a> MtxChat<'a> { new_username: false, new_room: false, status, + tt: ticktimer_server::Ticktimer::new().unwrap(), } } @@ -674,25 +677,23 @@ impl<'a> MtxChat<'a> { while self.wifi_try_modal() { self.netmgr.connection_manager_wifi_on_and_run().unwrap(); - self.modals - .start_progress("Connecting ...", 0, 10, 0) - .expect("no progress bar"); - let tt = ticktimer_server::Ticktimer::new().unwrap(); - for wait in 0..WIFI_TIMEOUT { - tt.sleep_ms(1000).unwrap(); - self.modals - .update_progress(wait) - .expect("no progress update"); + self.chat.set_status_text(t!("mtxchat.busy.connecting", locales::LANG)); + self.chat.set_busy_state(true); + let start = self.tt.elapsed_ms(); + while self.tt.elapsed_ms() - start < WIFI_TIMEOUT_MS as u64 { if let Some(conf) = self.netmgr.get_ipv4_config() { if conf.dhcp == com_rs::DhcpState::Bound { - self.modals - .finish_progress() - .expect("failed progress finish"); + self.chat.set_busy_state(false); + self.chat.set_status_text(&self.status); return true; } } + self.tt.sleep_ms(1000).unwrap(); } + self.modals.show_notification(t!("mtxchat.wifi.warning", locales::LANG), None).unwrap(); } + self.chat.set_busy_state(false); + self.chat.set_status_text(t!("mtxchat.wifi.warning_status", locales::LANG)); false } diff --git a/apps/mtxchat/src/listen.rs b/apps/mtxchat/src/listen.rs index 51bb325cf..c885d2438 100644 --- a/apps/mtxchat/src/listen.rs +++ b/apps/mtxchat/src/listen.rs @@ -1,4 +1,4 @@ -use crate::{get_username, web, MTX_LONG_TIMEOUT}; +use crate::{get_username, web, MTX_LONG_TIMEOUT_MS}; use chat::ChatOp; use modals::Modals; use std::sync::Arc; @@ -18,7 +18,7 @@ pub fn listen( ) { let xns = xous_names::XousNames::new().unwrap(); let modals = Modals::new(&xns).expect("can't connect to Modals server"); - log::info!("client_sync for {} ms...", MTX_LONG_TIMEOUT); + log::info!("client_sync for {} ms...", MTX_LONG_TIMEOUT_MS); let mut agent = ureq::builder() .tls_connector(Arc::new(TlsConnector{})) @@ -27,7 +27,7 @@ pub fn listen( url, filter, since, - MTX_LONG_TIMEOUT, + MTX_LONG_TIMEOUT_MS, &room_id, &token, &mut agent, diff --git a/libs/chat/src/ui.rs b/libs/chat/src/ui.rs index 4cd883036..6a822823e 100644 --- a/libs/chat/src/ui.rs +++ b/libs/chat/src/ui.rs @@ -21,7 +21,7 @@ use xous::{MessageEnvelope, CID}; use xous_names::XousNames; -pub const BUSY_ANIMATION_RATE_MS: usize = 50; +pub const BUSY_ANIMATION_RATE_MS: usize = 200; #[allow(dead_code)] pub(crate) struct Ui { @@ -627,6 +627,7 @@ impl Ui { pub(crate) fn redraw_busy(&mut self) -> Result<(), xous::Error> { let curtime = self.tt.elapsed_ms(); if curtime - self.status_last_update_ms > BUSY_ANIMATION_RATE_MS as u64 { + log::info!("update!"); self.gam.post_textview(&mut self.status_tv)?; self.gam.redraw().expect("couldn't redraw screen"); self.status_last_update_ms = curtime; diff --git a/services/gam/src/lib.rs b/services/gam/src/lib.rs index 9e351624c..550f68e8f 100644 --- a/services/gam/src/lib.rs +++ b/services/gam/src/lib.rs @@ -154,6 +154,7 @@ impl Gam { tv.bounds_computed = tvr.bounds_computed; tv.cursor = tvr.cursor; tv.overflow = tvr.overflow; + tv.busy_animation_state = tvr.busy_animation_state; } api::Return::NotCurrentlyDrawable => { tv.bounds_computed = None; From cdada997058f72e064b7764513aeece0cf83acc3 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 29 Oct 2023 19:14:57 +0800 Subject: [PATCH 11/16] miss copy-back of the animation state --- services/gam/src/main.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index bf0bd19c9..3e3d26fba 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -246,6 +246,7 @@ fn wrapped_main() -> ! { tv.cursor = tv_clone.cursor; tv.bounds_computed = tv_clone.bounds_computed; tv.overflow = tv_clone.overflow; + tv.busy_animation_state = tv_clone.busy_animation_state; let ret = api::Return::RenderReturn(tv); buffer.replace(ret).unwrap(); @@ -287,6 +288,7 @@ fn wrapped_main() -> ! { tv.cursor = tv_clone.cursor; tv.bounds_computed = tv_clone.bounds_computed; tv.overflow = tv_clone.overflow; + tv.busy_animation_state = tv_clone.busy_animation_state; let ret = api::Return::RenderReturn(tv); buffer.replace(ret).unwrap(); From 29fe24728c456f0d352b17f15d78757882e83ee6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 29 Oct 2023 19:15:11 +0800 Subject: [PATCH 12/16] add more wait states around long-run ops --- apps/mtxchat/locales/i18n.json | 16 ++++++++++++---- apps/mtxchat/src/lib.rs | 23 ++++++++++++++++++----- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/apps/mtxchat/locales/i18n.json b/apps/mtxchat/locales/i18n.json index d5d3edfea..304ecb736 100644 --- a/apps/mtxchat/locales/i18n.json +++ b/apps/mtxchat/locales/i18n.json @@ -11,6 +11,18 @@ "en": "Sending...", "en-tts": "Sending..." }, + "mtxchat.busy.room_id": { + "en": "Getting room ID...", + "en-tts": "Getting room ID..." + }, + "mtxchat.busy.login": { + "en": "Logging in...", + "en-tts": "Logging in..." + }, + "mtxchat.busy.new_listen": { + "en": "Syncing all events from server...", + "en-tts": "Syncing all events from server..." + }, "mtxchat.clock.warning": { "en": "WARNING: clock not set", "en-tts": "WARNING: clock not set", @@ -245,10 +257,6 @@ "en": "No connection! Read-only.", "en-tts": "No connection! Read-only." }, - "mtxchat.listen.patience": { - "en": "It takes a while to get new events from the [matrix] server.\nPlease be patient :-)", - "en-tts": "It takes a while to get new events from the [matrix] server.\nPlease be patient." - }, "mtxchat.close.item": { "en": "Close menu", "en-tts": "Close menu" diff --git a/apps/mtxchat/src/lib.rs b/apps/mtxchat/src/lib.rs index 3bf47b132..f537d3dce 100644 --- a/apps/mtxchat/src/lib.rs +++ b/apps/mtxchat/src/lib.rs @@ -38,6 +38,7 @@ const DOMAIN_MATRIX: &str = "matrix.org"; const MTX_LONG_TIMEOUT_MS: i32 = 60000; // ms const WIFI_TIMEOUT_MS: u32 = 30_000; // ms +const SEND_RETRIES: usize = 3; pub const CLOCK_NOT_SET_ID: usize = 1; pub const PDDB_NOT_MOUNTED_ID: usize = 2; @@ -255,9 +256,8 @@ impl<'a> MtxChat<'a> { self.listen(); if self.new_room { self.new_room = false; - self.modals - .show_notification(t!("mtxchat.listen.patience", locales::LANG), None) - .expect("notification failed"); + self.chat.set_status_text(t!("mtxchat.busy.new_listen", locales::LANG)); + self.chat.set_busy_state(true); } return true; } else { @@ -284,7 +284,7 @@ impl<'a> MtxChat<'a> { } pub fn login(&mut self) -> bool { - self.chat.set_status_text(t!("mtxchat.busy.connecting", locales::LANG)); + self.chat.set_status_text(t!("mtxchat.busy.login", locales::LANG)); self.chat.set_busy_state(true); self.token = self.get(TOKEN_KEY).unwrap_or(None); self.logged_in = false; @@ -444,12 +444,18 @@ impl<'a> MtxChat<'a> { (true, Some(token), Some(user_domain), Some(room_alias)) => { let mut url = Url::parse("https://matrix.org").unwrap(); url.set_host(Some(user_domain)).expect("failed to set host"); + self.chat.set_status_text(t!("mtxchat.busy.room_id", locales::LANG)); + self.chat.set_busy_state(true); if let Some(room_id) = web::get_room_id(&mut url, &room_alias, &token, &mut self.agent) { self.set_debug(ROOM_ID_KEY, &room_id); + self.chat.set_status_text(&self.status); + self.chat.set_busy_state(false); return Some(room_id); } else { + self.chat.set_status_text(&self.status); + self.chat.set_busy_state(false); "failed to get room_id" } } @@ -642,7 +648,14 @@ impl<'a> MtxChat<'a> { log::info!("txn_id = {}", txn_id); let mut url = Url::parse("https://matrix.org").unwrap(); url.set_host(Some(user_domain)).expect("failed to set host"); - let r = if web::send_message(&mut url, &room_id, &text, &txn_id, token, &mut self.agent) { + let mut success = false; + for _ in 0..SEND_RETRIES { + if web::send_message(&mut url, &room_id, &text, &txn_id, token, &mut self.agent) { + success = true; + break; + } + } + let r = if success { "SENT" } else { "FAILED TO SEND" From c3aa1f46cf9b7970d10c81c65c1813409edbd5c8 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 29 Oct 2023 20:06:57 +0800 Subject: [PATCH 13/16] use status bar to count receive events during listen --- apps/mtxchat/locales/i18n.json | 4 ++++ apps/mtxchat/src/listen.rs | 19 +++++++++---------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/apps/mtxchat/locales/i18n.json b/apps/mtxchat/locales/i18n.json index 304ecb736..2621fd2c9 100644 --- a/apps/mtxchat/locales/i18n.json +++ b/apps/mtxchat/locales/i18n.json @@ -19,6 +19,10 @@ "en": "Logging in...", "en-tts": "Logging in..." }, + "mtxchat.busy.rx_events": { + "en": "Receiving events...", + "en-tts": "Receiving events..." + }, "mtxchat.busy.new_listen": { "en": "Syncing all events from server...", "en-tts": "Syncing all events from server..." diff --git a/apps/mtxchat/src/listen.rs b/apps/mtxchat/src/listen.rs index c885d2438..4e4874919 100644 --- a/apps/mtxchat/src/listen.rs +++ b/apps/mtxchat/src/listen.rs @@ -1,11 +1,11 @@ use crate::{get_username, web, MTX_LONG_TIMEOUT_MS}; use chat::ChatOp; -use modals::Modals; use std::sync::Arc; use tls::xtls::TlsConnector; use url::Url; use xous::CID; use xous_ipc::Buffer; +use locales::t; pub fn listen( url: &mut Url, @@ -16,8 +16,6 @@ pub fn listen( dialogue_id: &str, chat_cid: CID, ) { - let xns = xous_names::XousNames::new().unwrap(); - let modals = Modals::new(&xns).expect("can't connect to Modals server"); log::info!("client_sync for {} ms...", MTX_LONG_TIMEOUT_MS); let mut agent = ureq::builder() @@ -38,9 +36,8 @@ pub fn listen( // TODO resolve suspected race condition // This progress modal is masking a bug by slowing the loop down // Precursor "Guru Mediation" `voilated: nonNull::new_unchecked` - modals - .start_progress("Receiving events ...", 0, events.len() as u32, 0) - .expect("no progress bar"); + chat::cf_set_status_text(chat_cid, t!("mtxchat.busy.rx_events", locales::LANG)); + chat::cf_set_busy_state(chat_cid, true); let mut event_count = 0; for event in events { let sender = event.sender.unwrap_or("anon".to_string()); @@ -58,12 +55,14 @@ pub fn listen( } .expect("failed to convert post into buffer"); event_count += 1; - modals - .update_progress(event_count) - .expect("no progress update"); + chat::cf_set_status_text(chat_cid, + &format!("{} {}", + t!("mtxchat.busy.rx_events", locales::LANG), + event_count) + ); } } - modals.finish_progress().expect("failed progress finish"); + chat::cf_set_busy_state(chat_cid, false); // trigger the chat ui to save the dialogue to the pddb xous::send_message( chat_cid, From d4a934785b7af09d2350719b5a22213450848ad1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 29 Oct 2023 20:07:22 +0800 Subject: [PATCH 14/16] re-introduce a default text to display when going out of busy state this simplifies the problem of tracking concurrency if multiple threads are requesting a busy-state to be presented. In this case, when the final thread leaves its busy state, the idle-state will be shown. --- apps/mtxchat/src/lib.rs | 7 ------- libs/chat/src/api.rs | 2 ++ libs/chat/src/lib.rs | 46 +++++++++++++++++++++++++++++++++++++++-- libs/chat/src/ui.rs | 20 +++++++++++++++--- 4 files changed, 63 insertions(+), 12 deletions(-) diff --git a/apps/mtxchat/src/lib.rs b/apps/mtxchat/src/lib.rs index f537d3dce..e2fdaa1a8 100644 --- a/apps/mtxchat/src/lib.rs +++ b/apps/mtxchat/src/lib.rs @@ -85,7 +85,6 @@ pub struct MtxChat<'a> { modals: Modals, new_username: bool, new_room: bool, - status: String, tt: Ticktimer, } impl<'a> MtxChat<'a> { @@ -119,7 +118,6 @@ impl<'a> MtxChat<'a> { modals: modals, new_username: false, new_room: false, - status, tt: ticktimer_server::Ticktimer::new().unwrap(), } } @@ -344,7 +342,6 @@ impl<'a> MtxChat<'a> { self.unset(USER_DOMAIN_KEY) .expect("failed to unset user domain"); } - self.chat.set_status_text(&self.status); self.chat.set_busy_state(false); self.logged_in } @@ -450,11 +447,9 @@ impl<'a> MtxChat<'a> { web::get_room_id(&mut url, &room_alias, &token, &mut self.agent) { self.set_debug(ROOM_ID_KEY, &room_id); - self.chat.set_status_text(&self.status); self.chat.set_busy_state(false); return Some(room_id); } else { - self.chat.set_status_text(&self.status); self.chat.set_busy_state(false); "failed to get room_id" } @@ -660,7 +655,6 @@ impl<'a> MtxChat<'a> { } else { "FAILED TO SEND" }; - self.chat.set_status_text(&self.status); self.chat.set_busy_state(false); r } @@ -697,7 +691,6 @@ impl<'a> MtxChat<'a> { if let Some(conf) = self.netmgr.get_ipv4_config() { if conf.dhcp == com_rs::DhcpState::Bound { self.chat.set_busy_state(false); - self.chat.set_status_text(&self.status); return true; } } diff --git a/libs/chat/src/api.rs b/libs/chat/src/api.rs index 091e04870..2a5765ce9 100644 --- a/libs/chat/src/api.rs +++ b/libs/chat/src/api.rs @@ -40,6 +40,8 @@ pub enum ChatOp { SetStatusText, /// Run or stop the busy animation. SetBusyAnimationState, + /// Set the status idle text (to be shown when exiting all busy states) + SetStatusIdleText, /// Update just the state of the busy animation, if any. Internal opcode. UpdateBusy, /// exit the application diff --git a/libs/chat/src/lib.rs b/libs/chat/src/lib.rs index a95272bab..65bba49ec 100644 --- a/libs/chat/src/lib.rs +++ b/libs/chat/src/lib.rs @@ -265,6 +265,20 @@ impl Chat { .map(|_| ()) .expect("internal error"); } + + /// Set status bar text when system is idle. + /// This is a convenience so we don't have to track the ins/outs of busy/idle state + /// and update the text, especially when we have multiple potential servers vying + /// to set a busy state. + pub fn set_status_idle_text(&self, msg: &str) { + let bm = BusyMessage { + busy_msg: xous_ipc::String::from_str(msg) + }; + Buffer::into_buf(bm).expect("internal error").send( + self.cid, ChatOp::SetStatusIdleText as u32 + ).expect("internal error"); + } + } /// Helper server that pumps the busy animation state until instructed to stop. @@ -298,7 +312,6 @@ pub fn busy_animator( ChatOp::UpdateBusy as usize, 0, 0, 0, 0) ).ok(); tt.sleep_ms(crate::BUSY_ANIMATION_RATE_MS).unwrap(); - log::info!("busy!"); xous::try_send_message(busy_bumper_cid, xous::Message::new_scalar( BusyAnimOp::Pump as usize, 0, 0, 0, 0) @@ -357,6 +370,13 @@ pub fn server( let s = buffer.to_original::().unwrap(); ui.set_status_text(s.busy_msg.as_str().unwrap()); } + Some(ChatOp::SetStatusIdleText) => { + let buffer = unsafe { + Buffer::from_memory_message(msg.body.memory_message().unwrap()) + }; + let s = buffer.to_original::().unwrap(); + ui.set_status_idle_text(s.busy_msg.as_str().unwrap()); + } Some(ChatOp::SetBusyAnimationState) => msg_scalar_unpack!(msg, state, _, _, _, { if state != 0 { ui.set_busy_state(true); @@ -368,8 +388,8 @@ pub fn server( ).ok(); } } else { + run_busy_animation.store(false, Ordering::SeqCst); ui.set_busy_state(false); - run_busy_animation.store(false, Ordering::SeqCst) } }), Some(ChatOp::DialogueSave) => { @@ -571,3 +591,25 @@ pub fn now() -> u64 { .try_into() .unwrap() } + +/// "context-free" (cf) communication with the chat object. +/// This is accomplished by making a copy of the connection to the chat server. +pub fn cf_set_status_text(chat_cid: xous::CID, msg: &str) { + let bm = BusyMessage { + busy_msg: xous_ipc::String::from_str(msg) + }; + Buffer::into_buf(bm).expect("internal error").send( + chat_cid, ChatOp::SetStatusText as u32 + ).expect("internal error"); +} + +pub fn cf_set_busy_state(chat_cid: xous::CID, run: bool) { + xous::send_message( + chat_cid, + xous::Message::new_scalar(ChatOp::SetBusyAnimationState as usize, + if run { 1 } else { 0 }, + 0, 0, 0), + ) + .map(|_| ()) + .expect("internal error"); +} \ No newline at end of file diff --git a/libs/chat/src/ui.rs b/libs/chat/src/ui.rs index 6a822823e..ddb5bfc24 100644 --- a/libs/chat/src/ui.rs +++ b/libs/chat/src/ui.rs @@ -62,8 +62,10 @@ pub(crate) struct Ui { status_height: u16, /// TextView for the status bar. This encapsulates the state of the busy animation, and the text within. status_tv: TextView, - /// track the last time we update the status bar; use this avoid double-updating busy animations + /// Track the last time we update the status bar; use this avoid double-updating busy animations status_last_update_ms: u64, + /// The default message to show when we exit a busy state + status_idle_text: String, bubble_width: u16, margin: Point, // margin to edge of canvas bubble_margin: Point, // margin of text in bubbles @@ -173,6 +175,7 @@ impl Ui { app_menu: app_menu.to_owned(), menu_mgr: menu_mgr, token: token, + status_idle_text: t!("chat.status.initial", locales::LANG).to_string(), } } @@ -627,7 +630,6 @@ impl Ui { pub(crate) fn redraw_busy(&mut self) -> Result<(), xous::Error> { let curtime = self.tt.elapsed_ms(); if curtime - self.status_last_update_ms > BUSY_ANIMATION_RATE_MS as u64 { - log::info!("update!"); self.gam.post_textview(&mut self.status_tv)?; self.gam.redraw().expect("couldn't redraw screen"); self.status_last_update_ms = curtime; @@ -654,9 +656,21 @@ impl Ui { if run { self.status_tv.busy_animation_state = Some(0); // the "glitch" to 0 is intentional, gives an indicator that a new op has started } else { - self.status_tv.busy_animation_state = None; + if self.status_tv.busy_animation_state.take().is_some() { + self.status_tv.clear_str(); + write!(self.status_tv, "{}", self.status_idle_text).ok(); + xous::send_message(self.app_cid.unwrap(), + xous::Message::new_scalar( + ChatOp::UpdateBusy as usize, 0, 0, 0, 0) + ).ok(); + } } } + /// Set the default idle text. Does *not* cause a redraw. If you need + /// an instant re-draw, call `set_status_text()` + pub(crate) fn set_status_idle_text(&mut self, msg: &str) { + self.status_idle_text = msg.to_owned(); + } /// Layout the post bubbles on the screen. /// From ae7ee770ee685677965ef4e38863559d8728a1c4 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 29 Oct 2023 23:02:44 +0800 Subject: [PATCH 15/16] expose the GAM minimum redraw period this could be useful for functions that have to rapidly toggle events on the screen and want to make sure that the last event actually is rendered. --- services/gam/src/lib.rs | 1 + services/gam/src/main.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/services/gam/src/lib.rs b/services/gam/src/lib.rs index 550f68e8f..a3cfd42f8 100644 --- a/services/gam/src/lib.rs +++ b/services/gam/src/lib.rs @@ -31,6 +31,7 @@ use ime_plugin_api::{ImefCallback, ApiToken}; #[doc = include_str!("../README.md")] +pub const RATE_LIMIT_MS: usize = 33; pub const SYSTEM_STYLE: GlyphStyle = GlyphStyle::Tall; // Add names here and insert them into the EXPECTED_BOOT_CONTEXTS structure below. diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index 3e3d26fba..9ced5ddb8 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -175,7 +175,7 @@ fn wrapped_main() -> ! { continue; // don't allow any redraws if a powerdown is requested } let elapsed_time = ticktimer.elapsed_ms(); - if elapsed_time - last_time > 33 { // rate limit updates, no point in going faster than the eye can see + if elapsed_time - last_time > gam::RATE_LIMIT_MS as u64 { // rate limit updates, no point in going faster than the eye can see last_time = elapsed_time; if deface(&gfx, &trng, &mut canvases) { From 5aefcac8ec52374292e4f0a0506081e2bd945339 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 29 Oct 2023 23:03:46 +0800 Subject: [PATCH 16/16] add forced redraw function, fix misdirected message - rapid redraws are normally aborted by this routine. offer a forced redraw in the case that a "final state" has to be rendered without fail. - fix a misdirected message (sending it to app instead of to ui by accident) --- libs/chat/locales/i18n.json | 4 ++-- libs/chat/src/api.rs | 3 +++ libs/chat/src/lib.rs | 3 +++ libs/chat/src/ui.rs | 19 ++++++++++++++++--- 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/libs/chat/locales/i18n.json b/libs/chat/locales/i18n.json index ede28f36f..bf1caf3a4 100644 --- a/libs/chat/locales/i18n.json +++ b/libs/chat/locales/i18n.json @@ -20,8 +20,8 @@ "en-tts": "no dialogues available to read" }, "chat.status.initial" : { - "en": "Idle", - "en-tts": "Idle" + "en": "Use ← to raise menu", + "en-tts": "Use ← to raise menu" }, "chat.help.navigation": { "en": "use ↑ & ↓ to scroll thru old posts\nuse ← & → to show menus\nF1-F4 dont do anything yet.", diff --git a/libs/chat/src/api.rs b/libs/chat/src/api.rs index 2a5765ce9..a41891705 100644 --- a/libs/chat/src/api.rs +++ b/libs/chat/src/api.rs @@ -43,7 +43,10 @@ pub enum ChatOp { /// Set the status idle text (to be shown when exiting all busy states) SetStatusIdleText, /// Update just the state of the busy animation, if any. Internal opcode. + /// Will skip the update if called too often. UpdateBusy, + /// Force update the busy bar, without rate throttling. Internal opcode. + UpdateBusyForced, /// exit the application Quit, } diff --git a/libs/chat/src/lib.rs b/libs/chat/src/lib.rs index 65bba49ec..52fc28563 100644 --- a/libs/chat/src/lib.rs +++ b/libs/chat/src/lib.rs @@ -363,6 +363,9 @@ pub fn server( Some(ChatOp::UpdateBusy) => { ui.redraw_busy().expect("CHAT couldn't redraw"); } + Some(ChatOp::UpdateBusyForced) => { + ui.redraw_status_forced().expect("CHAT couldn't redraw"); + } Some(ChatOp::SetStatusText) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) diff --git a/libs/chat/src/ui.rs b/libs/chat/src/ui.rs index ddb5bfc24..f564e425e 100644 --- a/libs/chat/src/ui.rs +++ b/libs/chat/src/ui.rs @@ -38,6 +38,8 @@ pub(crate) struct Ui { dialogue: Option, // Callbacks: + // callback to our own server + self_cid: CID, // optional SID of the "Owner" Chat App to receive UI-events app_cid: Option, // optional opcode ID to process UI-event msgs @@ -153,6 +155,7 @@ impl Ui { pddb_dict: None, pddb_key: None, dialogue: None, + self_cid: xous::connect(sid).unwrap(), app_cid, opcode_event, canvas, @@ -637,6 +640,15 @@ impl Ui { Ok(()) } + /// Update the status bar, without any throttling + pub(crate) fn redraw_status_forced(&mut self) -> Result<(), xous::Error> { + self.gam.post_textview(&mut self.status_tv)?; + self.gam.redraw().expect("couldn't redraw screen"); + let curtime = self.tt.elapsed_ms(); + self.status_last_update_ms = curtime; + Ok(()) + } + /// Returns `true` if the status bar is currently set for the busy animation pub(crate) fn is_busy(&self) -> bool { self.status_tv.busy_animation_state.is_some() @@ -646,7 +658,7 @@ impl Ui { pub(crate) fn set_status_text(&mut self, msg: &str) { self.status_tv.clear_str(); write!(self.status_tv, "{}", msg).ok(); - xous::send_message(self.app_cid.unwrap(), + xous::send_message(self.self_cid, xous::Message::new_scalar( ChatOp::UpdateBusy as usize, 0, 0, 0, 0) ).ok(); @@ -659,9 +671,10 @@ impl Ui { if self.status_tv.busy_animation_state.take().is_some() { self.status_tv.clear_str(); write!(self.status_tv, "{}", self.status_idle_text).ok(); - xous::send_message(self.app_cid.unwrap(), + // force the update, to ensure the idle state text is actually rendered + xous::send_message(self.self_cid, xous::Message::new_scalar( - ChatOp::UpdateBusy as usize, 0, 0, 0, 0) + ChatOp::UpdateBusyForced as usize, 0, 0, 0, 0) ).ok(); } }