menu Ux is now nominally doing something menu-like

This commit is contained in:
bunnie 2021-06-18 19:35:03 +08:00
parent 65cc8dd90c
commit 769c90764c
6 changed files with 182 additions and 30 deletions

View file

@ -17,9 +17,19 @@ pub struct GamObject {
pub obj: GamObjectType,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone, Eq, PartialEq)]
pub enum TokenType {
/// GAM tokens are for objects that the GAM delegates to do app logic.
/// this is different to prevent delegated apps from masquerading as the app itself
Gam,
/// App token is a token given to the app and only the app to identify itself to the Gam
/// for any requests
App,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct SetCanvasBoundsRequest {
pub token: [u32; 4],
pub token_type: TokenType,
pub requested: Point,
pub granted: Option<Point>,
}
@ -118,13 +128,8 @@ pub(crate) enum Opcode {
/// request an app to take the focus
RequestFocus,
/////// planned
// hides a canvas with a given GID
//HideCanvas(Gid),
// indicates if the current UI layout requires an input field
//HasInput(bool),
/// pass-through to get glyph heights to assist with layout planning, without having to create a gfx connection
QueryGlyphProps,
Quit,
}

View file

@ -175,14 +175,14 @@ pub(crate) struct MenuLayout {
menu_x_pad: i16,
menu_min_height: i16,
screensize: Point,
small_height: i16,
height: i16,
visible: bool,
}
impl MenuLayout {
pub fn init(gfx: &graphics_server::Gfx, trng: &trng::Trng, base_trust: u8, canvases: &mut FnvIndexMap<Gid, Canvas, {crate::MAX_CANVASES}>) -> Result<MenuLayout, xous::Error> {
let screensize = gfx.screen_size().expect("Couldn't get screen size");
// get the height of various text regions to compute the layout
let small_height: i16 = gfx.glyph_height_hint(GlyphStyle::Small).expect("couldn't get glyph height") as i16;
let height: i16 = gfx.glyph_height_hint(GlyphStyle::Regular).expect("couldn't get glyph height") as i16;
let checked_base_trust = if base_trust < 4 {
4
@ -195,7 +195,7 @@ impl MenuLayout {
// build for an initial size of 1 entry
// base trust - 1 so that status bar can always ride on top
let menu_canvas = Canvas::new(
Rectangle::new_coords(MENU_X_PAD, MENU_Y_PAD, screensize.x - MENU_X_PAD, MENU_Y_PAD + small_height),
Rectangle::new_coords(MENU_X_PAD, MENU_Y_PAD, screensize.x - MENU_X_PAD, MENU_Y_PAD + height),
checked_base_trust - 1, &trng, None
).expect("couldn't create menu canvas");
canvases.insert(menu_canvas.gid(), menu_canvas).expect("can't store menu canvas");
@ -204,9 +204,9 @@ impl MenuLayout {
menu: menu_canvas.gid(),
menu_y_pad: MENU_Y_PAD,
menu_x_pad: MENU_X_PAD,
menu_min_height: small_height,
menu_min_height: height,
screensize,
small_height,
height,
visible: true,
})
}
@ -219,24 +219,25 @@ impl LayoutApi for MenuLayout {
let menu_canvas = canvases.get(&self.menu).expect("couldn't find menu canvas");
let mut rect = menu_canvas.clip_rect();
rect.style = DrawStyle {fill_color: Some(PixelColor::Dark), stroke_color: None, stroke_width: 0,};
rect.style = DrawStyle {fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0,};
gfx.draw_rectangle(rect)
}
fn resize_height(&mut self, gfx: &graphics_server::Gfx, new_height: i16, _status_canvas: &Canvas, canvases: &mut FnvIndexMap<Gid, Canvas, {crate::MAX_CANVASES}>) -> Result<Point, xous::Error> {
let menu_canvas = canvases.get_mut(&self.menu).expect("couldn't find menu canvas");
let orig_rect = menu_canvas.clip_rect();
let mut height: i16 = if new_height < self.menu_min_height {
self.menu_min_height
self.menu_min_height + self.menu_y_pad
} else {
new_height
new_height + self.menu_y_pad
};
if new_height > self.screensize.y - self.menu_y_pad {
if height > self.screensize.y - self.menu_y_pad {
height = self.screensize.y - self.menu_y_pad;
}
let mut menu_clip_rect = Rectangle::new_coords(self.menu_x_pad, self.menu_y_pad, self.screensize.x - self.menu_x_pad, height);
let mut menu_clip_rect = Rectangle::new_coords(orig_rect.tl().x, self.menu_y_pad, orig_rect.br().x, height);
menu_clip_rect.style = DrawStyle {fill_color: Some(PixelColor::Dark), stroke_color: None, stroke_width: 0,};
menu_canvas.set_clip(menu_clip_rect);
gfx.draw_rectangle(menu_clip_rect).expect("can't clear menu");
// gfx.draw_rectangle(menu_clip_rect).expect("can't clear menu");
Ok(menu_clip_rect.br)
}
fn get_content_canvas(&self) -> Gid {

View file

@ -6,6 +6,7 @@ pub use api::*;
use graphics_server::api::{TextOp, TextView};
use graphics_server::api::{Point, Gid, Line, Rectangle, Circle, RoundedRectangle, TokenClaim};
pub use graphics_server::GlyphStyle;
use api::Opcode; // if you prefer to map the api into your local namespace
use xous::{send_message, CID, Message};
@ -28,7 +29,7 @@ impl Gam {
callback_sid: None,
})
}
pub fn conn(&self) -> CID { self.conn }
pub fn redraw(&self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::Redraw.to_usize().unwrap(), 0, 0, 0, 0)
@ -234,6 +235,18 @@ impl Gam {
token[0] as usize, token[1] as usize, token[2] as usize, token[3] as usize,)
).map(|_| ())
}
pub fn glyph_height_hint(&self, glyph: GlyphStyle) -> Result<usize, xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::QueryGlyphProps.to_usize().unwrap(),
glyph as usize, 0, 0, 0,)
).expect("QueryGlyphProps failed");
if let xous::Result::Scalar1(h) = response {
Ok(h)
} else {
panic!("unexpected return value: {:#?}", response);
}
}
}
use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -256,6 +256,24 @@ impl ContextManager {
}
None
}
// hmmm...feels wrong to have basically a dupe of the above. Maybe this abstraction needs to be cleaned up a bit.
pub(crate) fn set_canvas_height_app_token(&mut self,
gfx: &graphics_server::Gfx,
app_token: [u32; 4],
new_height: i16,
status_canvas: &Canvas,
canvases: &mut FnvIndexMap<Gid, Canvas, MAX_CANVASES>) -> Option<Point> {
for maybe_context in self.contexts.iter_mut() {
if let Some(context) = maybe_context {
if context.app_token == app_token {
let result = context.layout.resize_height(gfx, new_height, status_canvas, canvases).expect("couldn't adjust height of active Ux context");
return Some(result)
}
}
}
None
}
fn get_context_by_token_mut(&'_ mut self, token: [u32; 4]) -> Option<&'_ mut UxContext> {
for maybe_context in self.contexts.iter_mut() {
if let Some(context) = maybe_context {
@ -682,10 +700,14 @@ fn xmain() -> ! {
let mut cb = buffer.to_original::<SetCanvasBoundsRequest, _>().unwrap();
log::debug!("SetCanvasBoundsRequest {:?}", cb);
let granted = context_mgr.set_canvas_height(&gfx, cb.token, cb.requested.y, &status_canvas, &mut canvases);
let granted = if cb.token_type == TokenType::Gam {
context_mgr.set_canvas_height(&gfx, cb.token, cb.requested.y, &status_canvas, &mut canvases)
} else {
context_mgr.set_canvas_height_app_token(&gfx, cb.token, cb.requested.y, &status_canvas, &mut canvases)
};
if granted.is_some() {
// recompute the canvas orders based on the new layout
let mut recomp_canvases = recompute_canvases(&canvases, Rectangle::new(Point::new(0, 0), screensize));
let recomp_canvases = recompute_canvases(&canvases, Rectangle::new(Point::new(0, 0), screensize));
canvases = recomp_canvases;
context_mgr.redraw().expect("can't redraw after new canvas bounds");
}
@ -834,16 +856,17 @@ fn xmain() -> ! {
// this is a blocking scalar, so return /something/ so we know to move on
xous::return_scalar(msg.sender, 1).expect("couldn't confirm focus activation");
}),
Some(Opcode::QueryGlyphProps) => msg_blocking_scalar_unpack!(msg, style, _, _, _, {
let height = gfx.glyph_height_hint(GlyphStyle::from(style)).expect("couldn't query glyph height from gfx");
xous::return_scalar(msg.sender, height).expect("could not return QueryGlyphProps request");
}),
Some(Opcode::Quit) => break,
None => {log::error!("unhandled message {:?}", msg);}
}
/*
// if we don't have a focused app, try and find the default boot app and bring it to focus.
if context_mgr.focused_app().is_none() {
if let Some(shellchat_token) = context_mgr.find_app_token_by_name(BOOT_APP_NAME) {
context_mgr.activate(&gfx, &mut canvases, shellchat_token, true);
}
}*/
// we don't currently have a mechanism to guarantee that the default app has focus
// right now, it just depends upon it requesting focus, and none others taking it.
// probably something should be inserted around here to take care of that?
}
// clean up our program
log::trace!("main loop exit, destroying servers");

View file

@ -1,3 +1,4 @@
use gam::SetCanvasBoundsRequest;
use xous_ipc::*;
use graphics_server::*;
use num_traits::*;
@ -30,6 +31,8 @@ pub struct Menu {
pub index: usize, // currently selected item
pub canvas: Gid,
pub authtoken: [u32; 4],
pub margin: i16,
pub divider_margin: i16,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
@ -66,28 +69,108 @@ impl Menu {
index: 0,
canvas,
authtoken: authtoken.unwrap(),
margin: 4,
divider_margin: 20,
}
}
// if successful, returns None, otherwise, the menu item
pub fn add_item(&mut self, new_item: MenuItem) -> Option<MenuItem> {
// first, do the insertion.
// add the menu item to the first free slot
// any modifications to the menu structure should guarantee that the list is compacted
// and has no holes, in order for the "selected index" logic to work
let mut success = false;
for item in self.items.iter_mut() {
if item.is_none() {
*item = Some(new_item);
return None;
success = true;
break;
}
}
Some(new_item)
if success {
// now, recompute the height
let mut total_items = 0;
for item in self.items.iter() {
if item.is_some() {
total_items += 1;
}
}
if total_items == 0 {
total_items = 1; // just so we see a blank menu at least, and have a clue how to debug
}
let line_height = self.gam.glyph_height_hint(gam::GlyphStyle::Regular).expect("couldn't get glyph height hint");
let current_bounds = self.gam.get_canvas_bounds(self.canvas).expect("couldn't get current bounds");
let mut new_bounds = SetCanvasBoundsRequest {
requested: Point::new(current_bounds.x, (total_items * line_height + self.margin as usize * 2) as i16),
granted: None,
token_type: gam::TokenType::App,
token: self.authtoken,
};
log::debug!("add_item requesting bounds of {:?}", new_bounds);
self.gam.set_canvas_bounds_request(&mut new_bounds).expect("couldn't call set bounds");
None
} else {
Some(new_item)
}
}
pub fn redraw(&mut self) {
use core::fmt::Write;
// for now, just draw a black rectangle
log::trace!("menu redraw");
let canvas_size = self.gam.get_canvas_bounds(self.canvas).unwrap();
let line_height = self.gam.glyph_height_hint(gam::GlyphStyle::Regular).expect("couldn't get glyph height hint") as i16;
// draw the outer border
self.gam.draw_rounded_rectangle(self.canvas,
RoundedRectangle::new(
Rectangle::new_with_style(Point::new(0, 0), canvas_size,
DrawStyle::new(PixelColor::Light, PixelColor::Dark, 3)
), 5
)).unwrap();
// draw the line items
// we require that the items list be in index-order, with no holes: we abort at the first None item
let mut cur_index: i16 = 0;
let mut first_item = true;
for maybe_item in self.items.iter() {
if let Some(item) = maybe_item {
let mut item_tv = TextView::new(
self.canvas,
TextBounds::BoundingBox(Rectangle::new(
Point::new(self.margin, cur_index * line_height + self.margin as i16),
Point::new(canvas_size.x - self.margin, (cur_index + 1) * line_height + self.margin as i16),
)));
if self.index == cur_index as usize {
write!(item_tv.text, " • ").unwrap();
} else {
write!(item_tv.text, " ").unwrap();
}
write!(item_tv.text, "{}", item.name.as_str().unwrap()).unwrap();
item_tv.draw_border = false;
item_tv.style = GlyphStyle::Small;
item_tv.margin = Point::new(0, 0);
item_tv.ellipsis = true;
self.gam.post_textview(&mut item_tv).expect("couldn't render menu list item");
if !first_item {
// draw a dividing line above this item
self.gam.draw_line(self.canvas, Line::new_with_style(
Point::new(self.divider_margin, cur_index * line_height + self.margin/2),
Point::new(canvas_size.x - self.divider_margin, cur_index * line_height + self.margin/2),
DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1))
).expect("couldn't draw dividing line")
}
cur_index += 1;
first_item = false;
} else {
break;
}
}
}
pub fn key_event(&mut self, keys: [char; 4]) {
for &k in keys.iter() {
@ -118,6 +201,31 @@ impl Menu {
/////// strictly speaking this doesn't have to be in this file, but we make it part of this server so we are guaranteed to have a main menu at all times
pub fn main_menu_thread() {
let mut menu = Menu::new(crate::MAIN_MENU_NAME);
let thing_item = MenuItem {
name: String::<64>::from_str("Do a thing"),
action_conn: menu.gam.conn(),
action_opcode: crate::Opcode::RevertFocus.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
};
menu.add_item(thing_item);
let another_item = MenuItem {
name: String::<64>::from_str("Another thing"),
action_conn: menu.gam.conn(),
action_opcode: crate::Opcode::RevertFocus.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
};
menu.add_item(another_item);
let close_item = MenuItem {
name: String::<64>::from_str("Close Menu"),
action_conn: menu.gam.conn(),
action_opcode: crate::Opcode::RevertFocus.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
};
menu.add_item(close_item);
loop {
let msg = xous::receive_message(menu.sid).unwrap();
log::trace!("|status: Message: {:?}", msg);

View file

@ -374,6 +374,7 @@ impl InputTracker {
let mut req = SetCanvasBoundsRequest {
requested: Point::new(0, 0), // size 0 will snap to the original smallest default size
granted: None,
token_type: gam::TokenType::Gam,
token: self.gam_token.unwrap(),
};
if debug1{info!("attempting resize to {:?}", req.requested);}
@ -480,6 +481,7 @@ impl InputTracker {
let mut req = SetCanvasBoundsRequest {
requested: Point::new(0, ic_bounds.y + delta as i16),
granted: None,
token_type: gam::TokenType::Gam,
token: self.gam_token.unwrap(),
};
if debug1{info!("attempting resize to {:?}", req.requested);}