a bit more deck shuffling on the APIs

feels a lot cleaner now.
This commit is contained in:
bunnie 2021-03-04 16:02:42 +08:00
parent 76684c89fc
commit aa8c0e5792
8 changed files with 136 additions and 105 deletions

1
Cargo.lock generated
View file

@ -547,6 +547,7 @@ dependencies = [
name = "ime-plugin-api" name = "ime-plugin-api"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"log",
"rkyv", "rkyv",
"xous", "xous",
] ]

View file

@ -141,6 +141,9 @@ fn xmain() -> ! {
ime_frontend::set_input_canvas(imef_conn, chatlayout.input).expect("GAM: couldn't set IMEF input canvas"); ime_frontend::set_input_canvas(imef_conn, chatlayout.input).expect("GAM: couldn't set IMEF input canvas");
ime_frontend::set_prediction_canvas(imef_conn, chatlayout.predictive).expect("GAM: couldn't set IMEF prediction canvas"); ime_frontend::set_prediction_canvas(imef_conn, chatlayout.predictive).expect("GAM: couldn't set IMEF prediction canvas");
// ASSUME: shell is our default application, so set a default predictor of Shell
ime_frontend::set_predictor(imef_conn, xous::names::SERVER_NAME_IME_PLUGIN_SHELL).expect("GAM: couldn't set IMEF prediction to shell");
let mut last_time: u64 = ticktimer_server::elapsed_ms(ticktimer_conn).unwrap(); let mut last_time: u64 = ticktimer_server::elapsed_ms(ticktimer_conn).unwrap();
info!("GAM: entering main loop"); info!("GAM: entering main loop");
loop { loop {

View file

@ -12,3 +12,16 @@ pub fn set_prediction_canvas(cid: CID, g: graphics_server::Gid) -> Result<(), xo
send_message(cid, api::Opcode::SetPredictionCanvas(g).into())?; send_message(cid, api::Opcode::SetPredictionCanvas(g).into())?;
Ok(()) Ok(())
} }
pub fn set_predictor(cid: CID, servername: &str) -> Result<(), xous::Error> {
let mut server = xous::String::<256>::new();
use core::fmt::Write;
write!(server, "{}", servername).expect("IMEF: couldn't write set_predictor server name");
let ime_op = api::Opcode::SetPredictionServer(server);
use rkyv::Write as ArchiveWrite;
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&ime_op).expect("IMEF: couldn't archive SetPredictionServer");
writer.into_inner().lend(cid, pos as u32).expect("IMEF: SetPredicitonServer request failure");
Ok(())
}

View file

