From 0f937037e43bcf14d560495efdb3d5be4f8b4a92 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 18 Jun 2021 16:20:56 +0800 Subject: [PATCH] just getting to the point of implementing defacement menu now pops up. does nothing, but we can at least change contexts for the Ux into a different Ux theme. --- services/gam/src/canvas.rs | 7 ++-- services/gam/src/main.rs | 21 ++++++++--- services/gam/src/menu.rs | 3 +- services/ime-frontend/src/main.rs | 35 ++++++++++++++---- services/shellchat/src/main.rs | 2 +- services/xous-names/src/api.rs | 14 ++++++-- services/xous-names/src/lib.rs | 37 ++++++++++++++++++- services/xous-names/src/main.rs | 60 +++++++++++++++++++++++++++---- 8 files changed, 153 insertions(+), 26 deletions(-) diff --git a/services/gam/src/canvas.rs b/services/gam/src/canvas.rs index 5bad60bb5..923baf237 100644 --- a/services/gam/src/canvas.rs +++ b/services/gam/src/canvas.rs @@ -145,7 +145,7 @@ impl PartialEq for Canvas { impl Eq for Canvas {} -pub fn deface(gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap) -> Result<(), xous::Error> { +pub fn deface(gfx: &graphics_server::Gfx, tng: &trng::Trng, canvases: &mut FnvIndexMap) -> Result<(), xous::Error> { // first check if any need defacing, if not, then we're done let mut needs_defacing = false; for (_, c) in canvases.iter() { @@ -163,11 +163,12 @@ pub fn deface(gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap, // app_token of the main menu, if it has been registered } impl ContextManager { pub fn new(xns: &xous_names::XousNames) -> Self { @@ -131,6 +132,7 @@ impl ContextManager { imef, imef_active: false, kbd, + main_menu_app_token: None, } } pub(crate) fn claim_token(&mut self, name: &str) -> Option<[u32; 4]> { @@ -203,6 +205,12 @@ impl ContextManager { if maybe_context.is_none() { *maybe_context = Some(ux_context); found_slot = true; + // if this is the main menu, note its app token, as we have to conjure it later on + if registration.app_name.as_str().unwrap() == MAIN_MENU_NAME { + log::debug!("main menu found and registered!"); + assert!(self.main_menu_app_token == None, "attempt to double-register main menu handler, this should never happen."); + self.main_menu_app_token = Some(token); + } break; } } @@ -425,10 +433,13 @@ impl ContextManager { canvases: &mut FnvIndexMap, ) { // only pop up the menu if the primary key hit is the menu key (search just the first entry of keys); reject multi-key hits - if keys[0] == '∴' { + // only pop up the menu if it isn't already popped up + if keys[0] == '∴' && (self.focused_context != self.main_menu_app_token) { if let Some(menu_token) = self.find_app_token_by_name(MAIN_MENU_NAME) { // set the menu to the active context self.activate(gfx, canvases, menu_token, false); + // don't pass the initial key hit back to the menu app, just eat it and return + return; } } @@ -595,13 +606,13 @@ fn xmain() -> ! { if elapsed_time - last_time > 33 { // rate limit updates, no point in going faster than the eye can see last_time = elapsed_time; - deface(&gfx, &mut canvases); + deface(&gfx, &trng, &mut canvases); log::trace!("flushing..."); gfx.flush().expect("couldn't flush buffer to screen"); - /* // this throws errors right now because deface() doesn't work. + for (_, c) in canvases.iter_mut() { c.do_flushed(); - }*/ + } } }) } diff --git a/services/gam/src/menu.rs b/services/gam/src/menu.rs index df962988c..2b14e0087 100755 --- a/services/gam/src/menu.rs +++ b/services/gam/src/menu.rs @@ -86,7 +86,7 @@ impl Menu { RoundedRectangle::new( Rectangle::new_with_style(Point::new(0, 0), canvas_size, DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1) - ), 10 + ), 5 )).unwrap(); } pub fn key_event(&mut self, keys: [char; 4]) { @@ -94,6 +94,7 @@ impl Menu { log::trace!("got key '{}'", k); match k { '∴' => { + log::info!("relinquishing focus"); self.gam.relinquish_focus().expect("couldn't relinquish focus of the menu!"); }, '←' => { diff --git a/services/ime-frontend/src/main.rs b/services/ime-frontend/src/main.rs index 994146e72..b9d58edb7 100644 --- a/services/ime-frontend/src/main.rs +++ b/services/ime-frontend/src/main.rs @@ -34,6 +34,8 @@ struct InputTracker { /// our current prediction engine predictor: Option, + /// the name & token of our engine, so we can disconnect later on + pub predictor_conn: Option<(String::<64>, [u32; 4])>, /// cached copy of the predictor's triggers for predictions. Only valid if predictor is not None pred_triggers: Option, /// set if we're in a state where a backspace should trigger an unpredict @@ -66,6 +68,7 @@ impl InputTracker { input_canvas: None, pred_canvas: None, predictor: None, + predictor_conn: None, pred_triggers: None, gam_token: None, can_unpick: false, @@ -82,10 +85,15 @@ impl InputTracker { pub fn set_gam_token(&mut self, token: [u32; 4]) { self.gam_token = Some(token); } - pub fn set_predictor(&mut self, predictor: PredictionPlugin) { - self.predictor = Some(predictor); - self.pred_triggers = Some(predictor.get_prediction_triggers() - .expect("InputTracker failed to get prediction triggers from plugin")); + pub fn set_predictor(&mut self, predictor: Option) { + self.predictor = predictor; + if let Some(pred) = predictor { + self.pred_triggers = Some(pred.get_prediction_triggers() + .expect("InputTracker failed to get prediction triggers from plugin")); + } + } + pub fn get_predictor(&self) -> Option { + self.predictor } pub fn set_input_canvas(&mut self, input: Gid) { self.input_canvas = Some(input); @@ -621,10 +629,25 @@ fn xmain() -> ! { } else { tracker.clear_pred_canvas(); } + // disconnect any existing predictor, if we have one already + if let Some(_pred) = tracker.get_predictor() { + if let Some((name, token)) = tracker.predictor_conn { + xns.disconnect_with_token(name.as_str().unwrap(), token) + .expect("couldn't disconnect from previous predictor. Something is wrong with internal state!"); + } + tracker.predictor_conn = None; + tracker.set_predictor(None); + } if let Some(s) = descriptor.predictor { log::trace!("got prediction server: {}", s.as_str().unwrap()); - match xns.request_connection(s.as_str().unwrap()) { - Ok(pc) => tracker.set_predictor(ime_plugin_api::PredictionPlugin {connection: Some(pc)}), + match xns.request_connection_with_token(s.as_str().unwrap()) { + Ok((pc, token)) => { + tracker.set_predictor( Some(ime_plugin_api::PredictionPlugin {connection: Some(pc)}) ); + tracker.predictor_conn = Some( + (String::<64>::from_str(s.as_str().unwrap()), + token.expect("didn't get the disconnect token!")) + ); + }, _ => error!("can't find predictive engine {}, retaining existing one.", s.as_str().unwrap()), } } diff --git a/services/shellchat/src/main.rs b/services/shellchat/src/main.rs index f8fc6c07e..df7321461 100644 --- a/services/shellchat/src/main.rs +++ b/services/shellchat/src/main.rs @@ -66,7 +66,7 @@ impl Repl{ }).expect("couldn't register Ux context for shellchat"); // we should be the first app running, so get the focus - gam.request_focus(token.unwrap()); + gam.request_focus(token.unwrap()).expect("couldn't take focus"); let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas"); log::debug!("content canvas {:?}", content); diff --git a/services/xous-names/src/api.rs b/services/xous-names/src/api.rs index d522b22a7..72e5a91ae 100644 --- a/services/xous-names/src/api.rs +++ b/services/xous-names/src/api.rs @@ -13,6 +13,8 @@ pub(crate) enum Opcode { AuthenticatedLookup, /// unregister a server, given its cryptographically unique SID. Unregister, + /// disconnect, given a server name and a cryptographically unique, one-time use token + Disconnect, /// indicates if all inherentely trusted slots have been occupied. Should not run untrusted code until this is the case. TrustedInitDone, } @@ -25,8 +27,10 @@ pub(crate) enum Return { Failure, /// A server was successfully created with the given SID SID([u32; 4]), - /// A connection was successfully made with the given CID - CID(xous::CID), + /// A connection was successfully made with the given CID; an optional "disconnect token" is provided + CID((xous::CID, Option<[u32; 4]>)), + /// Operation requested was otherwise successful (currently only used by disconnect to ack the disconnect) + Success, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] @@ -35,6 +39,12 @@ pub(crate) struct Registration { pub conn_limit: Option, } +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct Disconnect { + pub name: xous_ipc::String::<64>, + pub token: [u32; 4], +} + #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] pub(crate) struct AuthenticatedLookup { pub name: xous_ipc::String::<64>, diff --git a/services/xous-names/src/lib.rs b/services/xous-names/src/lib.rs index 1353c0388..cf674c100 100644 --- a/services/xous-names/src/lib.rs +++ b/services/xous-names/src/lib.rs @@ -3,6 +3,7 @@ pub mod api; use core::fmt::Write; +use api::Disconnect; use xous_ipc::{String, Buffer}; use num_traits::ToPrimitive; @@ -70,6 +71,40 @@ impl XousNames { } } + pub fn request_connection_with_token(&self, name: &str) -> Result<(xous::CID, Option<[u32; 4]>), xous::Error> { + let mut lookup_name = xous_ipc::String::<64>::new(); + write!(lookup_name, "{}", name).expect("name problably too long"); + let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?; + + buf.lend_mut( + self.conn, + api::Opcode::Lookup.to_u32().unwrap() + ) + .or(Err(xous::Error::InternalError))?; + + match buf.to_original().unwrap() { + api::Return::CID((cid, token)) => Ok((cid, token)), + // api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied), + _ => Err(xous::Error::ServerNotFound), + } + } + pub fn disconnect_with_token(&self, name: &str, token: [u32; 4]) -> Result<(), xous::Error> { + let disconnect = Disconnect { + name: String::<64>::from_str(name), + token, + }; + let mut buf = Buffer::into_buf(disconnect).or(Err(xous::Error::InternalError))?; + buf.lend_mut( + self.conn, + api::Opcode::Disconnect.to_u32().unwrap() + ).or(Err(xous::Error::InternalError))?; + + match buf.to_original().unwrap() { + api::Return::Success => Ok(()), + _ => Err(xous::Error::ServerNotFound), + } + } + pub fn request_connection(&self, name: &str) -> Result { let mut lookup_name = xous_ipc::String::<64>::new(); write!(lookup_name, "{}", name).expect("name problably too long"); @@ -83,7 +118,7 @@ impl XousNames { .or(Err(xous::Error::InternalError))?; match buf.to_original().unwrap() { - api::Return::CID(cid) => Ok(cid), + api::Return::CID((cid, _)) => Ok(cid), // api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied), _ => Err(xous::Error::ServerNotFound), } diff --git a/services/xous-names/src/main.rs b/services/xous-names/src/main.rs index 01c90cd06..469620af8 100644 --- a/services/xous-names/src/main.rs +++ b/services/xous-names/src/main.rs @@ -81,6 +81,7 @@ struct Connection { pub max_conns: Option, // if None, unlimited connections allowed pub allow_authenticate: bool, pub auth_conns: u32, // number of authenticated connections + pub token: Option<[u32; 4]>, // a random number that must be presented to allow for disconnection for single-connection servers } struct SlowMap { pub map: [Option; 128], @@ -93,6 +94,12 @@ impl SlowMap { } pub fn insert(&mut self, name: XousServerName, sid: xous::SID, max_conns: Option) -> Result<(), xous::Error> { let mut ok = false; + let token = if max_conns == Some(1) { + // for the special case of 1-connection servers, provision a one-time use token for disconnects + Some(xous::create_server_id().expect("couldn't create token").to_array()) + } else { + None + }; for entry in self.map.iter_mut() { if entry.is_none() { *entry = Some(Connection { @@ -102,6 +109,7 @@ impl SlowMap { max_conns, allow_authenticate: false, // for now, we don't support authenticated connections auth_conns: 0, + token, }); ok = true; break; @@ -136,26 +144,35 @@ impl SlowMap { } return false } - pub fn connect(&mut self, name: &XousServerName) -> Option<&xous::SID> { + pub fn connect(&mut self, name: &XousServerName) -> (Option<&xous::SID>, Option<[u32; 4]>) { for maybe_entry in self.map.iter_mut() { if let Some(entry) = maybe_entry { if *name == entry.name { + if Some(1) == entry.max_conns { + // single-connection case + if entry.current_conns < 1 { + (*entry).current_conns = 1; + return (Some(&entry.sid), entry.token) + } else { + return (None, None) + } + } if let Some(max) = entry.max_conns { if entry.current_conns < max { (*entry).current_conns += 1; - return Some(&entry.sid); + return (Some(&entry.sid), None); } else { - return None; + return (None, None); } } else { // unlimited connections allowed (*entry).current_conns += 1; - return Some(&entry.sid); + return (Some(&entry.sid), None); } } } } - None + (None, None) } pub fn trusted_init_done(&self) -> bool { let mut trusted_done = true; @@ -189,6 +206,23 @@ impl SlowMap { } None } + // this is a safer version of disconnect. we track servers that allow exactly one connection at a time + // and give them a one-time-use token that a connector can use to disconnect. + pub fn disconnect_with_token(&mut self, name: &XousServerName, token: [u32; 4]) -> bool { + for maybe_entry in self.map.iter_mut() { + if let Some(entry) = maybe_entry { + if let Some(old_token) = entry.token { + if (*name == entry.name) && (token == old_token) && (entry.current_conns == 1) { + (*entry).current_conns = 0; + // generate the token -- we should never re-use these! + (*entry).token = Some(xous::create_server_id().expect("couldn't create token").to_array()); + return true + } + } + } + } + false + } } #[xous::xous_main] @@ -254,7 +288,7 @@ fn xmain() -> ! { let name = XousServerName::from_str(name_string.as_str().expect("couldn't convert server name to string")); log::trace!("Lookup request for '{}'", name); let response: api::Return; - if let Some(server_sid) = name_table.connect(&name) { + if let (Some(server_sid), token) = name_table.connect(&name) { let sender_pid = msg .sender .pid() @@ -264,7 +298,7 @@ fn xmain() -> ! { { xous::Result::ConnectionID(connection_id) => { log::trace!("lookup success, returning connection {}", connection_id); - response = api::Return::CID(connection_id) + response = api::Return::CID((connection_id, token)) } _ => { log::debug!( @@ -317,6 +351,18 @@ fn xmain() -> ! { xous::return_scalar(msg.sender, 0).expect("couldn't return trusted_init_done"); } } + Some(api::Opcode::Disconnect) => { + let mem = msg.body.memory_message_mut().unwrap(); + let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) }; + let disconnect = buffer.to_original::().unwrap(); + let name = XousServerName::from_str(disconnect.name.as_str().unwrap()); + let response = if name_table.disconnect_with_token(&name, disconnect.token) { + api::Return::Success + } else { + api::Return::Failure + }; + buffer.replace(response).expect("Can't return buffer"); + } None => {error!("couldn't decode message: {:?}", msg); break} } }