From d3eb53ba89d868651d238aae2ec68b7018f380f5 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 14 Jan 2024 18:56:07 +0800 Subject: [PATCH] format apps/repl --- apps/repl/src/cmds.rs | 73 +++++++++----------- apps/repl/src/cmds/audio.rs | 63 ++++++++++------- apps/repl/src/repl.rs | 130 ++++++++++++++++++++---------------- 3 files changed, 143 insertions(+), 123 deletions(-) diff --git a/apps/repl/src/cmds.rs b/apps/repl/src/cmds.rs index 043febd27..d447e9fc5 100644 --- a/apps/repl/src/cmds.rs +++ b/apps/repl/src/cmds.rs @@ -1,15 +1,23 @@ -use xous::{MessageEnvelope}; -use xous_ipc::String; use core::fmt::Write; - use std::collections::HashMap; + +use xous::MessageEnvelope; +use xous_ipc::String; /////////////////////////// Common items to all commands pub trait ShellCmdApi<'a> { // user implemented: // called to process the command with the remainder of the string attached - fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error>; + fn process( + &mut self, + args: String<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error>; // called to process incoming messages that may have been origniated by the most recently issued command - fn callback(&mut self, msg: &MessageEnvelope, _env: &mut CommonEnv) -> Result>, xous::Error> { + fn callback( + &mut self, + msg: &MessageEnvelope, + _env: &mut CommonEnv, + ) -> Result>, xous::Error> { log::info!("received unhandled message {:?}", msg); Ok(None) } @@ -23,16 +31,8 @@ pub trait ShellCmdApi<'a> { // the argument to this macro is the command verb macro_rules! cmd_api { ($verb:expr) => { - fn verb(&self) -> &'static str { - stringify!($verb) - } - fn matches(&self, verb: &str) -> bool { - if verb == stringify!($verb) { - true - } else { - false - } - } + fn verb(&self) -> &'static str { stringify!($verb) } + fn matches(&self, verb: &str) -> bool { if verb == stringify!($verb) { true } else { false } } }; } @@ -46,12 +46,12 @@ pub struct CommonEnv { codec: codec::Codec, ticktimer: ticktimer_server::Ticktimer, gam: gam::Gam, - cb_registrations: HashMap::>, + cb_registrations: HashMap>, trng: Trng, xns: xous_names::XousNames, } impl CommonEnv { - pub fn register_handler(&mut self, verb: String::<256>) -> u32 { + pub fn register_handler(&mut self, verb: String<256>) -> u32 { let mut key: u32; loop { key = self.trng.get_u32().unwrap(); @@ -78,11 +78,12 @@ impl CommonEnv { */ ///// 1. add your module here, and pull its namespace into the local crate -mod audio; use audio::*; +mod audio; +use audio::*; pub struct CmdEnv { common_env: CommonEnv, - lastverb: String::<256>, + lastverb: String<256>, ///// 2. declare storage for your command here. audio_cmd: Audio, } @@ -109,10 +110,14 @@ impl CmdEnv { } } - pub fn dispatch(&mut self, maybe_cmdline: Option<&mut String::<1024>>, maybe_callback: Option<&MessageEnvelope>) -> Result>, xous::Error> { + pub fn dispatch( + &mut self, + maybe_cmdline: Option<&mut String<1024>>, + maybe_callback: Option<&MessageEnvelope>, + ) -> Result>, xous::Error> { let mut ret = String::<1024>::new(); - let commands: &mut [& mut dyn ShellCmdApi] = &mut [ + let commands: &mut [&mut dyn ShellCmdApi] = &mut [ ///// 4. add your command to this array, so that it can be looked up and dispatched &mut self.audio_cmd, ]; @@ -120,7 +125,7 @@ impl CmdEnv { if let Some(cmdline) = maybe_cmdline { let maybe_verb = tokenize(cmdline); - let mut cmd_ret: Result>, xous::Error> = Ok(None); + let mut cmd_ret: Result>, xous::Error> = Ok(None); if let Some(verb_string) = maybe_verb { let verb = verb_string.to_str(); @@ -155,15 +160,11 @@ impl CmdEnv { Ok(None) } } else if let Some(callback) = maybe_callback { - let mut cmd_ret: Result>, xous::Error> = Ok(None); + let mut cmd_ret: Result>, xous::Error> = Ok(None); // first check and see if we have a callback registration; if not, just map to the last verb let verb = match self.common_env.cb_registrations.get(&(callback.body.id() as u32)) { - Some(verb) => { - verb.to_str() - }, - None => { - self.lastverb.to_str() - } + Some(verb) => verb.to_str(), + None => self.lastverb.to_str(), }; // now dispatch let mut verbfound = false; @@ -174,11 +175,7 @@ impl CmdEnv { break; }; } - if verbfound { - cmd_ret - } else { - Ok(None) - } + if verbfound { cmd_ret } else { Ok(None) } } else { Ok(None) } @@ -188,7 +185,7 @@ impl CmdEnv { /// extract the first token, as delimited by spaces /// modifies the incoming line by removing the token and returning the remainder /// returns the found token -pub fn tokenize(line: &mut String::<1024>) -> Option> { +pub fn tokenize(line: &mut String<1024>) -> Option> { let mut token = String::<1024>::new(); let mut retline = String::<1024>::new(); @@ -211,9 +208,5 @@ pub fn tokenize(line: &mut String::<1024>) -> Option> { } line.clear(); write!(line, "{}", retline.as_str().unwrap()).unwrap(); - if token.len() > 0 { - Some(token) - } else { - None - } + if token.len() > 0 { Some(token) } else { None } } diff --git a/apps/repl/src/cmds/audio.rs b/apps/repl/src/cmds/audio.rs index cc8ae3ffb..056757307 100644 --- a/apps/repl/src/cmds/audio.rs +++ b/apps/repl/src/cmds/audio.rs @@ -1,9 +1,11 @@ -use crate::{ShellCmdApi,CommonEnv}; -use xous_ipc::String; -use xous::{MessageEnvelope, Message}; -use codec::*; use core::fmt::Write; + +use codec::*; use locales::t; +use xous::{Message, MessageEnvelope}; +use xous_ipc::String; + +use crate::{CommonEnv, ShellCmdApi}; #[derive(Debug)] pub struct Audio { @@ -16,13 +18,7 @@ pub struct Audio { impl Audio { pub fn new(xns: &xous_names::XousNames) -> Self { let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_REPL).unwrap(); - Audio { - callback_id: None, - callback_conn, - framecount: 0, - play_sample: 0.0, - freq: 440.0, - } + Audio { callback_id: None, callback_conn, framecount: 0, play_sample: 0.0, freq: 440.0 } } } @@ -51,7 +47,7 @@ fn simple_kilofloat_parse(input: &str) -> core::result::Result() // you can't create a ParseIntError any other way + return "z".parse::(); // you can't create a ParseIntError any other way } } Ok(result) @@ -64,7 +60,11 @@ fn simple_kilofloat_parse(input: &str) -> core::result::Result ShellCmdApi<'a> for Audio { cmd_api!(audio); - fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + args: String<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { let mut ret = String::<1024>::new(); let helpstring = t!("replapp.audio.help", locales::LANG); let mut tokens = args.as_str().unwrap().split(' '); @@ -114,7 +114,8 @@ impl<'a> ShellCmdApi<'a> for Audio { move || { let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); ticktimer.sleep_ms((duration * 1000.0) as usize).unwrap(); - xous::send_message(conn, Message::new_scalar(cb_id as usize, 0, 0, 0, STOP_ID)).unwrap(); + xous::send_message(conn, Message::new_scalar(cb_id as usize, 0, 0, 0, STOP_ID)) + .unwrap(); } }); write!(ret, "{}", t!("replapp.audio.start", locales::LANG)).unwrap(); @@ -123,16 +124,25 @@ impl<'a> ShellCmdApi<'a> for Audio { write!(ret, "{}", helpstring).unwrap(); } } - } Ok(Some(ret)) } - fn callback(&mut self, msg: &MessageEnvelope, env: &mut CommonEnv) -> Result>, xous::Error> { + fn callback( + &mut self, + msg: &MessageEnvelope, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { const AMPLITUDE: f32 = 0.8; match &msg.body { - Message::Scalar(xous::ScalarMessage{id: _, arg1: free_play, arg2: _avail_rec, arg3: _, arg4: routing_id}) => { + Message::Scalar(xous::ScalarMessage { + id: _, + arg1: free_play, + arg2: _avail_rec, + arg3: _, + arg4: routing_id, + }) => { if *routing_id == codec::AUDIO_CB_ROUTING_ID { let mut frames: FrameRing = FrameRing::new(); let frames_to_push = if frames.writeable_count() < *free_play { @@ -144,11 +154,14 @@ impl<'a> ShellCmdApi<'a> for Audio { log::debug!("f{} p{}", self.framecount, frames_to_push); for _ in 0..frames_to_push { - let mut frame: [u32; codec::FIFO_DEPTH] = [ZERO_PCM as u32 | (ZERO_PCM as u32) << 16; codec::FIFO_DEPTH]; + let mut frame: [u32; codec::FIFO_DEPTH] = + [ZERO_PCM as u32 | (ZERO_PCM as u32) << 16; codec::FIFO_DEPTH]; // put the "expensive" f32 comparison outside the cosine wave table computation loop let omega = self.freq * 2.0 * std::f32::consts::PI / SAMPLE_RATE_HZ; for sample in frame.iter_mut() { - let raw_sine: i16 = (AMPLITUDE * cos_table::cos( self.play_sample * omega ) * i16::MAX as f32) as i16; + let raw_sine: i16 = (AMPLITUDE + * cos_table::cos(self.play_sample * omega) + * i16::MAX as f32) as i16; let left = raw_sine as u16; let right = raw_sine as u16; *sample = right as u32 | (left as u32) << 16; @@ -156,26 +169,28 @@ impl<'a> ShellCmdApi<'a> for Audio { } frames.nq_frame(frame).unwrap(); - } env.codec.swap_frames(&mut frames).unwrap(); } else if *routing_id == STOP_ID { let mut ret = String::<1024>::new(); env.codec.abort().unwrap(); // this should stop callbacks from occurring too. - write!(ret, "{} {} {}.", + write!( + ret, + "{} {} {}.", t!("replapp.audio.completion_a", locales::LANG), self.framecount, t!("replapp.audio.completion_b", locales::LANG), - ).unwrap(); + ) + .unwrap(); self.framecount = 0; self.play_sample = 0.0; env.codec.power_off().unwrap(); return Ok(Some(ret)); } - }, + } Message::Move(_mm) => { log::error!("received memory message when not expected") - }, + } _ => { log::error!("received unknown callback type") } diff --git a/apps/repl/src/repl.rs b/apps/repl/src/repl.rs index cc0994967..ad80916fa 100644 --- a/apps/repl/src/repl.rs +++ b/apps/repl/src/repl.rs @@ -1,10 +1,12 @@ -use super::*; -use gam::UxRegistration; -use graphics_server::{Gid, Point, Rectangle, TextBounds, TextView, DrawStyle, PixelColor}; -use graphics_server::api::GlyphStyle; -use xous::MessageEnvelope; use core::fmt::Write; + +use gam::UxRegistration; +use graphics_server::api::GlyphStyle; +use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView}; use locales::t; +use xous::MessageEnvelope; + +use super::*; #[derive(Debug)] struct History { @@ -23,7 +25,7 @@ pub(crate) struct Repl { msg: Option, // record our input history - history: Vec::, + history: Vec, history_len: usize, content: Gid, gam: gam::Gam, @@ -31,7 +33,7 @@ pub(crate) struct Repl { // variables that define our graphical attributes screensize: Point, bubble_width: u16, - margin: Point, // margin to edge of canvas + margin: Point, // margin to edge of canvas bubble_margin: Point, // margin of text in bubbles bubble_radius: u16, bubble_space: i16, // spacing between text bubbles @@ -42,28 +44,36 @@ pub(crate) struct Repl { // our security token for making changes to our record on the GAM token: [u32; 4], } -impl Repl{ +impl Repl { pub(crate) fn new(xns: &xous_names::XousNames, sid: xous::SID) -> Self { let gam = gam::Gam::new(xns).expect("can't connect to GAM"); - let token = gam.register_ux(UxRegistration { - app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_REPL), - ux_type: gam::UxType::Chat, - predictor: Some(xous_ipc::String::<64>::from_str(ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL)), - listener: sid.to_array(), // note disclosure of our SID to the GAM -- the secret is now shared with the GAM! - redraw_id: ReplOp::Redraw.to_u32().unwrap(), - gotinput_id: Some(ReplOp::Line.to_u32().unwrap()), - audioframe_id: None, - rawkeys_id: None, - focuschange_id: Some(ReplOp::ChangeFocus.to_u32().unwrap()), - }).expect("couldn't register Ux context for repl"); + let token = gam + .register_ux(UxRegistration { + app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_REPL), + ux_type: gam::UxType::Chat, + predictor: Some(xous_ipc::String::<64>::from_str( + ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL, + )), + listener: sid.to_array(), /* note disclosure of our SID to the GAM -- the secret is now + * shared with the GAM! */ + redraw_id: ReplOp::Redraw.to_u32().unwrap(), + gotinput_id: Some(ReplOp::Line.to_u32().unwrap()), + audioframe_id: None, + rawkeys_id: None, + focuschange_id: Some(ReplOp::ChangeFocus.to_u32().unwrap()), + }) + .expect("couldn't register Ux context for repl"); let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas"); let screensize = gam.get_canvas_bounds(content).expect("couldn't get dimensions of content canvas"); Repl { input: None, msg: None, - history: vec![History{text: String::from(t!("replapp.greeting", locales::LANG)), is_input: false}], + history: vec![History { + text: String::from(t!("replapp.greeting", locales::LANG)), + is_input: false, + }], history_len: 10, content, gam, @@ -85,9 +95,7 @@ impl Repl{ Ok(()) } - pub(crate) fn msg(&mut self, message: MessageEnvelope) { - self.msg = Some(message); - } + pub(crate) fn msg(&mut self, message: MessageEnvelope) { self.msg = Some(message); } fn circular_push(&mut self, item: History) { if self.history.len() >= self.history_len { @@ -100,10 +108,7 @@ impl Repl{ pub(crate) fn update(&mut self, was_callback: bool) -> Result<(), xous::Error> { // if we had an input string, do something if let Some(local) = &self.input { - let input_history = History { - text: local.to_string(), - is_input: true, - }; + let input_history = History { text: local.to_string(), is_input: true }; self.circular_push(input_history); } @@ -112,28 +117,29 @@ impl Repl{ // side effect our commands // redraw UI once upon accepting all input - if !was_callback { // don't need to redraw on a callback, save some cycles + if !was_callback { + // don't need to redraw on a callback, save some cycles self.redraw().expect("can't redraw"); } let mut dirty = true; // take the input and pass it on to the various command parsers, and attach result if let Some(local) = &self.input { - if let Some(res) = self.env.dispatch(Some(&mut xous_ipc::String::<1024>::from_str(&local)), None).expect("command dispatch failed") { - let output_history = History { - text: String::from(res.as_str().unwrap_or("UTF-8 Error")), - is_input: false - }; + if let Some(res) = self + .env + .dispatch(Some(&mut xous_ipc::String::<1024>::from_str(&local)), None) + .expect("command dispatch failed") + { + let output_history = + History { text: String::from(res.as_str().unwrap_or("UTF-8 Error")), is_input: false }; self.circular_push(output_history); } else { dirty = false; } } else if let Some(msg) = &self.msg { if let Some(res) = self.env.dispatch(None, Some(msg)).expect("callback failed") { - let output_history = History { - text: String::from(res.as_str().unwrap_or("UTF-8 Error")), - is_input: false - }; + let output_history = + History { text: String::from(res.as_str().unwrap_or("UTF-8 Error")), is_input: false }; self.circular_push(output_history); } else { dirty = false; @@ -152,15 +158,18 @@ impl Repl{ } fn clear_area(&self) { - self.gam.draw_rectangle(self.content, - Rectangle::new_with_style(Point::new(0, 0), self.screensize, - DrawStyle { - fill_color: Some(PixelColor::Light), - stroke_color: None, - stroke_width: 0 - } - )).expect("can't clear content area"); + self.gam + .draw_rectangle( + self.content, + Rectangle::new_with_style( + Point::new(0, 0), + self.screensize, + DrawStyle { fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0 }, + ), + ) + .expect("can't clear content area"); } + pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> { self.clear_area(); @@ -170,18 +179,20 @@ impl Repl{ // iterator returns from oldest to newest // .rev() iterator is from newest to oldest for h in self.history.iter().rev() { - let mut bubble_tv = - if h.is_input { - TextView::new(self.content, + let mut bubble_tv = if h.is_input { + TextView::new( + self.content, TextBounds::GrowableFromBr( Point::new(self.screensize.x - self.margin.x, bubble_baseline), - self.bubble_width)) - } else { - TextView::new(self.content, - TextBounds::GrowableFromBl( - Point::new(self.margin.x, bubble_baseline), - self.bubble_width)) - }; + self.bubble_width, + ), + ) + } else { + TextView::new( + self.content, + TextBounds::GrowableFromBl(Point::new(self.margin.x, bubble_baseline), self.bubble_width), + ) + }; if h.is_input { bubble_tv.border_width = 1; } else { @@ -192,13 +203,14 @@ impl Repl{ bubble_tv.rounded_border = Some(self.bubble_radius); bubble_tv.style = GlyphStyle::Regular; bubble_tv.margin = self.bubble_margin; - bubble_tv.ellipsis = false; bubble_tv.insertion = None; + bubble_tv.ellipsis = false; + bubble_tv.insertion = None; write!(bubble_tv.text, "{}", h.text.as_str()).expect("couldn't write history text to TextView"); self.gam.post_textview(&mut bubble_tv).expect("couldn't render bubble textview"); if let Some(bounds) = bubble_tv.bounds_computed { - // we only subtract 1x of the margin because the bounds were computed from a "bottom right" that already counted - // the margin once. + // we only subtract 1x of the margin because the bounds were computed from a "bottom right" + // that already counted the margin once. bubble_baseline -= (bounds.br.y - bounds.tl.y) + self.bubble_space + self.bubble_margin.y; if bubble_baseline <= 0 { // don't draw history that overflows the top of the screen @@ -212,4 +224,4 @@ impl Repl{ self.gam.redraw().expect("couldn't redraw screen"); Ok(()) } -} \ No newline at end of file +}