@ -8,11 +8,11 @@ use core::convert::TryFrom;
use log::{error, info}; use log::{error, info};
use graphics_server::Gid; use graphics_server::{Gid, TextView};
use heapless::Vec; use heapless::Vec;
use heapless::consts::U32; use heapless::consts::U32;
use core::pin::Pin; use core::pin::Pin;
use ime_plugin_api::{PredictionTriggers, PredictionApi}; use ime_plugin_api::{PredictionTriggers, PredictionPlugin, PredictionApi};
use rkyv::Unarchive; use rkyv::Unarchive;
use rkyv::archived_value; use rkyv::archived_value;
@ -20,14 +20,17 @@ use rkyv::archived_value;
struct InputTracker { struct InputTracker {
/// connection for handling graphical update requests /// connection for handling graphical update requests
pub gam_conn: xous::CID, pub gam_conn: xous::CID,
/// input area canvas, as given by the GAM /// input area canvas, as given by the GAM
pub input_canvas: Option<Gid>, input_canvas: Option<Gid>,
/// a connection to our current prediction engine
pub pred_conn: xous::CID,
/// prediction display area, as given by the GAM /// prediction display area, as given by the GAM
pub pred_canvas: Option<Gid>, pred_canvas: Option<Gid>,
/// triggers for predictions
pub pred_triggers: PredictionTriggers, /// our current prediction engine
predictor: Option<PredictionPlugin>,
/// cached copy of the predictor's triggers for predictions. Only valid if predictor is not None
pred_triggers: Option<PredictionTriggers>,
/// track the progress of our input line /// track the progress of our input line
line: xous::String::<4096>, line: xous::String::<4096>,
@ -35,45 +38,44 @@ struct InputTracker {
charwidths: [u8; 4096], charwidths: [u8; 4096],
/// what position the insertion cursor is at in the string. 0 is inserting elements into the front of the string /// what position the insertion cursor is at in the string. 0 is inserting elements into the front of the string
insertion: u8, insertion: u8,
predictions: [Option<TextView>; 4],
} }
impl InputTracker {
pub fn new(gam_conn: xous::CID, pred_conn: xous::CID, predictor: impl PredictionApi)-> InputTracker {
// a little dangerous: bypassing any explicit API call implementation for this one
/*
let response = xous::send_message(pred_conn, ime_plugin_api::Opcode::GetPredictionTriggers.into())
.expect("IMEF: InputTracker failed to get predictions from default plugin");
if let xous::Result::Scalar1(code) = response {
InputTracker {
gam_conn,
input_canvas: None,
pred_conn,
pred_canvas: None,
pred_triggers: code.into(),
line: xous::String::<4096>::new(),
charwidths: [0; 4096],
insertion: 0,
}
} else {
panic!("IMEF: InputTracker::new() failed to get prediction triggers")
}*/
let pred_triggers = predictor.get_prediction_triggers(pred_conn) impl InputTracker {
.expect("IMEF: InputTracker failed to get predictions from default plugin"); pub fn new(gam_conn: xous::CID)-> InputTracker {
InputTracker { InputTracker {
gam_conn, gam_conn,
input_canvas: None, input_canvas: None,
pred_conn,
pred_canvas: None, pred_canvas: None,
pred_triggers, predictor: None,
pred_triggers: None,
line: xous::String::<4096>::new(), line: xous::String::<4096>::new(),
charwidths: [0; 4096], charwidths: [0; 4096],
insertion: 0, insertion: 0,
predictions: [None; 4],
} }
} }
pub fn set_predictor(&mut self, predictor: PredictionPlugin) {
self.predictor = Some(predictor);
self.pred_triggers = Some(predictor.get_prediction_triggers()
.expect("IMEF: InputTracker failed to get prediction triggers from plugin"));
}
pub fn set_input_canvas(&mut self, input: Gid) {
self.input_canvas = Some(input);
}
pub fn set_pred_canvas(&mut self, pred: Gid) {
self.pred_canvas = Some(pred);
}
pub fn is_init(&self) -> bool {
self.input_canvas.is_some() && self.pred_canvas.is_some()
}
pub fn update(&mut self, newkeys: [char; 4]) { pub fn update(&mut self, newkeys: [char; 4]) {
// just draw a rectangle for the prediction area for now
/* /*
what else do we need: what else do we need:
- current string that is being built up - current string that is being built up
@ -102,14 +104,9 @@ fn xmain() -> ! {
let kbd_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_KBD).expect("IMEF: can't connect to KBD"); let kbd_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_KBD).expect("IMEF: can't connect to KBD");
keyboard::request_events(xous::names::SERVER_NAME_IME_FRONT, kbd_conn).expect("IMEF: couldn't request events from keyboard"); keyboard::request_events(xous::names::SERVER_NAME_IME_FRONT, kbd_conn).expect("IMEF: couldn't request events from keyboard");
let default_predictor = ime_plugin_api::StandardPredictionPlugin {};
let mut tracker = InputTracker::new( let mut tracker = InputTracker::new(
xous_names::request_connection_blocking(xous::names::SERVER_NAME_GAM).expect("IMEF: can't connect to GAM"), xous_names::request_connection_blocking(xous::names::SERVER_NAME_GAM).expect("IMEF: can't connect to GAM"),
// set a "default" prediction that is a shell-like history buffer of things previously typed
xous_names::request_connection_blocking(xous::names::SERVER_NAME_IME_PLUGIN_SHELL).expect("IMEF: can't connect to shell prediction engine"),
default_predictor
); );
// The first message should be my Gid from the GAM. // The first message should be my Gid from the GAM.
info!("IMEF: waiting for my canvas Gids"); info!("IMEF: waiting for my canvas Gids");
loop { loop {
@ -129,7 +126,7 @@ fn xmain() -> ! {
} else { } else {
info!("IMEF: expected canvas Gid, but got other message first {:?}", envelope); info!("IMEF: expected canvas Gid, but got other message first {:?}", envelope);
} }
if tracker.input_canvas.is_some() && tracker.pred_canvas.is_some() { if tracker.is_init() {
break; break;
} }
} }
@ -163,7 +160,7 @@ fn xmain() -> ! {
rkyv::Archived::<api::Opcode>::SetPredictionServer(rkyv_s) => { rkyv::Archived::<api::Opcode>::SetPredictionServer(rkyv_s) => {
let s: xous::String<256> = rkyv_s.unarchive(); let s: xous::String<256> = rkyv_s.unarchive();
match xous_names::request_connection(s.as_str().expect("IMEF: SetPrediction received malformed server name")) { match xous_names::request_connection(s.as_str().expect("IMEF: SetPrediction received malformed server name")) {
Ok(pc) => tracker.pred_conn = pc, Ok(pc) => tracker.set_predictor(ime_plugin_api::PredictionPlugin {connection: Some(pc)}),
_ => error!("IMEF: can't find predictive engine {}, retaining existing one.", s.as_str().expect("IMEF: SetPrediction received malformed server name")), _ => error!("IMEF: can't find predictive engine {}, retaining existing one.", s.as_str().expect("IMEF: SetPrediction received malformed server name")),
} }
}, },

View file

@ -8,4 +8,5 @@ description = "IME Plugin Common APIs"
[dependencies] [dependencies]
xous = { path = "../../xous-rs" } xous = { path = "../../xous-rs" }
rkyv = { version = "0.3.1", default_features = false } rkyv = { version = "0.3.1", default_features = false }
log = "0.4"

View file

@ -90,80 +90,105 @@ impl Into<Message> for Opcode {
} }
} }
pub trait PredictionApi {
fn get_prediction_triggers(&self) -> Result<PredictionTriggers, xous::Error>;
fn unpick(&self) -> Result<(), xous::Error>;
fn set_input(&self, s: String<4096>) -> Result<(), xous::Error>;
fn feedback_picked(&self, s: String<4096>) -> Result<(), xous::Error>;
fn get_prediction(&self, index: u32) -> Result<xous::String<4096>, xous::Error>;
}
// provide a convenience version of the API for generic/standard calls // provide a convenience version of the API for generic/standard calls
#[derive(Debug, Default, Copy, Clone)] #[derive(Debug, Default, Copy, Clone)]
pub struct StandardPredictionPlugin {} pub struct PredictionPlugin {
impl PredictionApi for StandardPredictionPlugin {} pub connection: Option<CID>,
}
// it's pretty dangerous to not use the default version of the API, because this is an IPC barrier impl PredictionApi for PredictionPlugin {
// and Rust can't check arguments and correctness between separate programs. fn get_prediction_triggers(&self) -> Result<PredictionTriggers, xous::Error> {
// In other words, you should really think twice before overriding these. match self.connection {
pub trait PredictionApi { Some(cid) => {
fn get_prediction_triggers(&self, cid: CID) -> Result<PredictionTriggers, xous::Error> { let response = xous::send_message(cid, Opcode::GetPredictionTriggers.into())?;
let response = xous::send_message(cid, Opcode::GetPredictionTriggers.into())?; if let xous::Result::Scalar1(code) = response {
if let xous::Result::Scalar1(code) = response { Ok(code.into())
Ok(code.into()) } else {
} else { Err(xous::Error::InternalError)
panic!("get_prediciton_triggers failed") }
},
_ => Err(xous::Error::UseBeforeInit),
} }
} }
fn unpick(&self, cid: CID) -> Result<(), xous::Error> { fn unpick(&self) -> Result<(), xous::Error> {
xous::send_message(cid, Opcode::Unpick.into())?; match self.connection {
Ok(()) Some(cid) => {
xous::send_message(cid, Opcode::Unpick.into())?;
Ok(())
},
_ => Err(xous::Error::UseBeforeInit)
}
} }
fn set_input(&self, cid: CID, s: String<4096>) -> Result<(), xous::Error> { fn set_input(&self, s: String<4096>) -> Result<(), xous::Error> {
use rkyv::Write; use rkyv::Write;
match self.connection {
Some(cid) => {
let rkyv_input = Opcode::Input(s);
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rkyv_input).expect("IME|API: couldn't archive input string");
let xous_buffer = writer.into_inner();
let rkyv_input = Opcode::Input(s); xous_buffer.lend(cid, pos as u32).expect("IME|API: set_input operation failure");
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096)); Ok(())
let pos = writer.archive(&rkyv_input).expect("IMES|API: couldn't archive input string"); },
let xous_buffer = writer.into_inner(); _ => Err(xous::Error::UseBeforeInit),
}
xous_buffer.lend(cid, pos as u32).expect("IMES|API: set_input operation failure");
Ok(())
} }
fn feedback_picked(&self, cid: CID, s: String<4096>) -> Result<(), xous::Error> { fn feedback_picked(&self, s: String<4096>) -> Result<(), xous::Error> {
use rkyv::Write; use rkyv::Write;
match self.connection {
Some(cid) => {
let rkyv_picked = Opcode::Picked(s);
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rkyv_picked).expect("IME|API: couldn't archive picked string");
let xous_buffer = writer.into_inner();
let rkyv_picked = Opcode::Picked(s); xous_buffer.lend(cid, pos as u32).expect("IME|API: feedback_picked operation failure");
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096)); Ok(())
let pos = writer.archive(&rkyv_picked).expect("IMES|API: couldn't archive picked string"); },
let xous_buffer = writer.into_inner(); _ => Err(xous::Error::UseBeforeInit),
}
xous_buffer.lend(cid, pos as u32).expect("IMES|API: feedback_picked operation failure");
Ok(())
} }
fn get_prediction(&self, cid: CID, index: u32) -> Result<xous::String<4096>, xous::Error> { fn get_prediction(&self, index: u32) -> Result<xous::String<4096>, xous::Error> {
use rkyv::Write; use rkyv::Write;
use rkyv::Unarchive; use rkyv::Unarchive;
match self.connection {
Some(cid) => {
let prediction = Prediction {
index,
string: xous::String::<4096>::new(),
};
let pred_op = Opcode::Prediction(prediction);
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&pred_op).expect("IME|API: couldn't archive prediction request");
let mut xous_buffer = writer.into_inner();
let prediction = Prediction { xous_buffer.lend_mut(cid, pos as u32).expect("IME|API: prediction fetch operation failure");
index,
string: xous::String::<4096>::new(),
};
let pred_op = Opcode::Prediction(prediction);
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096)); let returned = unsafe { rkyv::archived_value::<Opcode>(xous_buffer.as_ref(), pos)};
let pos = writer.archive(&pred_op).expect("IMES|API: couldn't archive prediction request"); if let rkyv::Archived::<Opcode>::Prediction(result) = returned {
let mut xous_buffer = writer.into_inner(); let pred_r: Prediction = result.unarchive();
let retstring: xous::String<4096> = pred_r.string.clone();
xous_buffer.lend_mut(cid, pos as u32).expect("IMES|API: prediction fetch operation failure"); Ok(retstring)
} else {
let returned = unsafe { rkyv::archived_value::<Opcode>(xous_buffer.as_ref(), pos)}; let r = returned.unarchive();
if let rkyv::Archived::<Opcode>::Prediction(result) = returned { log::error!("IME:API get_prediction returned an invalid result {:?}", r);
let pred_r: Prediction = result.unarchive(); Err(xous::Error::InvalidString)
}
let retstring: xous::String<4096> = pred_r.string.clone(); },
Ok(retstring) _ => Err(xous::Error::UseBeforeInit),
} else {
let r = returned.unarchive();
Err(xous::Error::InvalidString)
} }
} }
} }

View file

@ -1,10 +1,4 @@
#![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_std)]
// just inherit all the default from the ime_plugin_api
pub use ime_plugin_api::*; pub use ime_plugin_api::*;
pub struct PredictionApiImpl {
}
impl PredictionApi for PredictionApiImpl {
// inherit all the default methods
}

View file

@ -19,11 +19,7 @@ fn xmain() -> ! {
info!("IME_SH: my PID is {}", xous::process::id()); info!("IME_SH: my PID is {}", xous::process::id());
let ime_sh_sid = xous_names::register_name(xous::names::SERVER_NAME_IME_PLUGIN_SHELL).expect("IME_SH: can't register server"); let ime_sh_sid = xous_names::register_name(xous::names::SERVER_NAME_IME_PLUGIN_SHELL).expect("IME_SH: can't register server");
info!("IME_SH: registered with NS -- {:?}", ime_sh_sid); if debug1{info!("IME_SH: registered with NS -- {:?}", ime_sh_sid);}
let imef_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_IME_FRONT).expect("IME_SH: can't connect to IMEF");
info!("IME_SH: ready to accept requests");
let mut history: Queue<xous::String<4096>, U3> = Queue::new(); // this has 2^3 elements = 8 let mut history: Queue<xous::String<4096>, U3> = Queue::new(); // this has 2^3 elements = 8
let history_max = 8; let history_max = 8;
@ -34,6 +30,7 @@ fn xmain() -> ! {
trigger_whitespace: false, trigger_whitespace: false,
}; };
info!("IME_SH: ready to accept requests");
loop { loop {
let envelope = xous::receive_message(ime_sh_sid).unwrap(); let envelope = xous::receive_message(ime_sh_sid).unwrap();
if debug1{info!("IME_SH: received message {:?}", envelope);} if debug1{info!("IME_SH: received message {:?}", envelope);}