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.
This commit is contained in:
bunnie 2021-06-18 16:20:56 +08:00
parent 62c9737bbc
commit 0f937037e4
8 changed files with 153 additions and 26 deletions

View file

@ -145,7 +145,7 @@ impl PartialEq for Canvas {
impl Eq for Canvas {} impl Eq for Canvas {}
pub fn deface(gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<(), xous::Error> { pub fn deface(gfx: &graphics_server::Gfx, tng: &trng::Trng, canvases: &mut FnvIndexMap<Gid, Canvas, 32>) -> Result<(), xous::Error> {
// first check if any need defacing, if not, then we're done // first check if any need defacing, if not, then we're done
let mut needs_defacing = false; let mut needs_defacing = false;
for (_, c) in canvases.iter() { for (_, c) in canvases.iter() {
@ -163,11 +163,12 @@ pub fn deface(gfx: &graphics_server::Gfx, canvases: &mut FnvIndexMap<Gid, Canvas
in between states, so in the worst case we are drawing defacement with a rectangular clip in between states, so in the worst case we are drawing defacement with a rectangular clip
area open in the middle of a canvas... area open in the middle of a canvas...
*/ */
//Err(xous::Error::InternalError)
// temporarirly clear the error so we can develop other features // temporarirly clear the error so we can develop other features
for (_, c) in canvases.iter_mut() { for (_, c) in canvases.iter_mut() {
if c.needs_defacing() { if c.needs_defacing() {
// do the actual defacing
// indicate that the defacement has happened to the canvas state machine
c.do_defaced(); c.do_defaced();
} }
} }

View file

@ -94,7 +94,7 @@ pub(crate) struct UxContext {
} }
const MAX_UX_CONTEXTS: usize = 4; const MAX_UX_CONTEXTS: usize = 4;
pub(crate) const MAX_CANVASES: usize = 32; pub(crate) const MAX_CANVASES: usize = 32;
const BOOT_APP_NAME: &'static str = "shellchat"; // this is the app to display on boot // const BOOT_APP_NAME: &'static str = "shellchat"; // this is the app to display on boot -- we will eventually need this once we have more than one app?
pub const MAIN_MENU_NAME: &'static str = "main menu"; pub const MAIN_MENU_NAME: &'static str = "main menu";
const BOOT_CONTEXT_TRUSTLEVEL: u8 = 254; const BOOT_CONTEXT_TRUSTLEVEL: u8 = 254;
@ -113,6 +113,7 @@ struct ContextManager {
imef: ime_plugin_api::ImeFrontEnd, imef: ime_plugin_api::ImeFrontEnd,
imef_active: bool, imef_active: bool,
kbd: keyboard::Keyboard, kbd: keyboard::Keyboard,
main_menu_app_token: Option<[u32; 4]>, // app_token of the main menu, if it has been registered
} }
impl ContextManager { impl ContextManager {
pub fn new(xns: &xous_names::XousNames) -> Self { pub fn new(xns: &xous_names::XousNames) -> Self {
@ -131,6 +132,7 @@ impl ContextManager {
imef, imef,
imef_active: false, imef_active: false,
kbd, kbd,
main_menu_app_token: None,
} }
} }
pub(crate) fn claim_token(&mut self, name: &str) -> Option<[u32; 4]> { pub(crate) fn claim_token(&mut self, name: &str) -> Option<[u32; 4]> {
@ -203,6 +205,12 @@ impl ContextManager {
if maybe_context.is_none() { if maybe_context.is_none() {
*maybe_context = Some(ux_context); *maybe_context = Some(ux_context);
found_slot = true; 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; break;
} }
} }
@ -425,10 +433,13 @@ impl ContextManager {
canvases: &mut FnvIndexMap<Gid, Canvas, MAX_CANVASES>, canvases: &mut FnvIndexMap<Gid, Canvas, MAX_CANVASES>,
) { ) {
// 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 // 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) { if let Some(menu_token) = self.find_app_token_by_name(MAIN_MENU_NAME) {
// set the menu to the active context // set the menu to the active context
self.activate(gfx, canvases, menu_token, false); 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 if elapsed_time - last_time > 33 { // rate limit updates, no point in going faster than the eye can see
last_time = elapsed_time; last_time = elapsed_time;
deface(&gfx, &mut canvases); deface(&gfx, &trng, &mut canvases);
log::trace!("flushing..."); log::trace!("flushing...");
gfx.flush().expect("couldn't flush buffer to screen"); 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() { for (_, c) in canvases.iter_mut() {
c.do_flushed(); c.do_flushed();
}*/ }
} }
}) })
} }

View file

@ -86,7 +86,7 @@ impl Menu {
RoundedRectangle::new( RoundedRectangle::new(
Rectangle::new_with_style(Point::new(0, 0), canvas_size, Rectangle::new_with_style(Point::new(0, 0), canvas_size,
DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1) DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1)
), 10 ), 5
)).unwrap(); )).unwrap();
} }
pub fn key_event(&mut self, keys: [char; 4]) { pub fn key_event(&mut self, keys: [char; 4]) {
@ -94,6 +94,7 @@ impl Menu {
log::trace!("got key '{}'", k); log::trace!("got key '{}'", k);
match k { match k {
'∴' => { '∴' => {
log::info!("relinquishing focus");
self.gam.relinquish_focus().expect("couldn't relinquish focus of the menu!"); self.gam.relinquish_focus().expect("couldn't relinquish focus of the menu!");
}, },
'←' => { '←' => {

View file

@ -34,6 +34,8 @@ struct InputTracker {
/// our current prediction engine /// our current prediction engine
predictor: Option<PredictionPlugin>, predictor: Option<PredictionPlugin>,
/// 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 /// cached copy of the predictor's triggers for predictions. Only valid if predictor is not None
pred_triggers: Option<PredictionTriggers>, pred_triggers: Option<PredictionTriggers>,
/// set if we're in a state where a backspace should trigger an unpredict /// set if we're in a state where a backspace should trigger an unpredict
@ -66,6 +68,7 @@ impl InputTracker {
input_canvas: None, input_canvas: None,
pred_canvas: None, pred_canvas: None,
predictor: None, predictor: None,
predictor_conn: None,
pred_triggers: None, pred_triggers: None,
gam_token: None, gam_token: None,
can_unpick: false, can_unpick: false,
@ -82,10 +85,15 @@ impl InputTracker {
pub fn set_gam_token(&mut self, token: [u32; 4]) { pub fn set_gam_token(&mut self, token: [u32; 4]) {
self.gam_token = Some(token); self.gam_token = Some(token);
} }
pub fn set_predictor(&mut self, predictor: PredictionPlugin) { pub fn set_predictor(&mut self, predictor: Option<PredictionPlugin>) {
self.predictor = Some(predictor); self.predictor = predictor;
self.pred_triggers = Some(predictor.get_prediction_triggers() if let Some(pred) = predictor {
.expect("InputTracker failed to get prediction triggers from plugin")); self.pred_triggers = Some(pred.get_prediction_triggers()
.expect("InputTracker failed to get prediction triggers from plugin"));
}
}
pub fn get_predictor(&self) -> Option<PredictionPlugin> {
self.predictor
} }
pub fn set_input_canvas(&mut self, input: Gid) { pub fn set_input_canvas(&mut self, input: Gid) {
self.input_canvas = Some(input); self.input_canvas = Some(input);
@ -621,10 +629,25 @@ fn xmain() -> ! {
} else { } else {
tracker.clear_pred_canvas(); 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 { if let Some(s) = descriptor.predictor {
log::trace!("got prediction server: {}", s.as_str().unwrap()); log::trace!("got prediction server: {}", s.as_str().unwrap());
match xns.request_connection(s.as_str().unwrap()) { match xns.request_connection_with_token(s.as_str().unwrap()) {
Ok(pc) => tracker.set_predictor(ime_plugin_api::PredictionPlugin {connection: Some(pc)}), 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()), _ => error!("can't find predictive engine {}, retaining existing one.", s.as_str().unwrap()),
} }
} }

View file

@ -66,7 +66,7 @@ impl Repl{
}).expect("couldn't register Ux context for shellchat"); }).expect("couldn't register Ux context for shellchat");
// we should be the first app running, so get the focus // 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"); let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas");
log::debug!("content canvas {:?}", content); log::debug!("content canvas {:?}", content);

View file

@ -13,6 +13,8 @@ pub(crate) enum Opcode {
AuthenticatedLookup, AuthenticatedLookup,
/// unregister a server, given its cryptographically unique SID. /// unregister a server, given its cryptographically unique SID.
Unregister, 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. /// indicates if all inherentely trusted slots have been occupied. Should not run untrusted code until this is the case.
TrustedInitDone, TrustedInitDone,
} }
@ -25,8 +27,10 @@ pub(crate) enum Return {
Failure, Failure,
/// A server was successfully created with the given SID /// A server was successfully created with the given SID
SID([u32; 4]), SID([u32; 4]),
/// A connection was successfully made with the given CID /// A connection was successfully made with the given CID; an optional "disconnect token" is provided
CID(xous::CID), 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)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
@ -35,6 +39,12 @@ pub(crate) struct Registration {
pub conn_limit: Option<u32>, pub conn_limit: Option<u32>,
} }
#[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)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct AuthenticatedLookup { pub(crate) struct AuthenticatedLookup {
pub name: xous_ipc::String::<64>, pub name: xous_ipc::String::<64>,

View file

@ -3,6 +3,7 @@
pub mod api; pub mod api;
use core::fmt::Write; use core::fmt::Write;
use api::Disconnect;
use xous_ipc::{String, Buffer}; use xous_ipc::{String, Buffer};
use num_traits::ToPrimitive; 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<xous::CID, xous::Error> { pub fn request_connection(&self, name: &str) -> Result<xous::CID, xous::Error> {
let mut lookup_name = xous_ipc::String::<64>::new(); let mut lookup_name = xous_ipc::String::<64>::new();
write!(lookup_name, "{}", name).expect("name problably too long"); write!(lookup_name, "{}", name).expect("name problably too long");
@ -83,7 +118,7 @@ impl XousNames {
.or(Err(xous::Error::InternalError))?; .or(Err(xous::Error::InternalError))?;
match buf.to_original().unwrap() { match buf.to_original().unwrap() {
api::Return::CID(cid) => Ok(cid), api::Return::CID((cid, _)) => Ok(cid),
// api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied), // api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied),
_ => Err(xous::Error::ServerNotFound), _ => Err(xous::Error::ServerNotFound),
} }

View file

@ -81,6 +81,7 @@ struct Connection {
pub max_conns: Option<u32>, // if None, unlimited connections allowed pub max_conns: Option<u32>, // if None, unlimited connections allowed
pub allow_authenticate: bool, pub allow_authenticate: bool,
pub auth_conns: u32, // number of authenticated connections 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 { struct SlowMap {
pub map: [Option<Connection>; 128], pub map: [Option<Connection>; 128],
@ -93,6 +94,12 @@ impl SlowMap {
} }
pub fn insert(&mut self, name: XousServerName, sid: xous::SID, max_conns: Option<u32>) -> Result<(), xous::Error> { pub fn insert(&mut self, name: XousServerName, sid: xous::SID, max_conns: Option<u32>) -> Result<(), xous::Error> {
let mut ok = false; 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() { for entry in self.map.iter_mut() {
if entry.is_none() { if entry.is_none() {
*entry = Some(Connection { *entry = Some(Connection {
@ -102,6 +109,7 @@ impl SlowMap {
max_conns, max_conns,
allow_authenticate: false, // for now, we don't support authenticated connections allow_authenticate: false, // for now, we don't support authenticated connections
auth_conns: 0, auth_conns: 0,
token,
}); });
ok = true; ok = true;
break; break;
@ -136,26 +144,35 @@ impl SlowMap {
} }
return false 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() { for maybe_entry in self.map.iter_mut() {
if let Some(entry) = maybe_entry { if let Some(entry) = maybe_entry {
if *name == entry.name { 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 let Some(max) = entry.max_conns {
if entry.current_conns < max { if entry.current_conns < max {
(*entry).current_conns += 1; (*entry).current_conns += 1;
return Some(&entry.sid); return (Some(&entry.sid), None);
} else { } else {
return None; return (None, None);
} }
} else { } else {
// unlimited connections allowed // unlimited connections allowed
(*entry).current_conns += 1; (*entry).current_conns += 1;
return Some(&entry.sid); return (Some(&entry.sid), None);
} }
} }
} }
} }
None (None, None)
} }
pub fn trusted_init_done(&self) -> bool { pub fn trusted_init_done(&self) -> bool {
let mut trusted_done = true; let mut trusted_done = true;
@ -189,6 +206,23 @@ impl SlowMap {
} }
None 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] #[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")); let name = XousServerName::from_str(name_string.as_str().expect("couldn't convert server name to string"));
log::trace!("Lookup request for '{}'", name); log::trace!("Lookup request for '{}'", name);
let response: api::Return; 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 let sender_pid = msg
.sender .sender
.pid() .pid()
@ -264,7 +298,7 @@ fn xmain() -> ! {
{ {
xous::Result::ConnectionID(connection_id) => { xous::Result::ConnectionID(connection_id) => {
log::trace!("lookup success, returning connection {}", 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!( log::debug!(
@ -317,6 +351,18 @@ fn xmain() -> ! {
xous::return_scalar(msg.sender, 0).expect("couldn't return trusted_init_done"); 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::<Disconnect, _>().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} None => {error!("couldn't decode message: {:?}", msg); break}
} }
} }