mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-20 09:03:28 +00:00
add a demo REPL app to help users get started with something more interactive
This commit is contained in:
parent
a52f498edb
commit
583c2e172b
15 changed files with 762 additions and 2 deletions
24
Cargo.lock
generated
24
Cargo.lock
generated
|
|
@ -1779,6 +1779,30 @@ dependencies = [
|
||||||
"winapi",
|
"winapi",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "repl"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"codec",
|
||||||
|
"com",
|
||||||
|
"content-plugin-api",
|
||||||
|
"gam",
|
||||||
|
"graphics-server",
|
||||||
|
"ime-plugin-api",
|
||||||
|
"ime-plugin-shell",
|
||||||
|
"llio",
|
||||||
|
"locales",
|
||||||
|
"log",
|
||||||
|
"log-server",
|
||||||
|
"num-derive",
|
||||||
|
"num-traits",
|
||||||
|
"ticktimer-server",
|
||||||
|
"trng",
|
||||||
|
"xous",
|
||||||
|
"xous-ipc",
|
||||||
|
"xous-names",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ring"
|
name = "ring"
|
||||||
version = "0.16.20"
|
version = "0.16.20"
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,7 @@ default-members = [
|
||||||
"services/dns",
|
"services/dns",
|
||||||
"services/modals",
|
"services/modals",
|
||||||
"apps/ball",
|
"apps/ball",
|
||||||
|
"apps/repl",
|
||||||
]
|
]
|
||||||
members = [
|
members = [
|
||||||
"xous-ipc",
|
"xous-ipc",
|
||||||
|
|
@ -86,6 +87,7 @@ members = [
|
||||||
"services/dns",
|
"services/dns",
|
||||||
"services/modals",
|
"services/modals",
|
||||||
"apps/ball",
|
"apps/ball",
|
||||||
|
"apps/repl",
|
||||||
"kernel",
|
"kernel",
|
||||||
]
|
]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
|
||||||
|
|
@ -10,3 +10,4 @@ but without much emphasis on I/O.
|
||||||
3. Add it to the Workspace `default-members` and `members` arrays by editing `./Cargo.toml`
|
3. Add it to the Workspace `default-members` and `members` arrays by editing `./Cargo.toml`
|
||||||
4. Add it to the build by editing `xtask/src/main.rs` and inserting it into the relevant descriptor. Typically, you would insert your app into the `hw_pkgs` array, as this is what is built and targeted for full hardware builds. Most of the other trimmed-down descriptors are for debug, emulation, and benchmarking.
|
4. Add it to the build by editing `xtask/src/main.rs` and inserting it into the relevant descriptor. Typically, you would insert your app into the `hw_pkgs` array, as this is what is built and targeted for full hardware builds. Most of the other trimmed-down descriptors are for debug, emulation, and benchmarking.
|
||||||
5. (optional) You may also need to run `cargo xtask generate-locales` if you modify/add any internationalization strings.
|
5. (optional) You may also need to run `cargo xtask generate-locales` if you modify/add any internationalization strings.
|
||||||
|
6. Add entries to the app switching menu. `services/status/src/appmenu.rs` to add the menu item (plus `locales/i18n.json` in the status directory if you want translated names for the app), and `services/status/src/main.rs` to add the Opcode (inside the `StatusOpcode` struct, around line 55) and the actual operation itself (in the main `loop`, around line 670).
|
||||||
|
|
|
||||||
30
apps/repl/Cargo.toml
Normal file
30
apps/repl/Cargo.toml
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
[package]
|
||||||
|
name = "repl"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["bunnie <bunnie@kosagi.com>"]
|
||||||
|
edition = "2018"
|
||||||
|
description = "REPL demo app"
|
||||||
|
|
||||||
|
# Dependency policy: fully specify dependencies to the minor version number
|
||||||
|
[dependencies]
|
||||||
|
log = "0.4.14"
|
||||||
|
num-derive = {version = "0.3.3", default-features = false}
|
||||||
|
num-traits = {version = "0.2.14", default-features = false}
|
||||||
|
xous = { path = "../../xous-rs" }
|
||||||
|
xous-ipc = { path = "../../xous-ipc" }
|
||||||
|
log-server = { path = "../../services/log-server" }
|
||||||
|
ticktimer-server = { path = "../../services/ticktimer-server" }
|
||||||
|
xous-names = { path = "../../services/xous-names" }
|
||||||
|
gam = {path = "../../services/gam" }
|
||||||
|
graphics-server = {path = "../../services/graphics-server" }
|
||||||
|
trng = {path = "../../services/trng"}
|
||||||
|
locales = {path = "../../locales"}
|
||||||
|
ime-plugin-api = {path = "../../services/ime-plugin-api"}
|
||||||
|
ime-plugin-shell = {path = "../../services/ime-plugin-shell"}
|
||||||
|
content-plugin-api = {path = "../../services/content-plugin-api"} # all content canvas providers must provide this API
|
||||||
|
com = {path = "../../services/com"}
|
||||||
|
llio = {path = "../../services/llio"}
|
||||||
|
codec = {path = "../../services/codec"}
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = []
|
||||||
12
apps/repl/README.md
Normal file
12
apps/repl/README.md
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
# REPL
|
||||||
|
|
||||||
|
A simple demo application that provides a bare-bones REPL framework.
|
||||||
|
|
||||||
|
## Integration
|
||||||
|
|
||||||
|
1. Add a UX context by editing `services/gam/src/lib.rs/EXPECTED_BOOT_CONTEXTS`
|
||||||
|
2. Copy this demo application, and rename the relevant structures in its `Cargo.toml` and `main.rs`.
|
||||||
|
3. Add it to the Workspace `default-members` and `members` arrays by editing `./Cargo.toml`
|
||||||
|
4. Add it to the build by editing `xtask/src/main.rs` and inserting it into the relevant descriptor. Typically, you would insert your app into the `hw_pkgs` array, as this is what is built and targeted for full hardware builds. Most of the other trimmed-down descriptors are for debug, emulation, and benchmarking.
|
||||||
|
5. (optional) You may also need to run `cargo xtask generate-locales` if you modify/add any internationalization strings.
|
||||||
|
6. Add entries to the app switching menu. `services/status/src/appmenu.rs` to add the menu item (plus `locales/i18n.json` in the status directory if you want translated names for the app), and `services/status/src/main.rs` to add the Opcode (inside the `StatusOpcode` struct, around line 55) and the actual operation itself (in the main `loop`, around line 670).
|
||||||
17
apps/repl/locales/i18n.json
Normal file
17
apps/repl/locales/i18n.json
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
{
|
||||||
|
"replapp.beep.help": {
|
||||||
|
"en": "beep [tone [freq [duration]]]",
|
||||||
|
"zh": "beep [tone [音频 [时长]]]",
|
||||||
|
"en-audio": "beep tone, then optional frequency plus optional duration."
|
||||||
|
},
|
||||||
|
"replapp.beep.completion_a": {
|
||||||
|
"en": "Playback stopped at",
|
||||||
|
"zh": "播放停止在",
|
||||||
|
"en-audio": "Playback stopped at"
|
||||||
|
},
|
||||||
|
"replapp.beep.completion_b": {
|
||||||
|
"en": "frames",
|
||||||
|
"zh": "帧",
|
||||||
|
"en-audio": "frames"
|
||||||
|
}
|
||||||
|
}
|
||||||
218
apps/repl/src/cmds.rs
Normal file
218
apps/repl/src/cmds.rs
Normal file
|
|
@ -0,0 +1,218 @@
|
||||||
|
use xous::{MessageEnvelope};
|
||||||
|
use xous_ipc::String;
|
||||||
|
use core::fmt::Write;
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
/////////////////////////// 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<Option<String::<1024>>, 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<Option<String::<1024>>, xous::Error> {
|
||||||
|
log::info!("received unhandled message {:?}", msg);
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
// created with cmd_api! macro
|
||||||
|
// checks if the command matches the current verb in question
|
||||||
|
fn matches(&self, verb: &str) -> bool;
|
||||||
|
// returns my verb
|
||||||
|
fn verb(&self) -> &'static str;
|
||||||
|
}
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
use trng::*;
|
||||||
|
/////////////////////////// Command shell integration
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[allow(dead_code)] // there's more in the envornment right now than we need for the demo
|
||||||
|
pub struct CommonEnv {
|
||||||
|
llio: llio::Llio,
|
||||||
|
com: com::Com,
|
||||||
|
codec: codec::Codec,
|
||||||
|
ticktimer: ticktimer_server::Ticktimer,
|
||||||
|
gam: gam::Gam,
|
||||||
|
cb_registrations: HashMap::<u32, String::<256>>,
|
||||||
|
trng: Trng,
|
||||||
|
xns: xous_names::XousNames,
|
||||||
|
}
|
||||||
|
impl CommonEnv {
|
||||||
|
pub fn register_handler(&mut self, verb: String::<256>) -> u32 {
|
||||||
|
let mut key: u32;
|
||||||
|
loop {
|
||||||
|
key = self.trng.get_u32().unwrap();
|
||||||
|
// reserve the bottom 1000 IDs for the main loop enums.
|
||||||
|
if !self.cb_registrations.contains_key(&key) && (key > 1000) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.cb_registrations.insert(key, verb);
|
||||||
|
key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
To add a new command:
|
||||||
|
0. ensure that the command implements the ShellCmdApi (above)
|
||||||
|
1. mod/use the new command
|
||||||
|
2. create an entry for the command's storage in the CmdEnv structure
|
||||||
|
3. initialize the persistant storage here
|
||||||
|
4. add it to the "commands" array in the dispatch() routine below
|
||||||
|
|
||||||
|
Side note: if your command doesn't require persistent storage, you could,
|
||||||
|
technically, generate the command dynamically every time it's called.
|
||||||
|
*/
|
||||||
|
|
||||||
|
///// 1. add your module here, and pull its namespace into the local crate
|
||||||
|
mod beep; use beep::*;
|
||||||
|
|
||||||
|
pub struct CmdEnv {
|
||||||
|
common_env: CommonEnv,
|
||||||
|
lastverb: String::<256>,
|
||||||
|
///// 2. declare storage for your command here.
|
||||||
|
beep_cmd: Beep,
|
||||||
|
}
|
||||||
|
impl CmdEnv {
|
||||||
|
pub fn new(xns: &xous_names::XousNames) -> CmdEnv {
|
||||||
|
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
|
||||||
|
let common = CommonEnv {
|
||||||
|
llio: llio::Llio::new(&xns),
|
||||||
|
com: com::Com::new(&xns).expect("could't connect to COM"),
|
||||||
|
codec: codec::Codec::new(&xns).expect("couldn't connect to CODEC"),
|
||||||
|
ticktimer,
|
||||||
|
gam: gam::Gam::new(&xns).expect("couldn't connect to GAM"),
|
||||||
|
cb_registrations: HashMap::new(),
|
||||||
|
trng: Trng::new(&xns).unwrap(),
|
||||||
|
xns: xous_names::XousNames::new().unwrap(),
|
||||||
|
};
|
||||||
|
|
||||||
|
CmdEnv {
|
||||||
|
common_env: common,
|
||||||
|
lastverb: String::<256>::new(),
|
||||||
|
///// 3. initialize your storage, by calling new()
|
||||||
|
beep_cmd: Beep::new(&xns),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dispatch(&mut self, maybe_cmdline: Option<&mut String::<1024>>, maybe_callback: Option<&MessageEnvelope>) -> Result<Option<String::<1024>>, xous::Error> {
|
||||||
|
let mut ret = String::<1024>::new();
|
||||||
|
|
||||||
|
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.beep_cmd,
|
||||||
|
];
|
||||||
|
|
||||||
|
if let Some(cmdline) = maybe_cmdline {
|
||||||
|
let maybe_verb = tokenize(cmdline);
|
||||||
|
|
||||||
|
let mut cmd_ret: Result<Option<String::<1024>>, xous::Error> = Ok(None);
|
||||||
|
if let Some(verb_string) = maybe_verb {
|
||||||
|
let verb = verb_string.to_str();
|
||||||
|
|
||||||
|
// search through the list of commands linearly until one matches,
|
||||||
|
// then run it.
|
||||||
|
let mut match_found = false;
|
||||||
|
for cmd in commands.iter_mut() {
|
||||||
|
if cmd.matches(verb) {
|
||||||
|
match_found = true;
|
||||||
|
cmd_ret = cmd.process(*cmdline, &mut self.common_env);
|
||||||
|
self.lastverb.clear();
|
||||||
|
write!(self.lastverb, "{}", verb).expect("couldn't record last verb");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// if none match, create a list of available commands
|
||||||
|
if !match_found {
|
||||||
|
let mut first = true;
|
||||||
|
write!(ret, "Commands: ").unwrap();
|
||||||
|
for cmd in commands.iter() {
|
||||||
|
if !first {
|
||||||
|
ret.append(", ")?;
|
||||||
|
}
|
||||||
|
ret.append(cmd.verb())?;
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
Ok(Some(ret))
|
||||||
|
} else {
|
||||||
|
cmd_ret
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
} else if let Some(callback) = maybe_callback {
|
||||||
|
let mut cmd_ret: Result<Option<String::<1024>>, 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()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// now dispatch
|
||||||
|
let mut verbfound = false;
|
||||||
|
for cmd in commands.iter_mut() {
|
||||||
|
if cmd.matches(verb) {
|
||||||
|
cmd_ret = cmd.callback(callback, &mut self.common_env);
|
||||||
|
verbfound = true;
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
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 String::<1024>) -> Option<String::<1024>> {
|
||||||
|
let mut token = String::<1024>::new();
|
||||||
|
let mut retline = String::<1024>::new();
|
||||||
|
|
||||||
|
let lineiter = line.as_str().unwrap().chars();
|
||||||
|
let mut foundspace = false;
|
||||||
|
let mut foundrest = false;
|
||||||
|
for ch in lineiter {
|
||||||
|
if ch != ' ' && !foundspace {
|
||||||
|
token.push(ch).unwrap();
|
||||||
|
} else if foundspace && foundrest {
|
||||||
|
retline.push(ch).unwrap();
|
||||||
|
} else if foundspace && ch != ' ' {
|
||||||
|
// handle case of multiple spaces in a row
|
||||||
|
foundrest = true;
|
||||||
|
retline.push(ch).unwrap();
|
||||||
|
} else {
|
||||||
|
foundspace = true;
|
||||||
|
// consume the space
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line.clear();
|
||||||
|
write!(line, "{}", retline.as_str().unwrap()).unwrap();
|
||||||
|
if token.len() > 0 {
|
||||||
|
Some(token)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
139
apps/repl/src/cmds/beep.rs
Normal file
139
apps/repl/src/cmds/beep.rs
Normal file
|
|
@ -0,0 +1,139 @@
|
||||||
|
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 Beep {
|
||||||
|
callback_id: Option<u32>,
|
||||||
|
callback_conn: u32,
|
||||||
|
framecount: u32,
|
||||||
|
play_sample: f32, // count of play samples generated. in f32 to avoid int<->f32 conversions
|
||||||
|
freq: f32,
|
||||||
|
}
|
||||||
|
impl Beep {
|
||||||
|
pub fn new(xns: &xous_names::XousNames) -> Self {
|
||||||
|
let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_REPL).unwrap();
|
||||||
|
|
||||||
|
Beep {
|
||||||
|
callback_id: None,
|
||||||
|
callback_conn,
|
||||||
|
framecount: 0,
|
||||||
|
play_sample: 0.0,
|
||||||
|
freq: 440.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SAMPLE_RATE_HZ: f32 = 8000.0;
|
||||||
|
// note to self: A4 = 440.0, E4 = 329.63, C4 = 261.63
|
||||||
|
|
||||||
|
impl<'a> ShellCmdApi<'a> for Beep {
|
||||||
|
cmd_api!(beep);
|
||||||
|
|
||||||
|
fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
|
||||||
|
let mut ret = String::<1024>::new();
|
||||||
|
let helpstring = t!("replapp.beep.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 freq_str.parse::<f32>() {
|
||||||
|
Ok(f) => f,
|
||||||
|
Err(_) => 440.0,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
440.0
|
||||||
|
};
|
||||||
|
let mut duration: f32 = if let Some(duration_str) = tokens.next() {
|
||||||
|
duration_str.parse::<f32>().unwrap_or(2.0)
|
||||||
|
} else {
|
||||||
|
2.0
|
||||||
|
};
|
||||||
|
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();
|
||||||
|
|
||||||
|
env.ticktimer.sleep_ms((duration * 1000.0) as usize).unwrap();
|
||||||
|
|
||||||
|
env.codec.pause().unwrap(); // this should stop callbacks from occurring too.
|
||||||
|
write!(ret, "{} {} {}.",
|
||||||
|
t!("replapp.beep.completion_a", xous::LANG),
|
||||||
|
self.framecount,
|
||||||
|
t!("replapp.beep.completion_b", xous::LANG),
|
||||||
|
).unwrap();
|
||||||
|
self.framecount = 0;
|
||||||
|
self.play_sample = 0.0;
|
||||||
|
env.codec.power_off().unwrap();
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
write!(ret, "{}", helpstring).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
Ok(Some(ret))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn callback(&mut self, msg: &MessageEnvelope, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
|
||||||
|
const AMPLITUDE: f32 = 0.8;
|
||||||
|
|
||||||
|
match &msg.body {
|
||||||
|
Message::Scalar(xous::ScalarMessage{id: _, arg1: free_play, arg2: _avail_rec, arg3: _, arg4: _}) => {
|
||||||
|
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();
|
||||||
|
},
|
||||||
|
Message::Move(_mm) => {
|
||||||
|
log::error!("received memory message when not expected")
|
||||||
|
},
|
||||||
|
_ => {
|
||||||
|
log::error!("received unknown callback type")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
77
apps/repl/src/main.rs
Normal file
77
apps/repl/src/main.rs
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
#![cfg_attr(target_os = "none", no_std)]
|
||||||
|
#![cfg_attr(target_os = "none", no_main)]
|
||||||
|
|
||||||
|
mod repl;
|
||||||
|
use repl::*;
|
||||||
|
mod cmds;
|
||||||
|
use cmds::*;
|
||||||
|
use num_traits::*;
|
||||||
|
use xous_ipc::Buffer;
|
||||||
|
|
||||||
|
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||||
|
pub(crate) enum ReplOp {
|
||||||
|
/// a line of text has arrived
|
||||||
|
Line = 0, // make sure we occupy opcodes with discriminants < 1000, as the rest are used for callbacks
|
||||||
|
/// redraw our UI
|
||||||
|
Redraw,
|
||||||
|
/// exit the application
|
||||||
|
Quit,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) const SERVER_NAME_REPL: &str = "_REPL demo application_";
|
||||||
|
|
||||||
|
#[xous::xous_main]
|
||||||
|
fn xmain() -> ! {
|
||||||
|
log_server::init_wait().unwrap();
|
||||||
|
log::set_max_level(log::LevelFilter::Info);
|
||||||
|
log::info!("my PID is {}", xous::process::id());
|
||||||
|
|
||||||
|
let xns = xous_names::XousNames::new().unwrap();
|
||||||
|
// unlimited connections allowed, this is a user app and it's up to the app to decide its policy
|
||||||
|
let sid = xns.register_name(SERVER_NAME_REPL, None).expect("can't register server");
|
||||||
|
//log::trace!("registered with NS -- {:?}", sid);
|
||||||
|
|
||||||
|
let mut repl = Repl::new(&xns, sid);
|
||||||
|
let mut update_repl = false;
|
||||||
|
let mut was_callback = false;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let msg = xous::receive_message(sid).unwrap();
|
||||||
|
log::debug!("got message {:?}", msg);
|
||||||
|
match FromPrimitive::from_usize(msg.body.id()) {
|
||||||
|
Some(ReplOp::Line) => {
|
||||||
|
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
|
||||||
|
let s = buffer.as_flat::<xous_ipc::String<4000>, _>().unwrap();
|
||||||
|
log::trace!("repl got input line: {}", s.as_str());
|
||||||
|
repl.input(s.as_str()).expect("REPL couldn't accept input string");
|
||||||
|
update_repl = true; // set a flag, instead of calling here, so message can drop and calling server is released
|
||||||
|
was_callback = false;
|
||||||
|
}
|
||||||
|
Some(ReplOp::Redraw) => {
|
||||||
|
log::trace!("got Redraw");
|
||||||
|
repl.redraw().expect("REPL couldn't redraw");
|
||||||
|
}
|
||||||
|
Some(ReplOp::Quit) => {
|
||||||
|
log::error!("got Quit");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
log::trace!("got unknown message, treating as callback");
|
||||||
|
repl.msg(msg);
|
||||||
|
update_repl = true;
|
||||||
|
was_callback = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if update_repl {
|
||||||
|
repl.update(was_callback).expect("REPL had problems updating");
|
||||||
|
update_repl = false;
|
||||||
|
}
|
||||||
|
log::trace!("reached bottom of main loop");
|
||||||
|
}
|
||||||
|
// clean up our program
|
||||||
|
log::error!("main loop exit, destroying servers");
|
||||||
|
xns.unregister_server(sid).unwrap();
|
||||||
|
xous::destroy_server(sid).unwrap();
|
||||||
|
log::trace!("quitting");
|
||||||
|
xous::terminate_process(0)
|
||||||
|
}
|
||||||
214
apps/repl/src/repl.rs
Normal file
214
apps/repl/src/repl.rs
Normal file
|
|
@ -0,0 +1,214 @@
|
||||||
|
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;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct History {
|
||||||
|
// the history record
|
||||||
|
pub text: String,
|
||||||
|
// if true, this was input from the user; if false, it's a response from the shell
|
||||||
|
pub is_input: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) struct Repl {
|
||||||
|
// optional structures that indicate new input to the Repl loop per iteration
|
||||||
|
// an input string
|
||||||
|
input: Option<String>,
|
||||||
|
// messages from other servers
|
||||||
|
msg: Option<MessageEnvelope>,
|
||||||
|
|
||||||
|
// record our input history
|
||||||
|
history: Vec::<History>,
|
||||||
|
history_len: usize,
|
||||||
|
content: Gid,
|
||||||
|
gam: gam::Gam,
|
||||||
|
|
||||||
|
// variables that define our graphical attributes
|
||||||
|
screensize: Point,
|
||||||
|
bubble_width: u16,
|
||||||
|
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
|
||||||
|
|
||||||
|
// command environment
|
||||||
|
env: CmdEnv,
|
||||||
|
|
||||||
|
// our security token for making changes to our record on the GAM
|
||||||
|
token: [u32; 4],
|
||||||
|
}
|
||||||
|
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: None, // repl will keep running in the background even if it has lost focus
|
||||||
|
}).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::new(),
|
||||||
|
history_len: 10,
|
||||||
|
content,
|
||||||
|
gam,
|
||||||
|
screensize,
|
||||||
|
bubble_width: ((screensize.x / 5) * 4) as u16, // 80% width for the text bubbles
|
||||||
|
margin: Point::new(4, 4),
|
||||||
|
bubble_margin: Point::new(4, 4),
|
||||||
|
bubble_radius: 4,
|
||||||
|
bubble_space: 4,
|
||||||
|
env: CmdEnv::new(xns),
|
||||||
|
token: token.unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// accept a new input string
|
||||||
|
pub(crate) fn input(&mut self, line: &str) -> Result<(), xous::Error> {
|
||||||
|
self.input = Some(String::from(line));
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
self.history.remove(0);
|
||||||
|
}
|
||||||
|
self.history.push(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// update the loop, in response to various inputs
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
self.circular_push(input_history);
|
||||||
|
}
|
||||||
|
|
||||||
|
// AT THIS POINT: if we have other inputs, update accordingly
|
||||||
|
// other inputs might be, for example, events that came in from other servers that would
|
||||||
|
// 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
|
||||||
|
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
|
||||||
|
};
|
||||||
|
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
|
||||||
|
};
|
||||||
|
self.circular_push(output_history);
|
||||||
|
} else {
|
||||||
|
dirty = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// clear all the inputs to the loop, so we don't process them twice
|
||||||
|
self.input = None;
|
||||||
|
self.msg = None;
|
||||||
|
// redraw UI now that we've responded
|
||||||
|
if dirty {
|
||||||
|
self.redraw().expect("can't redraw");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> {
|
||||||
|
self.clear_area();
|
||||||
|
|
||||||
|
// this defines the bottom border of the text bubbles as they stack up wards
|
||||||
|
let mut bubble_baseline = self.screensize.y - self.margin.y;
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
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))
|
||||||
|
};
|
||||||
|
if h.is_input {
|
||||||
|
bubble_tv.border_width = 1;
|
||||||
|
} else {
|
||||||
|
bubble_tv.border_width = 2;
|
||||||
|
}
|
||||||
|
bubble_tv.draw_border = true;
|
||||||
|
bubble_tv.clear_area = true;
|
||||||
|
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;
|
||||||
|
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.
|
||||||
|
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
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
break; // we get None on the bounds computed if the text view fell off the top of the screen
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.gam.redraw().expect("couldn't redraw screen");
|
||||||
|
// self.gam.request_ime_redraw().expect("couldn't redraw the IME area");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -32,7 +32,8 @@ pub const SHARED_MODAL_NAME: &'static str = "shared modal";
|
||||||
pub const STATUS_BAR_NAME: &'static str = "status";
|
pub const STATUS_BAR_NAME: &'static str = "status";
|
||||||
pub const APP_NAME_SHELLCHAT: &'static str = "shellchat";
|
pub const APP_NAME_SHELLCHAT: &'static str = "shellchat";
|
||||||
pub const APP_MENU_NAME: &'static str = "app menu";
|
pub const APP_MENU_NAME: &'static str = "app menu";
|
||||||
pub const APP_NAME_BALL: &'static str = "ball app";
|
pub const APP_NAME_BALL: &'static str = "ball demo app";
|
||||||
|
pub const APP_NAME_REPL: &'static str = "repl demo app";
|
||||||
|
|
||||||
/// UX context registry. Names here are authorized by the GAM to have Canvases.
|
/// UX context registry. Names here are authorized by the GAM to have Canvases.
|
||||||
pub const EXPECTED_BOOT_CONTEXTS: &[&'static str] = &[
|
pub const EXPECTED_BOOT_CONTEXTS: &[&'static str] = &[
|
||||||
|
|
@ -46,6 +47,7 @@ pub const EXPECTED_BOOT_CONTEXTS: &[&'static str] = &[
|
||||||
PDDB_MENU_NAME,
|
PDDB_MENU_NAME,
|
||||||
APP_MENU_NAME,
|
APP_MENU_NAME,
|
||||||
APP_NAME_BALL,
|
APP_NAME_BALL,
|
||||||
|
APP_NAME_REPL,
|
||||||
];
|
];
|
||||||
|
|
||||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||||
|
|
|
||||||
|
|
@ -94,6 +94,11 @@
|
||||||
"zh": "简单的球演示",
|
"zh": "简单的球演示",
|
||||||
"en-audio": "Simple ball demo"
|
"en-audio": "Simple ball demo"
|
||||||
},
|
},
|
||||||
|
"appmenu.repl": {
|
||||||
|
"en": "Basic REPL demo",
|
||||||
|
"zh": "基本 REPL 演示",
|
||||||
|
"en-audio": "Basic REPL demo"
|
||||||
|
},
|
||||||
"appmenu.shellchat": {
|
"appmenu.shellchat": {
|
||||||
"en": "Shellchat",
|
"en": "Shellchat",
|
||||||
"zh": "外壳聊天",
|
"zh": "外壳聊天",
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,14 @@ pub fn create_app_menu(status_conn: xous::CID) {
|
||||||
close_on_select: true,
|
close_on_select: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
menu_items.push(MenuItem {
|
||||||
|
name: xous_ipc::String::from_str(t!("appmenu.repl", xous::LANG)),
|
||||||
|
action_conn: Some(status_conn),
|
||||||
|
action_opcode: StatusOpcode::SwitchToRepl.to_u32().unwrap(),
|
||||||
|
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
|
||||||
|
close_on_select: true,
|
||||||
|
});
|
||||||
|
|
||||||
menu_items.push(MenuItem {
|
menu_items.push(MenuItem {
|
||||||
name: xous_ipc::String::from_str(t!("mainmenu.closemenu", xous::LANG)),
|
name: xous_ipc::String::from_str(t!("mainmenu.closemenu", xous::LANG)),
|
||||||
action_conn: None,
|
action_conn: None,
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,8 @@ enum StatusOpcode {
|
||||||
SwitchToShellchat,
|
SwitchToShellchat,
|
||||||
/// Raise the Ball app
|
/// Raise the Ball app
|
||||||
SwitchToBall,
|
SwitchToBall,
|
||||||
|
/// Raise the REPL demo app
|
||||||
|
SwitchToRepl,
|
||||||
|
|
||||||
/// Suspend handler from the main menu
|
/// Suspend handler from the main menu
|
||||||
TrySuspend,
|
TrySuspend,
|
||||||
|
|
@ -667,6 +669,10 @@ fn xmain() -> ! {
|
||||||
ticktimer.sleep_ms(100).ok();
|
ticktimer.sleep_ms(100).ok();
|
||||||
gam.switch_to_app(gam::APP_NAME_BALL, security_tv.token.unwrap()).expect("couldn't raise ball demo");
|
gam.switch_to_app(gam::APP_NAME_BALL, security_tv.token.unwrap()).expect("couldn't raise ball demo");
|
||||||
},
|
},
|
||||||
|
Some(StatusOpcode::SwitchToRepl) => {
|
||||||
|
ticktimer.sleep_ms(100).ok();
|
||||||
|
gam.switch_to_app(gam::APP_NAME_REPL, security_tv.token.unwrap()).expect("couldn't raise repl demo");
|
||||||
|
},
|
||||||
Some(StatusOpcode::TrySuspend) => {
|
Some(StatusOpcode::TrySuspend) => {
|
||||||
if ((llio.adc_vbus().unwrap() as f64) * 0.005033) > 1.5 {
|
if ((llio.adc_vbus().unwrap() as f64) * 0.005033) > 1.5 {
|
||||||
modals.show_notification(t!("mainmenu.cant_sleep", xous::LANG)).expect("couldn't notify that power is plugged in");
|
modals.show_notification(t!("mainmenu.cant_sleep", xous::LANG)).expect("couldn't notify that power is plugged in");
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,7 @@ impl std::error::Error for BuildError {}
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let hw_pkgs = [
|
let hw_pkgs = [
|
||||||
|
// core OS services
|
||||||
"gam",
|
"gam",
|
||||||
"status",
|
"status",
|
||||||
"shellchat",
|
"shellchat",
|
||||||
|
|
@ -59,7 +60,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
"dns",
|
"dns",
|
||||||
"pddb",
|
"pddb",
|
||||||
"modals",
|
"modals",
|
||||||
|
// apps
|
||||||
"ball",
|
"ball",
|
||||||
|
"repl",
|
||||||
];
|
];
|
||||||
let benchmark_pkgs = [
|
let benchmark_pkgs = [
|
||||||
"benchmark",
|
"benchmark",
|
||||||
|
|
@ -968,8 +971,10 @@ fn project_root() -> PathBuf {
|
||||||
fn generate_locales() -> Result<(), std::io::Error> {
|
fn generate_locales() -> Result<(), std::io::Error> {
|
||||||
let ts = filetime::FileTime::from_system_time(std::time::SystemTime::now());
|
let ts = filetime::FileTime::from_system_time(std::time::SystemTime::now());
|
||||||
filetime::set_file_mtime("locales/src/lib.rs", ts)?;
|
filetime::set_file_mtime("locales/src/lib.rs", ts)?;
|
||||||
|
let mut path = project_root();
|
||||||
|
path.push("locales");
|
||||||
let status = Command::new(cargo())
|
let status = Command::new(cargo())
|
||||||
.current_dir(project_root())
|
.current_dir(path)
|
||||||
.args(&[
|
.args(&[
|
||||||
"build",
|
"build",
|
||||||
"--package",
|
"--package",
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue