diff --git a/apps/manifest.json b/apps/manifest.json index faa8b6156..def46d9c2 100644 --- a/apps/manifest.json +++ b/apps/manifest.json @@ -47,11 +47,11 @@ "mtxcli": { "context_name": "Matrix chat", "menu_name": { - "appmenu.repl": { + "appmenu.mtxcli": { "en": "Matrix chat", "ja": "シンプルなMATRIXデモ", "zh": "基本 MATRIX 演示", - "en-tts": "Basic MATRIX demo" + "en-tts": "MATRIX demo" } } } diff --git a/apps/mtxcli/locales/i18n.json b/apps/mtxcli/locales/i18n.json index 766249fda..25e803b32 100644 --- a/apps/mtxcli/locales/i18n.json +++ b/apps/mtxcli/locales/i18n.json @@ -1,32 +1,38 @@ { "mtxcli.greeting": { - "en": "Welcome to the simple MTXCLI demo.", + "en": "Welcome to the MTXCLI demo.", "ja": "シンプルなMTXCLIデモへようこそ", "zh": "简单的 mtxcli 演示活动", "en-tts": "Welcome to the simple MTXCLI demo." }, - "mtxcli.audio.start": { - "en": "tone started...", - "ja": "トーン開始…", - "zh": "哔声开始...", - "en-tts": "tone started..." + "mtxcli.help.help": { + "en": "help [cmd]", + "ja": "TBD help [cmd]", + "zh": "TBD help [cmd]", + "en-tts": "help [cmd]" }, - "mtxcli.audio.help": { - "en": "audio [tone [freq [duration]]]", - "ja": "オーディオ [ トーン [ 周波数 [ 間隔 ]]]", - "zh": "audio [tone [音频 [时长]]]", - "en-tts": "audio tone, then optional frequency plus optional duration." + "mtxcli.help.overview": { + "en": "available mtxcli commands:", + "ja": "TBD available mtxcli commands:", + "zh": "TBD available mtxcli commands:", + "en-tts": "available mtxcli commands:" }, - "mtxcli.audio.completion_a": { - "en": "Playback stopped at", - "ja": "再生停止位置: ", - "zh": "播放停止在", - "en-tts": "Playback stopped at" + "mtxcli.quit.help": { + "en": "quit (returns to shellchat)", + "ja": "TBD quit...", + "zh": "TBD quit...", + "en-tts": "quit (returns to shellchat)" }, - "mtxcli.audio.completion_b": { - "en": "frames", - "ja": "フレーム", - "zh": "帧", - "en-tts": "frames" + "mtxcli.quit.quitting": { + "en": "quitting...", + "ja": "TBD quitting...", + "zh": "TBD quitting...", + "en-tts": "quitting.." + }, + "mtxcli.unknown.help": { + "en": "unknown command", + "ja": "TBD unknown command", + "zh": "TBD unknown command", + "en-tts": "unknown command" } } diff --git a/apps/mtxcli/src/cmds.rs b/apps/mtxcli/src/cmds.rs index 043febd27..a1b7ba4cd 100644 --- a/apps/mtxcli/src/cmds.rs +++ b/apps/mtxcli/src/cmds.rs @@ -51,6 +51,7 @@ pub struct CommonEnv { xns: xous_names::XousNames, } impl CommonEnv { + /* currently unused pub fn register_handler(&mut self, verb: String::<256>) -> u32 { let mut key: u32; loop { @@ -63,6 +64,7 @@ impl CommonEnv { self.cb_registrations.insert(key, verb); key } + */ } /* @@ -78,13 +80,15 @@ impl CommonEnv { */ ///// 1. add your module here, and pull its namespace into the local crate -mod audio; use audio::*; +mod help; use help::*; +mod quit; use quit::*; pub struct CmdEnv { common_env: CommonEnv, lastverb: String::<256>, ///// 2. declare storage for your command here. - audio_cmd: Audio, + help_cmd: Help, + quit_cmd: Quit, } impl CmdEnv { pub fn new(xns: &xous_names::XousNames) -> CmdEnv { @@ -105,7 +109,8 @@ impl CmdEnv { common_env: common, lastverb: String::<256>::new(), ///// 3. initialize your storage, by calling new() - audio_cmd: Audio::new(&xns), + help_cmd: Help::new(&xns), + quit_cmd: Quit::new(&xns), } } @@ -114,7 +119,8 @@ impl CmdEnv { 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, + &mut self.help_cmd, + &mut self.quit_cmd, ]; if let Some(cmdline) = maybe_cmdline { diff --git a/apps/mtxcli/src/cmds/audio.rs b/apps/mtxcli/src/cmds/audio.rs deleted file mode 100644 index 4575eb527..000000000 --- a/apps/mtxcli/src/cmds/audio.rs +++ /dev/null @@ -1,185 +0,0 @@ -use crate::{ShellCmdApi,CommonEnv}; -use xous_ipc::String; -use xous::{MessageEnvelope, Message}; -use codec::*; -use core::fmt::Write; -use locales::t; - -#[derive(Debug)] -pub struct Audio { - callback_id: Option, - callback_conn: u32, - framecount: u32, - play_sample: f32, // count of play samples generated. in f32 to avoid int<->f32 conversions - freq: f32, -} -impl Audio { - pub fn new(xns: &xous_names::XousNames) -> Self { - let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_MTXCLI).unwrap(); - Audio { - callback_id: None, - callback_conn, - framecount: 0, - play_sample: 0.0, - freq: 440.0, - } - } -} - -const STOP_ID: usize = 1; -const SAMPLE_RATE_HZ: f32 = 8000.0; -// note to self: A4 = 440.0, E4 = 329.63, C4 = 261.63 - -use std::num::ParseIntError; -/// this will parse a simple decimal into an i32, multiplied by 1000 -/// we do this because the full f32 parsing stuff is pretty heavy, some -/// 28kiB of code -#[inline(never)] -fn simple_kilofloat_parse(input: &str) -> core::result::Result { - if let Some((integer, fraction)) = input.split_once('.') { - let mut result = integer.parse::()? * 1000; - let mut significance = 100i32; - for (place, digit) in fraction.chars().enumerate() { - if place >= 3 { - break; - } - if let Some(d) = digit.to_digit(10) { - if result >= 0 { - result += (d as i32) * significance; - } else { - result -= (d as i32) * significance; - } - significance /= 10; - } else { - return "z".parse::() // you can't create a ParseIntError any other way - } - } - Ok(result) - } else { - let base = input.parse::()?; - Ok(base * 1000) - } -} - -impl<'a> ShellCmdApi<'a> for Audio { - cmd_api!(audio); - - fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { - let mut ret = String::<1024>::new(); - let helpstring = t!("mtxcli.audio.help", xous::LANG); - let mut tokens = args.as_str().unwrap().split(' '); - - if let Some(sub_cmd) = tokens.next() { - match sub_cmd { - "tone" => { - self.freq = if let Some(freq_str) = tokens.next() { - match simple_kilofloat_parse(freq_str) { - Ok(f) => (f as f32) / 1000.0, - Err(_) => 440.0, - } - } else { - 440.0 - }; - let mut duration: f32 = if let Some(duration_str) = tokens.next() { - simple_kilofloat_parse(duration_str).unwrap_or(500) as f32 / 1000.0 - } else { - 0.5 - }; - if duration > 10.0 { - duration = 10.0; // sanity check the duration so we don't go nuts - } - - env.codec.setup_8k_stream().expect("couldn't set the CODEC to expected defaults"); - env.ticktimer.sleep_ms(50).unwrap(); - - env.codec.set_speaker_volume(VolumeOps::RestoreDefault, None).unwrap(); - env.codec.set_headphone_volume(VolumeOps::RestoreDefault, None).unwrap(); - - if self.callback_id.is_none() { - let cb_id = env.register_handler(String::<256>::from_str(self.verb())); - log::trace!("hooking frame callback with ID {}", cb_id); - env.codec.hook_frame_callback(cb_id, self.callback_conn).unwrap(); // any non-handled IDs get routed to our callback port - self.callback_id = Some(cb_id); - } - - self.play_sample = 0.0; - - env.codec.resume().unwrap(); - - // kick off a thread that stops the playback, after the designated delay - std::thread::spawn({ - let cb_id = self.callback_id.unwrap().clone(); - let conn = self.callback_conn.clone(); - let duration = duration.clone(); - 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(); - } - }); - write!(ret, "{}", t!("mtxcli.audio.start", xous::LANG)).unwrap(); - } - _ => { - write!(ret, "{}", helpstring).unwrap(); - } - } - - } - Ok(Some(ret)) - } - - 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}) => { - if *routing_id == codec::AUDIO_CB_ROUTING_ID { - let mut frames: FrameRing = FrameRing::new(); - let frames_to_push = if frames.writeable_count() < *free_play { - frames.writeable_count() - } else { - *free_play - }; - self.framecount += frames_to_push as u32; - - 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]; - // 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 * f32::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; - self.play_sample += 1.0; - } - - 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, "{} {} {}.", - t!("mtxcli.audio.completion_a", xous::LANG), - self.framecount, - t!("mtxcli.audio.completion_b", xous::LANG), - ).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") - } - } - Ok(None) - } -} diff --git a/apps/mtxcli/src/cmds/help.rs b/apps/mtxcli/src/cmds/help.rs new file mode 100644 index 000000000..8ba6693da --- /dev/null +++ b/apps/mtxcli/src/cmds/help.rs @@ -0,0 +1,47 @@ +use crate::{ShellCmdApi,CommonEnv}; +use xous_ipc::String; +use core::fmt::Write; +use locales::t; + +#[derive(Debug)] +pub struct Help { +} +impl Help { + pub fn new(_xns: &xous_names::XousNames) -> Self { + Help { + } + } +} + +impl<'a> ShellCmdApi<'a> for Help { + cmd_api!(help); + + fn process(&mut self, args: String::<1024>, _env: &mut CommonEnv) -> Result>, xous::Error> { + let mut ret = String::<1024>::new(); + let mut tokens = args.as_str().unwrap().split(' '); + + // write!(ret, "{}", t!("mtxcli.help.helpting", xous::LANG)).unwrap(); + + if let Some(cmd) = tokens.next() { + match cmd { + "help" => { + write!(ret, "{}", t!("mtxcli.help.help", xous::LANG)).unwrap(); + } + "quit" => { + write!(ret, "{}", t!("mtxcli.quit.help", xous::LANG)).unwrap(); + } + "" => { + write!(ret, "{}\n", t!("mtxcli.help.overview", xous::LANG)).unwrap(); + write!(ret, "{}\n", t!("mtxcli.help.help", xous::LANG)).unwrap(); + write!(ret, "{}", t!("mtxcli.quit.help", xous::LANG)).unwrap(); + } + _ => { + write!(ret, "{}: {}", + t!("mtxcli.unknown.help", xous::LANG), cmd).unwrap(); + } + } + } + + Ok(Some(ret)) + } +} diff --git a/apps/mtxcli/src/cmds/quit.rs b/apps/mtxcli/src/cmds/quit.rs new file mode 100644 index 000000000..dad519df9 --- /dev/null +++ b/apps/mtxcli/src/cmds/quit.rs @@ -0,0 +1,26 @@ +use crate::{ShellCmdApi,CommonEnv}; +use xous_ipc::String; +use core::fmt::Write; +use locales::t; + +#[derive(Debug)] +pub struct Quit { +} +impl Quit { + pub fn new(_xns: &xous_names::XousNames) -> Self { + Quit { + } + } +} + +impl<'a> ShellCmdApi<'a> for Quit { + cmd_api!(quit); + + fn process(&mut self, _args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + let mut ret = String::<1024>::new(); + + write!(ret, "{}", t!("mtxcli.quit.quitting", xous::LANG)).unwrap(); + env.gam.request_default_app().unwrap(); + Ok(Some(ret)) + } +} diff --git a/services/gam/src/api.rs b/services/gam/src/api.rs index 3b86e8265..afe906728 100644 --- a/services/gam/src/api.rs +++ b/services/gam/src/api.rs @@ -74,6 +74,10 @@ pub struct SwitchToApp { pub app_name: String::<128>, } +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct DefaultApp { +} + #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub enum UxType { Chat, @@ -201,6 +205,9 @@ pub(crate) enum Opcode { Bip39toBytes = 30, BytestoBip39 = 31, Bip39Suggestions = 32, + + /// Request switching to the default app + DefaultApp = 33, } // small wart -- we have to reset the size of a modal to max size for resize computations diff --git a/services/gam/src/lib.rs b/services/gam/src/lib.rs index c53417d7b..1c6ad6471 100644 --- a/services/gam/src/lib.rs +++ b/services/gam/src/lib.rs @@ -394,6 +394,13 @@ impl Gam { let buf = Buffer::into_buf(switchapp).or(Err(xous::Error::InternalError))?; buf.send(self.conn, Opcode::SwitchToApp.to_u32().unwrap()).or(Err(xous::Error::InternalError)).map(|_|()) } + /// Allows applications to "quit" and switch to a default application + pub fn request_default_app(&self) -> Result<(), xous::Error> { + let defaultapp = DefaultApp { + }; + let buf = Buffer::into_buf(defaultapp).or(Err(xous::Error::InternalError))?; + buf.send(self.conn, Opcode::DefaultApp.to_u32().unwrap()).or(Err(xous::Error::InternalError)).map(|_|()) + } pub fn raise_menu(&self, menu_name_str: &str) -> Result<(), xous::Error> { let menu_name = GamActivation { name: String::<128>::from_str(menu_name_str), diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index bafdae764..f0f157c97 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -664,6 +664,10 @@ fn wrapped_main() -> ! { } buffer.replace(spec).unwrap(); } + Some(Opcode::DefaultApp) => { + // FIXME: Switch to shellchat here + log::error!("not implemented yet, switch to shellchat: {:?}", msg); + } Some(Opcode::Quit) => break, None => {log::error!("unhandled message {:?}", msg);} }