From 536ad89010b47c014e4dcd781c3f6a2bbc86ffc0 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 15 Jan 2024 00:46:06 +0800 Subject: [PATCH] format apps/mtxcli somehow, this was missed. --- apps/mtxcli/src/cmds.rs | 297 +++++++++--------- apps/mtxcli/src/cmds/get.rs | 42 +-- apps/mtxcli/src/cmds/heap.rs | 20 +- apps/mtxcli/src/cmds/help.rs | 86 +++-- apps/mtxcli/src/cmds/login.rs | 17 +- apps/mtxcli/src/cmds/logout.rs | 17 +- apps/mtxcli/src/cmds/migrations.rs | 39 +-- .../src/cmds/migrations/v0_9_11_0120.rs | 10 +- apps/mtxcli/src/cmds/set.rs | 38 +-- apps/mtxcli/src/cmds/status.rs | 19 +- apps/mtxcli/src/cmds/unset.rs | 22 +- apps/mtxcli/src/cmds/url.rs | 15 +- apps/mtxcli/src/cmds/web.rs | 103 ++---- apps/mtxcli/src/main.rs | 16 +- apps/mtxcli/src/mtxcli.rs | 126 ++++---- 15 files changed, 413 insertions(+), 454 deletions(-) diff --git a/apps/mtxcli/src/cmds.rs b/apps/mtxcli/src/cmds.rs index 55ee56628..b872ab436 100644 --- a/apps/mtxcli/src/cmds.rs +++ b/apps/mtxcli/src/cmds.rs @@ -1,15 +1,16 @@ -use xous::{MessageEnvelope, Message,StringBuffer}; -use xous_ipc::String as XousString; use core::fmt::Write; - +use core::str::FromStr; use std::collections::HashMap; use std::fs::File; -use std::io::{Read, Write as StdWrite, Error, ErrorKind}; +use std::io::{Error, ErrorKind, Read, Write as StdWrite}; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; // to help gen_txn_id -use core::str::FromStr; -mod migrations; use migrations::run_migrations; +use xous::{Message, MessageEnvelope, StringBuffer}; +use xous_ipc::String as XousString; + +mod migrations; +use migrations::run_migrations; mod url; mod web; @@ -69,12 +70,11 @@ fn get_version(ticktimer: &ticktimer_server::Ticktimer) -> String { let v: Vec<&str> = xous_version.split('-').collect(); if v.len() > 2 { let n = v[1].parse::().expect("could not parse version"); - let version = format!("{}-{:04}",v[0], n); + let version = format!("{}-{:04}", v[0], n); log::info!("version={}=", version); version } else { - log::info!("ERROR, couldn't find version from xous_version: {}", - xous_version); + log::info!("ERROR, couldn't find version from xous_version: {}", xous_version); xous_version } } @@ -83,9 +83,17 @@ fn get_version(ticktimer: &ticktimer_server::Ticktimer) -> String { pub trait ShellCmdApi<'a> { // user implemented: // called to process the command with the remainder of the string attached - fn process(&mut self, args: XousString::<1024>, env: &mut CommonEnv) -> Result>, xous::Error>; + fn process( + &mut self, + args: XousString<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) } @@ -99,16 +107,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 } } }; } @@ -117,7 +117,7 @@ use trng::*; #[derive(Debug)] pub struct CommonEnv { ticktimer: ticktimer_server::Ticktimer, - cb_registrations: HashMap::>, + cb_registrations: HashMap>, async_msg_callback_id: u32, async_msg_conn: u32, trng: Trng, @@ -139,8 +139,7 @@ pub struct CommonEnv { } impl CommonEnv { pub fn new() -> CommonEnv { - let ticktimer = ticktimer_server::Ticktimer::new() - .expect("Couldn't connect to Ticktimer"); + let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); let cb_registrations = HashMap::new(); let async_msg_callback_id: u32 = 0; let async_msg_conn: u32 = 0; @@ -172,7 +171,7 @@ impl CommonEnv { common } - pub fn register_handler(&mut self, verb: XousString::<256>) -> u32 { + pub fn register_handler(&mut self, verb: XousString<256>) -> u32 { let mut key: u32; loop { key = self.trng.get_u32().unwrap(); @@ -193,31 +192,25 @@ impl CommonEnv { } pub fn scalar_async_msg(&self, async_msg_id: usize) { - let msg = Message::new_scalar(self.async_msg_callback_id as usize, - 0, 0, 0, async_msg_id); + let msg = Message::new_scalar(self.async_msg_callback_id as usize, 0, 0, 0, async_msg_id); xous::send_message(self.async_msg_conn, msg).unwrap(); } pub fn send_async_msg(&self, async_msg: &str) { - let str_buf = StringBuffer::from_str(async_msg) - .expect("unable to create string message"); - str_buf.send(self.async_msg_conn, self.async_msg_callback_id) - .expect("unable to send string message"); + let str_buf = StringBuffer::from_str(async_msg).expect("unable to create string message"); + str_buf.send(self.async_msg_conn, self.async_msg_callback_id).expect("unable to send string message"); } pub fn gen_txn_id(&mut self) -> String { - let mut txn_id = self.trng.get_u32() - .expect("unable to generate random u32"); + let mut txn_id = self.trng.get_u32().expect("unable to generate random u32"); log::info!("trng.get_u32() = {}", txn_id); - txn_id += SystemTime::now().duration_since(UNIX_EPOCH) - .expect("Time went backwards").subsec_nanos(); + txn_id += SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards").subsec_nanos(); txn_id.to_string() } pub fn set(&mut self, key: &str, value: &str) -> Result<(), Error> { if key.starts_with("__") { - Err(Error::new(ErrorKind::PermissionDenied, - "may not set a variable beginning with __ ")) + Err(Error::new(ErrorKind::PermissionDenied, "may not set a variable beginning with __ ")) } else { log::info!("set '{}' = '{}'", key, value); let mut keypath = PathBuf::new(); @@ -230,16 +223,33 @@ impl CommonEnv { } keypath.push(key); File::create(keypath)?.write_all(value.as_bytes())?; - match key { // special case side effects - FILTER_KEY => { self.filter = value.to_string(); } - PASSWORD_KEY => { self.set_password(); } - ROOM_ID_KEY => { self.room_id = value.to_string(); } - ROOM_KEY => { self.set_room(); } - SERVER_KEY => { self.server = value.to_string(); } - SINCE_KEY => { self.since = value.to_string(); } - USERNAME_KEY => { self.username = value.to_string(); } - USER_KEY => { self.set_user(value); } - _ => { } + match key { + // special case side effects + FILTER_KEY => { + self.filter = value.to_string(); + } + PASSWORD_KEY => { + self.set_password(); + } + ROOM_ID_KEY => { + self.room_id = value.to_string(); + } + ROOM_KEY => { + self.set_room(); + } + SERVER_KEY => { + self.server = value.to_string(); + } + SINCE_KEY => { + self.since = value.to_string(); + } + USERNAME_KEY => { + self.username = value.to_string(); + } + USER_KEY => { + self.set_user(value); + } + _ => {} } Ok(()) } @@ -248,9 +258,7 @@ impl CommonEnv { // will log on error (vs. panic) pub fn set_debug(&mut self, key: &str, value: &str) -> bool { match self.set(key, value) { - Ok(()) => { - true - }, + Ok(()) => true, Err(e) => { log::info!("error setting key {}: {:?}", key, e); false @@ -261,12 +269,12 @@ impl CommonEnv { pub fn set_user(&mut self, value: &str) { log::info!("# USER_KEY set '{}' = '{}'", USER_KEY, value); let i = match value.find('@') { - Some(index) => { index + 1 }, - None => { 0 }, + Some(index) => index + 1, + None => 0, }; let j = match value.find(':') { - Some(index) => { index }, - None => { value.len() }, + Some(index) => index, + None => value.len(), }; self.username = (&value[i..j]).to_string(); if j < value.len() { @@ -296,8 +304,7 @@ impl CommonEnv { pub fn unset(&mut self, key: &str) -> Result<(), Error> { if key.starts_with("__") { - Err(Error::new(ErrorKind::PermissionDenied, - "may not unset a variable beginning with __ ")) + Err(Error::new(ErrorKind::PermissionDenied, "may not unset a variable beginning with __ ")) } else { log::info!("unset '{}'", key); let mut keypath = PathBuf::new(); @@ -309,18 +316,32 @@ impl CommonEnv { std::fs::create_dir_all(&keypath)?; } keypath.push(key); - if std::fs::metadata(&keypath).is_ok() { // keypath exists + if std::fs::metadata(&keypath).is_ok() { + // keypath exists log::info!("dict:key = '{}:{}' exists.. deleting it", MTXCLI_DICT, key); std::fs::remove_file(keypath)?; } - match key { // special case side effects -- update cached values - FILTER_KEY => { self.filter = EMPTY.to_string(); } - ROOM_ID_KEY => { self.room_id = EMPTY.to_string(); } - SINCE_KEY => { self.since = EMPTY.to_string(); } - SERVER_KEY => { self.server = EMPTY.to_string(); } - USER_KEY => { self.user = EMPTY.to_string(); } - USERNAME_KEY => { self.username = EMPTY.to_string(); } - _ => { } + match key { + // special case side effects -- update cached values + FILTER_KEY => { + self.filter = EMPTY.to_string(); + } + ROOM_ID_KEY => { + self.room_id = EMPTY.to_string(); + } + SINCE_KEY => { + self.since = EMPTY.to_string(); + } + SERVER_KEY => { + self.server = EMPTY.to_string(); + } + USER_KEY => { + self.user = EMPTY.to_string(); + } + USERNAME_KEY => { + self.username = EMPTY.to_string(); + } + _ => {} } Ok(()) } @@ -329,9 +350,7 @@ impl CommonEnv { // will log on error (vs. panic) pub fn unset_debug(&mut self, key: &str) -> bool { match self.unset(key) { - Ok(()) => { - true - }, + Ok(()) => true, Err(e) => { log::info!("error unsetting key {}: {:?}", key, e); false @@ -352,7 +371,7 @@ impl CommonEnv { std::fs::create_dir_all(&keypath)?; } keypath.push(key); - if let Ok(mut file)= File::open(keypath) { + if let Ok(mut file) = File::open(keypath) { let mut value = String::new(); file.read_to_string(&mut value)?; log::info!("get '{}' = '{}'", key, value); @@ -365,12 +384,8 @@ impl CommonEnv { pub fn get_default(&mut self, key: &str, default: &str) -> String { match self.get(key) { - Ok(None) => { - default.to_string() - }, - Ok(Some(value)) => { - value.to_string() - } + Ok(None) => default.to_string(), + Ok(Some(value)) => value.to_string(), Err(e) => { log::info!("error getting key {}: {:?}", key, e); default.to_string() @@ -379,18 +394,18 @@ impl CommonEnv { } pub fn user_says(&mut self, text: &str) { - if ! self.logged_in { - if ! self.login() { + if !self.logged_in { + if !self.login() { return; } } if self.room_id.len() == 0 { - if ! self.get_room_id() { + if !self.get_room_id() { return; } } if self.filter.len() == 0 { - if ! self.get_filter() { + if !self.get_filter() { return; } } @@ -413,7 +428,7 @@ impl CommonEnv { self.logged_in = true; } } - if ! self.logged_in { + if !self.logged_in { if web::get_login_type(&self.server) { let user = self.get_default(USER_KEY, USER_KEY); if user.len() == 0 { @@ -427,7 +442,7 @@ impl CommonEnv { self.set_debug(TOKEN_KEY, &new_token); self.logged_in = true; } else { - log::info!("Error: cannnot login with type: {}", web::MTX_LOGIN_PASSWORD); + log::info!("Error: cannnot login with type: {}", web::MTX_LOGIN_PASSWORD); } } } @@ -461,18 +476,14 @@ impl CommonEnv { false } else { let mut room_server = String::new(); - if ! room.starts_with("#") { + if !room.starts_with("#") { room_server.push_str("#"); } room_server.push_str(&room); room_server.push_str(":"); let i = match server.find(HTTPS) { - Some(index) => { - index + HTTPS.len() - }, - None => { - server.len() - }, + Some(index) => index + HTTPS.len(), + None => server.len(), }; if i >= server.len() { self.scalar_async_msg(SET_SERVER_ID); @@ -496,8 +507,7 @@ impl CommonEnv { if self.filter.len() > 0 { true } else { - if let Some(new_filter) = web::get_filter(&self.user, &self.server, - &self.room_id, &self.token) { + if let Some(new_filter) = web::get_filter(&self.user, &self.server, &self.room_id, &self.token) { self.set_debug(FILTER_KEY, &new_filter); true } else { @@ -512,17 +522,17 @@ impl CommonEnv { log::info!("Already listening"); return; } - if ! self.logged_in { + if !self.logged_in { log::info!("Not logged in"); return; } if self.room_id.len() == 0 { - if ! self.get_room_id() { + if !self.get_room_id() { return; } } if self.filter.len() == 0 { - if ! self.get_filter() { + if !self.get_filter() { return; } } @@ -540,16 +550,16 @@ impl CommonEnv { // log::info!("client_sync for {} ms...", MTX_LONG_TIMEOUT); let mut response = String::new(); response.push(SENTINEL); - if let Some((since, messages)) = web::client_sync(&server, &filter, &since, MTX_LONG_TIMEOUT, &room_id, &token) { + if let Some((since, messages)) = + web::client_sync(&server, &filter, &since, MTX_LONG_TIMEOUT, &room_id, &token) + { response.push_str(&since); response.push(SENTINEL); response.push_str(&messages); response.push(SENTINEL); } - let str_buf = StringBuffer::from_str(&response) - .expect("unable to create string message"); - str_buf.send(async_msg_conn, async_msg_callback_id) - .expect("unable to send string message"); + let str_buf = StringBuffer::from_str(&response).expect("unable to create string message"); + str_buf.send(async_msg_conn, async_msg_callback_id).expect("unable to send string message"); } }); } @@ -580,18 +590,26 @@ impl CommonEnv { */ ///// 1. add your module here, and pull its namespace into the local crate -mod get; use get::*; -mod heap; use heap::*; -mod help; use help::*; -mod login; use login::*; -mod logout; use logout::*; -mod set; use set::*; -mod status; use status::*; -mod unset; use unset::*; +mod get; +use get::*; +mod heap; +use heap::*; +mod help; +use help::*; +mod login; +use login::*; +mod logout; +use logout::*; +mod set; +use set::*; +mod status; +use status::*; +mod unset; +use unset::*; pub struct CmdEnv { common_env: CommonEnv, - lastverb: XousString::<256>, + lastverb: XousString<256>, ///// 2. declare storage for your command here. get_cmd: Get, heap_cmd: Heap, @@ -621,11 +639,15 @@ impl CmdEnv { } } - pub fn dispatch(&mut self, maybe_cmdline: Option<&mut XousString::<1024>>, maybe_callback: Option<&MessageEnvelope>) -> Result>, xous::Error> { + pub fn dispatch( + &mut self, + maybe_cmdline: Option<&mut XousString<1024>>, + maybe_callback: Option<&MessageEnvelope>, + ) -> Result>, xous::Error> { let mut ret = XousString::<1024>::new(); self.common_env.first_line = true; - 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.get_cmd, &mut self.heap_cmd, @@ -645,7 +667,7 @@ impl CmdEnv { } } if self.common_env.wifi_connected != prev_wifi_connected { - if self.common_env.wifi_connected { + if self.common_env.wifi_connected { self.common_env.scalar_async_msg(WIFI_CONNECTED_ID); } else { self.common_env.scalar_async_msg(WIFI_NOT_CONNECTED_ID); @@ -653,17 +675,17 @@ impl CmdEnv { } if let Some(cmdline) = maybe_cmdline { - if ! self.common_env.initialized { + if !self.common_env.initialized { log::info!("initializing"); log::info!("WiFi connected: {}", self.common_env.wifi_connected); if clock_not_set() { self.common_env.scalar_async_msg(CLOCK_NOT_SET_ID); } - if ! self.common_env.wifi_connected && ! prev_wifi_connected { + if !self.common_env.wifi_connected && !prev_wifi_connected { self.common_env.scalar_async_msg(WIFI_NOT_CONNECTED_ID); } let pddb = pddb::PddbMountPoller::new(); - if ! pddb.is_mounted_nonblocking() { + if !pddb.is_mounted_nonblocking() { self.common_env.scalar_async_msg(PDDB_NOT_MOUNTED_ID); } else { log::info!("PDDB is mounted"); @@ -685,16 +707,17 @@ impl CmdEnv { } } - if ! self.common_env.listening && - self.common_env.logged_in && - (HOSTED_MODE || self.common_env.wifi_connected) && - self.common_env.initialized { + if !self.common_env.listening + && self.common_env.logged_in + && (HOSTED_MODE || self.common_env.wifi_connected) + && self.common_env.initialized + { self.common_env.listen(); } 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(); @@ -729,7 +752,8 @@ impl CmdEnv { } else { cmd_ret } - } else { // chat + } else { + // chat let mut text = String::from(verb); text.push_str(" "); text.push_str(cmdline.to_str()); @@ -742,15 +766,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; @@ -761,22 +781,17 @@ impl CmdEnv { break; }; } - if verbfound { - cmd_ret - } else { - Ok(None) - } + if verbfound { cmd_ret } else { Ok(None) } } else { Ok(None) } } } - /// 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 XousString::<1024>) -> Option> { +pub fn tokenize(line: &mut XousString<1024>) -> Option> { let mut token = XousString::<1024>::new(); let mut retline = XousString::<1024>::new(); @@ -799,15 +814,13 @@ pub fn tokenize(line: &mut XousString::<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 } } pub(crate) fn heap_usage() -> usize { - match xous::rsyscall(xous::SysCall::IncreaseHeap(0, xous::MemoryFlags::R)).expect("couldn't get heap size") { + match xous::rsyscall(xous::SysCall::IncreaseHeap(0, xous::MemoryFlags::R)) + .expect("couldn't get heap size") + { xous::Result::MemoryRange(m) => { let usage = m.len(); usage @@ -815,15 +828,13 @@ pub(crate) fn heap_usage() -> usize { _ => { log::info!("Couldn't measure heap usage"); 0 - }, + } } } - pub fn clock_not_set() -> bool { let now = SystemTime::now(); - let since_the_epoch = now.duration_since(UNIX_EPOCH) - .expect("Time went backwards"); + let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards"); let seconds: u64 = since_the_epoch.as_secs(); if seconds < DATE_2023 { log::info!("clock NOT set, seconds since epoch: {}", seconds); diff --git a/apps/mtxcli/src/cmds/get.rs b/apps/mtxcli/src/cmds/get.rs index 3efa1e707..f4de4fb9f 100644 --- a/apps/mtxcli/src/cmds/get.rs +++ b/apps/mtxcli/src/cmds/get.rs @@ -1,22 +1,24 @@ -use crate::{ShellCmdApi,CommonEnv}; -use xous_ipc::String as XousString; use core::fmt::Write; + use locales::t; +use xous_ipc::String as XousString; + +use crate::{CommonEnv, ShellCmdApi}; #[derive(Debug)] -pub struct Get { -} +pub struct Get {} impl Get { - pub fn new() -> Self { - Get { - } - } + pub fn new() -> Self { Get {} } } impl<'a> ShellCmdApi<'a> for Get { cmd_api!(get); - fn process(&mut self, args: XousString::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + args: XousString<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { let mut ret = XousString::<1024>::new(); let mut tokens = args.as_str().unwrap().split(' '); @@ -25,19 +27,17 @@ impl<'a> ShellCmdApi<'a> for Get { "" => { write!(ret, "{}", t!("mtxcli.get.help", locales::LANG)).unwrap(); } - _ => { - match env.get(key) { - Ok(None) => { - write!(ret, "{} is UNSET", key).unwrap(); - }, - Ok(Some(value)) => { - write!(ret, "{}", value).unwrap(); - } - Err(e) => { - log::error!("error getting key {}: {:?}", key, e); - } + _ => match env.get(key) { + Ok(None) => { + write!(ret, "{} is UNSET", key).unwrap(); } - } + Ok(Some(value)) => { + write!(ret, "{}", value).unwrap(); + } + Err(e) => { + log::error!("error getting key {}: {:?}", key, e); + } + }, } } diff --git a/apps/mtxcli/src/cmds/heap.rs b/apps/mtxcli/src/cmds/heap.rs index 2a4f4c0f1..52f12cab1 100644 --- a/apps/mtxcli/src/cmds/heap.rs +++ b/apps/mtxcli/src/cmds/heap.rs @@ -1,21 +1,23 @@ -use crate::{ShellCmdApi,CommonEnv,heap_usage}; -use xous_ipc::String as XousString; use core::fmt::Write; +use xous_ipc::String as XousString; + +use crate::{heap_usage, CommonEnv, ShellCmdApi}; + #[derive(Debug)] -pub struct Heap { -} +pub struct Heap {} impl Heap { - pub fn new() -> Self { - Heap { - } - } + pub fn new() -> Self { Heap {} } } impl<'a> ShellCmdApi<'a> for Heap { cmd_api!(heap); - fn process(&mut self, _args: XousString::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + _args: XousString<1024>, + _env: &mut CommonEnv, + ) -> Result>, xous::Error> { let mut ret = XousString::<1024>::new(); let heap = heap_usage(); write!(ret, "heap usage: {}", heap).unwrap(); diff --git a/apps/mtxcli/src/cmds/help.rs b/apps/mtxcli/src/cmds/help.rs index 64fdc8242..293066920 100644 --- a/apps/mtxcli/src/cmds/help.rs +++ b/apps/mtxcli/src/cmds/help.rs @@ -1,33 +1,31 @@ -use crate::{ShellCmdApi, CommonEnv}; -use crate::cmds::*; -use xous::{MessageEnvelope, Message, StringBuffer}; -use xous_ipc::String as XousString; use core::fmt::Write; + use locales::t; +use xous::{Message, MessageEnvelope, StringBuffer}; +use xous_ipc::String as XousString; + +use crate::cmds::*; +use crate::{CommonEnv, ShellCmdApi}; #[derive(Debug)] -pub struct Help { -} +pub struct Help {} impl Help { - pub fn new() -> Self { - Help { - } - } + pub fn new() -> Self { Help {} } } impl<'a> ShellCmdApi<'a> for Help { cmd_api!(help); - fn process(&mut self, args: XousString::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + args: XousString<1024>, + _env: &mut CommonEnv, + ) -> Result>, xous::Error> { let mut ret = XousString::<1024>::new(); let mut tokens = args.as_str().unwrap().split(' '); if let Some(slashcmd) = tokens.next() { - let cmd = if slashcmd.starts_with("/") { - &slashcmd[1..] - } else { - slashcmd - }; + let cmd = if slashcmd.starts_with("/") { &slashcmd[1..] } else { slashcmd }; match cmd { "get" => { write!(ret, "{}", t!("mtxcli.get.help", locales::LANG)).unwrap(); @@ -65,8 +63,7 @@ impl<'a> ShellCmdApi<'a> for Help { write!(ret, "{}", t!("mtxcli.unset.help", locales::LANG)).unwrap(); } _ => { - write!(ret, "{}: {}", - t!("mtxcli.unknown.help", locales::LANG), cmd).unwrap(); + write!(ret, "{}: {}", t!("mtxcli.unknown.help", locales::LANG), cmd).unwrap(); } } } @@ -74,74 +71,75 @@ impl<'a> ShellCmdApi<'a> for Help { } // NOTE: the help callback is used to process async messages - fn callback(&mut self, msg: &MessageEnvelope, env: &mut CommonEnv) -> Result>, xous::Error> { + fn callback( + &mut self, + msg: &MessageEnvelope, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { match &msg.body { - Message::Scalar(xous::ScalarMessage{id: _, arg1: _, arg2: _, - arg3: _, arg4: async_msg_id}) => { + Message::Scalar(xous::ScalarMessage { id: _, arg1: _, arg2: _, arg3: _, arg4: async_msg_id }) => { let mut ret = XousString::<1024>::new(); let warning = match *async_msg_id { CLOCK_NOT_SET_ID => { t!("mtxcli.clock.warning", locales::LANG) - }, + } PDDB_NOT_MOUNTED_ID => { t!("mtxcli.pddb.warning", locales::LANG) - }, + } WIFI_NOT_CONNECTED_ID => { t!("mtxcli.wifi.warning", locales::LANG) - }, + } MTXCLI_INITIALIZED_ID => { t!("mtxcli.initialized", locales::LANG) - }, + } WIFI_CONNECTED_ID => { t!("mtxcli.wifi.connected", locales::LANG) - }, + } SET_USER_ID => { t!("mtxcli.please.set.user", locales::LANG) - }, + } SET_PASSWORD_ID => { t!("mtxcli.please.set.password", locales::LANG) - }, + } LOGGED_IN_ID => { t!("mtxcli.logged.in", locales::LANG) - }, + } LOGIN_FAILED_ID => { t!("mtxcli.login.failed", locales::LANG) - }, + } SET_ROOM_ID => { t!("mtxcli.please.set.room", locales::LANG) - }, + } ROOMID_FAILED_ID => { t!("mtxcli.roomid.failed", locales::LANG) - }, + } FILTER_FAILED_ID => { t!("mtxcli.filter.failed", locales::LANG) - }, + } SET_SERVER_ID => { t!("mtxcli.please.set.server", locales::LANG) - }, + } LOGGING_IN_ID => { t!("mtxcli.logging.in", locales::LANG) - }, + } LOGGED_OUT_ID => { t!("mtxcli.logged.out", locales::LANG) - }, + } NOT_CONNECTED_ID => { t!("mtxcli.not.connected", locales::LANG) - }, + } FAILED_TO_SEND_ID => { t!("mtxcli.send.failed", locales::LANG) - }, + } PLEASE_LOGIN_ID => { t!("mtxcli.please.login", locales::LANG) - }, - _ => { - "unknown async_msg_id" - }, + } + _ => "unknown async_msg_id", }; write!(ret, "{}", warning).unwrap(); log::warn!("{}", warning); return Ok(Some(ret)); - }, + } Message::Move(mm) => { let str_buf = unsafe { StringBuffer::from_memory_message(mm) }; let msg = str_buf.to_str(); @@ -166,7 +164,7 @@ impl<'a> ShellCmdApi<'a> for Help { write!(ret, "{}", msg).unwrap(); return Ok(Some(ret)); } - }, + } _ => { log::error!("received unknown callback type: {:?}", msg) } diff --git a/apps/mtxcli/src/cmds/login.rs b/apps/mtxcli/src/cmds/login.rs index ac6685b13..55225da22 100644 --- a/apps/mtxcli/src/cmds/login.rs +++ b/apps/mtxcli/src/cmds/login.rs @@ -1,20 +1,21 @@ -use crate::{ShellCmdApi,CommonEnv}; use xous_ipc::String as XousString; +use crate::{CommonEnv, ShellCmdApi}; + #[derive(Debug)] -pub struct Login { -} +pub struct Login {} impl Login { - pub fn new() -> Self { - Login { - } - } + pub fn new() -> Self { Login {} } } impl<'a> ShellCmdApi<'a> for Login { cmd_api!(login); - fn process(&mut self, _args: XousString::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + _args: XousString<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { env.login(); Ok(None) } diff --git a/apps/mtxcli/src/cmds/logout.rs b/apps/mtxcli/src/cmds/logout.rs index 914d588da..0b95722ae 100644 --- a/apps/mtxcli/src/cmds/logout.rs +++ b/apps/mtxcli/src/cmds/logout.rs @@ -1,20 +1,21 @@ -use crate::{ShellCmdApi,CommonEnv}; use xous_ipc::String as XousString; +use crate::{CommonEnv, ShellCmdApi}; + #[derive(Debug)] -pub struct Logout { -} +pub struct Logout {} impl Logout { - pub fn new() -> Self { - Logout { - } - } + pub fn new() -> Self { Logout {} } } impl<'a> ShellCmdApi<'a> for Logout { cmd_api!(logout); - fn process(&mut self, _args: XousString::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + _args: XousString<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { env.logout(); Ok(None) } diff --git a/apps/mtxcli/src/cmds/migrations.rs b/apps/mtxcli/src/cmds/migrations.rs index c99622d74..be817a3fc 100644 --- a/apps/mtxcli/src/cmds/migrations.rs +++ b/apps/mtxcli/src/cmds/migrations.rs @@ -3,10 +3,13 @@ //! Runs migrations up to the current version use std::io::Error; -use crate::cmds::{CommonEnv,VERSION_KEY}; + use locales::t; -mod v0_9_11_0120; use v0_9_11_0120::*; +use crate::cmds::{CommonEnv, VERSION_KEY}; + +mod v0_9_11_0120; +use v0_9_11_0120::*; const DEFAULT_VERSION: &str = "0"; @@ -23,18 +26,11 @@ pub trait MigrationApi<'a> { // the argument to this macro is the command verb #[macro_export] macro_rules! migration_api { - ($version:expr) => { // NOTE the expr will have literal quotes - fn version(&self) -> &'static str { - $version - } + ($version:expr) => { + // NOTE the expr will have literal quotes + fn version(&self) -> &'static str { $version } - fn applies(&self, version: &str) -> bool { - if version < self.version() { - true - } else { - false - } - } + fn applies(&self, version: &str) -> bool { if version < self.version() { true } else { false } } }; } @@ -43,8 +39,7 @@ pub fn run_migrations(common: &mut CommonEnv) { let version = common.get_default(VERSION_KEY, DEFAULT_VERSION); if version.ne(&common.version) { let running_migrations = t!("mtxcli.running.migrations", locales::LANG); - let msg = format!("{} {} .. {}", - running_migrations, version, common.version); + let msg = format!("{} {} .. {}", running_migrations, version, common.version); log::info!("{}", msg); common.send_async_msg(&msg); let mut migrations: Vec> = Vec::new(); @@ -54,23 +49,19 @@ pub fn run_migrations(common: &mut CommonEnv) { match migration.process(common) { Ok(boolean) => { let migration_completed = t!("mtxcli.migration.completed", locales::LANG); - let msg = format!("{}: {}: {}", - migration_completed, migration.version(), boolean); + let msg = format!("{}: {}: {}", migration_completed, migration.version(), boolean); common.send_async_msg(&msg); if boolean { - common.set(VERSION_KEY, migration.version()) - .expect("cannot set _version"); + common.set(VERSION_KEY, migration.version()).expect("cannot set _version"); } - }, + } Err(e) => { - log::error!("error running migration: {}: {:?}", - migration.version(), e); + log::error!("error running migration: {}: {:?}", migration.version(), e); } } } } - common.set(VERSION_KEY, &common.version.clone()) - .expect("cannot set _version"); + common.set(VERSION_KEY, &common.version.clone()).expect("cannot set _version"); let migrations_complete = t!("mtxcli.migrations.complete", locales::LANG); log::info!("{}", migrations_complete); common.send_async_msg(&migrations_complete); diff --git a/apps/mtxcli/src/cmds/migrations/v0_9_11_0120.rs b/apps/mtxcli/src/cmds/migrations/v0_9_11_0120.rs index 9a1151383..2df0195fb 100644 --- a/apps/mtxcli/src/cmds/migrations/v0_9_11_0120.rs +++ b/apps/mtxcli/src/cmds/migrations/v0_9_11_0120.rs @@ -1,17 +1,13 @@ use std::io::Error; -use crate::cmds::{CommonEnv,FILTER_KEY}; use crate::cmds::migrations::MigrationApi; +use crate::cmds::{CommonEnv, FILTER_KEY}; use crate::migration_api; #[derive(Debug)] -pub struct V0_9_11_0120 { -} +pub struct V0_9_11_0120 {} impl V0_9_11_0120 { - pub fn new() -> Self { - V0_9_11_0120 { - } - } + pub fn new() -> Self { V0_9_11_0120 {} } } impl<'a> MigrationApi<'a> for V0_9_11_0120 { diff --git a/apps/mtxcli/src/cmds/set.rs b/apps/mtxcli/src/cmds/set.rs index 81bcd756d..29f986daf 100644 --- a/apps/mtxcli/src/cmds/set.rs +++ b/apps/mtxcli/src/cmds/set.rs @@ -1,22 +1,24 @@ -use crate::{ShellCmdApi,CommonEnv}; -use xous_ipc::String as XousString; use core::fmt::Write; + use locales::t; +use xous_ipc::String as XousString; + +use crate::{CommonEnv, ShellCmdApi}; #[derive(Debug)] -pub struct Set { -} +pub struct Set {} impl Set { - pub fn new() -> Self { - Set { - } - } + pub fn new() -> Self { Set {} } } impl<'a> ShellCmdApi<'a> for Set { cmd_api!(set); - fn process(&mut self, args: XousString::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + args: XousString<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { let mut ret = XousString::<1024>::new(); let mut tokens = args.as_str().unwrap().split(' '); @@ -31,16 +33,14 @@ impl<'a> ShellCmdApi<'a> for Set { "" => { write!(ret, "{}", t!("mtxcli.set.help", locales::LANG)).unwrap(); } - _ => { - match env.set(key, value) { - Ok(()) => { - write!(ret, "set {}", key).unwrap(); - }, - Err(e) => { - log::error!("error setting key {}: {:?}", key, e); - } + _ => match env.set(key, value) { + Ok(()) => { + write!(ret, "set {}", key).unwrap(); } - } + Err(e) => { + log::error!("error setting key {}: {:?}", key, e); + } + }, } } else { // Instead of an error -- set to the empty string @@ -49,7 +49,7 @@ impl<'a> ShellCmdApi<'a> for Set { match env.set(key, "") { Ok(()) => { write!(ret, "set {} EMPTY", key).unwrap(); - }, + } Err(e) => { log::error!("error setting key {}: {:?}", key, e); } diff --git a/apps/mtxcli/src/cmds/status.rs b/apps/mtxcli/src/cmds/status.rs index 93379fae2..d02d585f6 100644 --- a/apps/mtxcli/src/cmds/status.rs +++ b/apps/mtxcli/src/cmds/status.rs @@ -1,21 +1,22 @@ -use crate::{ShellCmdApi,CommonEnv}; -use crate::cmds::*; use xous_ipc::String as XousString; +use crate::cmds::*; +use crate::{CommonEnv, ShellCmdApi}; + #[derive(Debug)] -pub struct Status { -} +pub struct Status {} impl Status { - pub fn new() -> Self { - Status { - } - } + pub fn new() -> Self { Status {} } } impl<'a> ShellCmdApi<'a> for Status { cmd_api!(status); - fn process(&mut self, _args: XousString::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + _args: XousString<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { if env.logged_in { env.scalar_async_msg(LOGGED_IN_ID); } else { diff --git a/apps/mtxcli/src/cmds/unset.rs b/apps/mtxcli/src/cmds/unset.rs index 9f667021d..588382bc1 100644 --- a/apps/mtxcli/src/cmds/unset.rs +++ b/apps/mtxcli/src/cmds/unset.rs @@ -1,22 +1,24 @@ -use crate::{ShellCmdApi,CommonEnv}; -use xous_ipc::String as XousString; use core::fmt::Write; + use locales::t; +use xous_ipc::String as XousString; + +use crate::{CommonEnv, ShellCmdApi}; #[derive(Debug)] -pub struct Unset { -} +pub struct Unset {} impl Unset { - pub fn new() -> Self { - Unset { - } - } + pub fn new() -> Self { Unset {} } } impl<'a> ShellCmdApi<'a> for Unset { cmd_api!(unset); - fn process(&mut self, args: XousString::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + fn process( + &mut self, + args: XousString<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { let mut ret = XousString::<1024>::new(); let mut tokens = args.as_str().unwrap().split(' '); @@ -29,7 +31,7 @@ impl<'a> ShellCmdApi<'a> for Unset { match env.unset(key) { Ok(()) => { write!(ret, "unset {}", key).unwrap(); - }, + } Err(e) => { // NOTE: we current expect this error // when unsetting a non existant key diff --git a/apps/mtxcli/src/cmds/url.rs b/apps/mtxcli/src/cmds/url.rs index 7dc085866..4390c34dc 100644 --- a/apps/mtxcli/src/cmds/url.rs +++ b/apps/mtxcli/src/cmds/url.rs @@ -1,22 +1,15 @@ //! URL encoding and decoding /// Encoding to use for conversions -pub const RFC3986: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC - .remove(b'.') - .remove(b'-') - .remove(b'_') - .remove(b'~'); +pub const RFC3986: &percent_encoding::AsciiSet = + &percent_encoding::NON_ALPHANUMERIC.remove(b'.').remove(b'-').remove(b'_').remove(b'~'); /// URL encode string -pub fn encode(v: &str) -> String { - percent_encoding::utf8_percent_encode(v, RFC3986).to_string() -} +pub fn encode(v: &str) -> String { percent_encoding::utf8_percent_encode(v, RFC3986).to_string() } /// URL decode string #[allow(dead_code)] pub fn decode(v: &str) -> String { - let decoded = percent_encoding::percent_decode_str(v) - .decode_utf8() - .expect("unable to decode"); + let decoded = percent_encoding::percent_decode_str(v).decode_utf8().expect("unable to decode"); decoded.to_string() } diff --git a/apps/mtxcli/src/cmds/web.rs b/apps/mtxcli/src/cmds/web.rs index 6cad891b8..136ea03e2 100644 --- a/apps/mtxcli/src/cmds/web.rs +++ b/apps/mtxcli/src/cmds/web.rs @@ -1,6 +1,6 @@ -use serde::{Serialize,Deserialize}; -use ureq::serde_json::{Value, Map}; +use serde::{Deserialize, Serialize}; use ureq; +use ureq::serde_json::{Map, Value}; use crate::cmds::url; @@ -14,21 +14,19 @@ const MTX_ID_USER: &str = "m.id.user"; pub fn get_username(user: &str) -> String { let i = match user.find('@') { - Some(index) => { index + 1 }, - None => { 0 }, + Some(index) => index + 1, + None => 0, }; let j = match user.find(':') { - Some(index) => { index }, - None => { user.len() }, + Some(index) => index, + None => user.len(), }; (&user[i..j]).to_string() } fn serialize(object: &T) -> Option { match ureq::serde_json::to_string(&object) { - Ok(value) => { - Some(value) - }, + Ok(value) => Some(value), Err(e) => { log::info!("ERROR in serialize: {:?}", e); None @@ -36,7 +34,7 @@ fn serialize(object: &T) -> Option { } } -pub fn handle_response(maybe_response: Result) -> Option { +pub fn handle_response(maybe_response: Result) -> Option { match maybe_response { Ok(response) => { if let Ok(body) = response.into_json() { @@ -45,7 +43,7 @@ pub fn handle_response(maybe_response: Result) -> Op log::info!("Error: could not convert response into JSON"); None } - }, + } Err(ureq::Error::Status(code, response)) => { /* the server returned an unexpected status code (such as 400, 500 etc) */ @@ -61,42 +59,29 @@ pub fn handle_response(maybe_response: Result) -> Op } pub fn get_json(url: &str) -> Result { - ureq::get(&url) - .set(ACCEPT, ACCEPT_JSON) - .call() + ureq::get(&url).set(ACCEPT, ACCEPT_JSON).call() } -pub fn get_json_auth(url: &str, token:&str) -> Result { +pub fn get_json_auth(url: &str, token: &str) -> Result { let mut authorization = String::from(BEARER); authorization.push_str(token); - ureq::get(&url) - .set(ACCEPT, ACCEPT_JSON) - .set(AUTHORIZATION, &authorization) - .call() + ureq::get(&url).set(ACCEPT, ACCEPT_JSON).set(AUTHORIZATION, &authorization).call() } pub fn post_string(url: &str, request_body: &str) -> Result { - ureq::post(&url) - .set(ACCEPT, ACCEPT_JSON) - .send_string(request_body) + ureq::post(&url).set(ACCEPT, ACCEPT_JSON).send_string(request_body) } pub fn post_string_auth(url: &str, request_body: &str, token: &str) -> Result { let mut authorization = String::from(BEARER); authorization.push_str(token); - ureq::post(&url) - .set(ACCEPT, ACCEPT_JSON) - .set(AUTHORIZATION, &authorization) - .send_string(request_body) + ureq::post(&url).set(ACCEPT, ACCEPT_JSON).set(AUTHORIZATION, &authorization).send_string(request_body) } pub fn put_string_auth(url: &str, request_body: &str, token: &str) -> Result { let mut authorization = String::from(BEARER); authorization.push_str(token); - ureq::put(&url) - .set(ACCEPT, ACCEPT_JSON) - .set(AUTHORIZATION, &authorization) - .send_string(request_body) + ureq::put(&url).set(ACCEPT, ACCEPT_JSON).set(AUTHORIZATION, &authorization).send_string(request_body) } // -------------------------------- @@ -157,15 +142,8 @@ struct AuthRequest { impl AuthRequest { pub fn new(user: &str, password: &str) -> Self { - let identifier = AuthIdentifier { - type_: MTX_ID_USER.to_string(), - user: user.to_string() - }; - AuthRequest { - type_: MTX_LOGIN_PASSWORD.to_string(), - identifier: identifier, - password: password.to_string() - } + let identifier = AuthIdentifier { type_: MTX_ID_USER.to_string(), user: user.to_string() }; + AuthRequest { type_: MTX_LOGIN_PASSWORD.to_string(), identifier, password: password.to_string() } } } @@ -221,10 +199,7 @@ impl EventFilter { pub fn new(limit: i32) -> Self { let mut not_types: Vec = Vec::new(); not_types.push("*".to_string()); - EventFilter { - limit, - not_types, - } + EventFilter { limit, not_types } } } @@ -241,17 +216,13 @@ impl RoomEventFilter { types.push(type_0.to_string()); let mut rooms: Vec = Vec::new(); rooms.push(room_id.to_string()); - RoomEventFilter { - limit, - types, - rooms, - } + RoomEventFilter { limit, types, rooms } } } #[derive(Serialize, Deserialize)] struct RoomFilter { - account_data: EventFilter, // Should be RoomEventFilter + account_data: EventFilter, // Should be RoomEventFilter ephemeral: EventFilter, rooms: Vec, state: EventFilter, // Should be StateFilter @@ -266,13 +237,7 @@ impl RoomFilter { rooms.push(room_id.to_string()); let state = EventFilter::new(0); let timeline = RoomEventFilter::new(10, room_id, "m.room.message"); - RoomFilter { - account_data, - ephemeral, - rooms, - state, - timeline, - } + RoomFilter { account_data, ephemeral, rooms, state, timeline } } } @@ -293,17 +258,11 @@ impl FilterRequest { event_fields.push("content.body".to_string()); let presence = EventFilter::new(0); let room = RoomFilter::new(room_id); - FilterRequest { - account_data, - event_fields, - presence, - room, - } + FilterRequest { account_data, event_fields, presence, room } } } -pub fn get_filter(user: &str, server: &str, room_id: &str, token: &str) - -> Option { +pub fn get_filter(user: &str, server: &str, room_id: &str, token: &str) -> Option { let user_encoded = url::encode(user); let mut url = String::from(server); url.push_str("/_matrix/client/v3/user/"); @@ -358,7 +317,6 @@ fn get_messages(body: Map, room_id: &str) -> String { if let Some(Value::Object(content)) = event.get("content") { if let Some(Value::String(body)) = content.get("body") { messages.push_str(body); - } else { messages.push_str("...."); } @@ -376,8 +334,14 @@ fn get_messages(body: Map, room_id: &str) -> String { messages } -pub fn client_sync(server: &str, filter: &str, since: &str, timeout: i32, - room_id: &str, token: &str) -> Option<(String, String)> { +pub fn client_sync( + server: &str, + filter: &str, + since: &str, + timeout: i32, + room_id: &str, + token: &str, +) -> Option<(String, String)> { log::info!("heap usage: {}", crate::cmds::heap_usage()); let mut url = String::from(server); url.push_str("/_matrix/client/r0/sync?filter="); @@ -416,10 +380,7 @@ impl MessageRequest { pub fn new(text: &str) -> Self { let msgtype = "m.text".to_string(); let body = text.to_string(); - MessageRequest { - msgtype, - body, - } + MessageRequest { msgtype, body } } } diff --git a/apps/mtxcli/src/main.rs b/apps/mtxcli/src/main.rs index eaaae677f..c9df9d265 100644 --- a/apps/mtxcli/src/main.rs +++ b/apps/mtxcli/src/main.rs @@ -23,14 +23,9 @@ pub(crate) enum MtxcliOp { // This name should be (1) unique (2) under 64 characters long and (3) ideally descriptive. pub(crate) const SERVER_NAME_MTXCLI: &str = "_Matrix cli_"; -fn main () -> ! { +fn main() -> ! { let stack_size = 1024 * 1024; - std::thread::Builder::new() - .stack_size(stack_size) - .spawn(wrapped_main) - .unwrap() - .join() - .unwrap() + std::thread::Builder::new().stack_size(stack_size).spawn(wrapped_main).unwrap().join().unwrap() } fn wrapped_main() -> ! { @@ -40,11 +35,8 @@ fn wrapped_main() -> ! { const HEAP_LARGER_LIMIT: usize = 2048 * 1024; let new_limit = HEAP_LARGER_LIMIT; - let result = xous::rsyscall(xous::SysCall::AdjustProcessLimit( - xous::Limits::HeapMaximum as usize, - 0, - new_limit, - )); + let result = + xous::rsyscall(xous::SysCall::AdjustProcessLimit(xous::Limits::HeapMaximum as usize, 0, new_limit)); if let Ok(xous::Result::Scalar2(1, current_limit)) = result { xous::rsyscall(xous::SysCall::AdjustProcessLimit( diff --git a/apps/mtxcli/src/mtxcli.rs b/apps/mtxcli/src/mtxcli.rs index eee822ae1..4f9dbf41a 100644 --- a/apps/mtxcli/src/mtxcli.rs +++ b/apps/mtxcli/src/mtxcli.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 { @@ -22,7 +24,7 @@ pub(crate) struct Mtxcli { msg: Option, // record our input history - history: Vec::, + history: Vec, history_len: usize, content: Gid, gam: gam::Gam, @@ -30,7 +32,7 @@ pub(crate) struct Mtxcli { // 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 @@ -38,25 +40,31 @@ pub(crate) struct Mtxcli { // command environment env: CmdEnv, } -impl Mtxcli{ +impl Mtxcli { 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_MTXCLI), - 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: MtxcliOp::Redraw.to_u32().unwrap(), - gotinput_id: Some(MtxcliOp::Line.to_u32().unwrap()), - audioframe_id: None, - rawkeys_id: None, - focuschange_id: Some(MtxcliOp::ChangeFocus.to_u32().unwrap()), - }).expect("couldn't register Ux context for mtxcli"); + let token = gam + .register_ux(UxRegistration { + app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_MTXCLI), + 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: MtxcliOp::Redraw.to_u32().unwrap(), + gotinput_id: Some(MtxcliOp::Line.to_u32().unwrap()), + audioframe_id: None, + rawkeys_id: None, + focuschange_id: Some(MtxcliOp::ChangeFocus.to_u32().unwrap()), + }) + .expect("couldn't register Ux context for mtxcli"); 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"); - let history: Vec:: = vec![History{text: String::from(t!("mtxcli.greeting", locales::LANG)), is_input: false}]; + let history: Vec = + vec![History { text: String::from(t!("mtxcli.greeting", locales::LANG)), is_input: false }]; let env = CmdEnv::new(); Mtxcli { input: None, @@ -82,9 +90,7 @@ impl Mtxcli{ 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 { @@ -97,10 +103,7 @@ impl Mtxcli{ 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); } @@ -109,28 +112,29 @@ impl Mtxcli{ // 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; @@ -149,15 +153,18 @@ impl Mtxcli{ } 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(); @@ -167,18 +174,20 @@ impl Mtxcli{ // 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 { @@ -189,13 +198,14 @@ impl Mtxcli{ 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