it doesn't look that impressive, but there's a lot of plumbing now.

This commit is contained in:
bunnie 2021-03-06 01:10:18 +08:00
parent 5d1fba4015
commit 0cc1f9f5fb
14 changed files with 443 additions and 171 deletions

View file

@ -9,8 +9,6 @@ members = [
"services/log-server",
"services/ticktimer-server",
"services/com",
"services/llio",
"services/trng-tester",
"services/fcc-agent",
"services/xous-names",
"services/keyboard",
@ -26,18 +24,18 @@ members = [
"imports/blitstr-ref",
"imports/com_rs-ref",
"services/ime-plugin-api",
"services/llio",
"services/trng-tester",
]
default-members = [
"services/shell",
"services/log-server",
"services/graphics-server",
"services/ticktimer-server",
"services/trng-tester",
"services/fcc-agent",
"services/xous-names",
"services/keyboard",
"services/com",
"services/llio",
"services/trng",
"services/gam",
"imports/blitstr-ref",
@ -47,6 +45,8 @@ default-members = [
"services/benchmark-target",
"services/ime-frontend",
"services/ime-plugin-shell",
"services/llio",
"services/trng-tester",
]
# These packages have custom RUSTFLAGS, so if they

View file

@ -62,6 +62,7 @@ impl Canvas {
}
})
}
pub fn pan_offset(&self) -> Point { self.pan_offset }
pub fn clip_rect(&self) -> Rectangle { self.clip_rect }
pub fn gid(&self) -> Gid { self.gid }
pub fn trust_level(&self) -> u8 { self.trust_level }
@ -140,7 +141,7 @@ impl Eq for Canvas {}
// we use the "screen" parameter to determine when we can turn off drawing to canvases that are off-screen
pub fn recompute_canvases(canvases: FnvIndexMap<Gid, Canvas, U32>, screen: Rectangle) -> FnvIndexMap<Gid, Canvas, U32> {
let debug = false;
let debug = true;
// first, sort canvases by trust_level. Canvas implements ord/eq based on the trust_level attribute
// so jush pushing it into a max binary heap does the trick.
if debug { info!("CANVAS: recompute canvas"); }
@ -154,6 +155,7 @@ pub fn recompute_canvases(canvases: FnvIndexMap<Gid, Canvas, U32>, screen: Recta
let mut higher_clipregions: BinaryHeap<Canvas, U32, Max> = BinaryHeap::new();
let mut trust_level: u8 = 255;
// sorted_clipregions is a Max heap keyed on trust, so popping the elements off will return them sorted from most to least trusted
info!("CANVAS: received screen argument of {:?}", screen);
info!("CANVAS: now determining which regions are drawable");
loop {
if let Some(c) = sorted_clipregions.pop() {
@ -167,14 +169,14 @@ pub fn recompute_canvases(canvases: FnvIndexMap<Gid, Canvas, U32>, screen: Recta
}
if !clip_region.intersects(screen) {
drawable = false;
if debug { info!(" CANVAS: not drawable, does not intersect");}
if debug { info!(" * CANVAS: not drawable, does not intersect");}
} else { // short circuit this computation if it's not drawable because it's off screen
// note that this .iter() is *not* sorted by trust level, but all elements will be of greater than or equal to the current trust level
for &region in higher_clipregions.iter() {
// regions of the same trust level can draw over each other. Draw order is arbitrary.
if region.clip_rect().intersects(clip_region) && (region.trust_level() < trust_level) {
drawable = false;
if debug { info!(" CANVAS: not drawable, lower trust intersecting with higher trust region");}
if debug { info!(" * CANVAS: not drawable, lower trust intersecting with higher trust region");}
}
}
}

View file

@ -54,9 +54,12 @@ pub fn draw_line(gam_cid: xous::CID, gid: Gid, line: Line) -> Result<(), xous::E
}
pub fn get_canvas_bounds(gam_cid: xous::CID, gid: Gid) -> Result<Point, xous::Error> {
let debug1 = false;
if debug1{info!("GAM_API: get_canvas_bounds");}
let response = xous::send_message(gam_cid, api::Opcode::GetCanvasBounds(gid).into())?;
if let xous::Result::Scalar2(tl, br) = response {
// note that the result should always be normalized so the rectangle's "tl" should be (0,0)
if debug1{info!("GAM_API: tl:{}, br:{}", tl, br);}
assert!(tl == 0, "GAM_API: api call returned non-zero top left for canvas bounds");
Ok(br.into())
} else {

View file

@ -70,6 +70,7 @@ fn add_chat_layout(gfx_conn: xous::CID, trng_conn: xous::CID, canvases: &mut Fnv
// get the height of various text regions to compute the layout
let small_height: i16 = graphics_server::glyph_height_hint(gfx_conn, GlyphStyle::Small).expect("GAM: couldn't get glyph height") as i16;
let regular_height: i16 = graphics_server::glyph_height_hint(gfx_conn, GlyphStyle::Regular).expect("GAM: couldn't get glyph height") as i16;
let margin = 4;
// allocate canvases in structures, and record their GID for future reference
let status_canvas = Canvas::new(
@ -79,14 +80,14 @@ fn add_chat_layout(gfx_conn: xous::CID, trng_conn: xous::CID, canvases: &mut Fnv
canvases.insert(status_canvas.gid(), status_canvas).expect("GAM: can't store status canvus");
let predictive_canvas = Canvas::new(
Rectangle::new_coords(0, screensize.y - regular_height, screensize.x, screensize.y),
Rectangle::new_coords(0, screensize.y - regular_height - margin*2, screensize.x, screensize.y),
254,
trng_conn, None
).expect("GAM: couldn't create predictive text canvas");
canvases.insert(predictive_canvas.gid(), predictive_canvas).expect("GAM: couldn't store predictive canvas");
let input_canvas = Canvas::new(
Rectangle::new_v_stack(predictive_canvas.clip_rect(), -regular_height),
Rectangle::new_v_stack(predictive_canvas.clip_rect(), -regular_height - margin*2),
254, trng_conn, None
).expect("GAM: couldn't create input text canvas");
canvases.insert(input_canvas.gid(), input_canvas).expect("GAM: couldn't store input canvas");
@ -145,14 +146,15 @@ fn xmain() -> ! {
// ASSUME: shell is our default application, so set a default predictor of Shell
imef.set_predictor(xous::names::SERVER_NAME_IME_PLUGIN_SHELL).expect("GAM: couldn't set IMEF prediction to shell");
// NOTE: all three API calls (set_input_canvas, set_prediction_canvas, set_predictor) are mandatory for IMEF initialization
let mut last_time: u64 = ticktimer_server::elapsed_ms(ticktimer_conn).unwrap();
info!("GAM: entering main loop");
loop {
let maybe_env = xous::try_receive_message(gam_sid).unwrap();
if debug1 { if maybe_env.is_some() {info!("GAM: Message: {:?}", maybe_env);} }
match maybe_env {
Some(envelope) => {
// let envelope = xous::receive_message(gam_sid).unwrap();
if debug1 {info!("GAM: Message: {:?}", envelope); }
if let Ok(opcode) = Opcode::try_from(&envelope.body) {
if debug1 {info!("GAM: Opcode: {:?}", opcode);}
@ -175,7 +177,7 @@ fn xmain() -> ! {
match canvases.get(&gid) {
Some(c) => {
let mut rect = c.clip_rect();
rect.translate(rect.tl); // normalize to 0,0 coordinates
rect.normalize(); // normalize to 0,0 coordinates
xous::return_scalar2(envelope.sender,
rect.tl.into(),
rect.br.into(),
@ -219,8 +221,14 @@ fn xmain() -> ! {
// issue the draw command
graphics_server::draw_textview(gfx_conn, &mut tv_clone).expect("GAM: text view draw could not complete.");
// copy back the fields that we want to be mutable
if debug1{info!("GAM: got computed cursor of {:?}", tv_clone.cursor);}
tv.cursor = tv_clone.cursor;
tv.bounds_computed = tv_clone.bounds_computed;
// pack our data back into the buffer to return
use rkyv::Write;
let mut writer = rkyv::ArchiveBuffer::new(buf);
writer.archive(&api::Opcode::RenderTextView(tv)).expect("GAM: couldn't re-archive return value");
} else {
info!("GAM: attempt to draw TextView on non-drawable canvas. Not fatal, but request ignored.");
}
@ -247,17 +255,37 @@ fn xmain() -> ! {
// first, figure out if we should even be drawing to this canvas.
if canvas.is_drawable() {
match obj.obj {
GamObjectType::Line(line) => {
graphics_server::draw_line(gfx_conn, line).expect("GAM: couldn't draw line");
GamObjectType::Line(mut line) => {
line.translate(canvas.clip_rect().tl);
line.translate(canvas.pan_offset());
graphics_server::draw_line_clipped(gfx_conn,
line,
canvas.clip_rect(),
).expect("GAM: couldn't draw line");
},
GamObjectType::Circ(circ) => {
graphics_server::draw_circle(gfx_conn, circ).expect("GAM: couldn't draw circle");
GamObjectType::Circ(mut circ) => {
circ.translate(canvas.clip_rect().tl);
circ.translate(canvas.pan_offset());
graphics_server::draw_circle_clipped(gfx_conn,
circ,
canvas.clip_rect(),
).expect("GAM: couldn't draw circle");
},
GamObjectType::Rect(rect) => {
graphics_server::draw_rectangle(gfx_conn, rect).expect("GAM: couldn't draw rectangle");
GamObjectType::Rect(mut rect) => {
rect.translate(canvas.clip_rect().tl);
rect.translate(canvas.pan_offset());
graphics_server::draw_rectangle_clipped(gfx_conn,
rect,
canvas.clip_rect(),
).expect("GAM: couldn't draw rectangle");
},
GamObjectType::RoundRect(rr) => {
graphics_server::draw_rounded_rectangle(gfx_conn, rr).expect("GAM: couldn't draw rounded rectangle");
GamObjectType::RoundRect(mut rr) => {
rr.translate(canvas.clip_rect().tl);
rr.translate(canvas.pan_offset());
graphics_server::draw_rounded_rectangle_clipped(gfx_conn,
rr,
canvas.clip_rect(),
).expect("GAM: couldn't draw rounded rectangle");
}
}
} else {
@ -282,6 +310,10 @@ fn xmain() -> ! {
if let Ok(elapsed_time) = ticktimer_server::elapsed_ms(ticktimer_conn) {
if elapsed_time - last_time > 33 { // rate limit updates to 30fps
last_time = elapsed_time;
// TODO: enhance this update with a methods that:
// 1. deface dirty areas that require defacing
// 2. update the drawn dirty bits indicating things have been drawn, as appropriate
graphics_server::flush(gfx_conn).expect("GAM: couldn't flush buffer to screen");
}
}

View file

@ -99,8 +99,11 @@ pub enum Opcode {
/// gets info about the current glyph to assist with layout
QueryGlyphProps(GlyphStyle),
// draws a textview
/// draws a textview
DrawTextView(TextView),
/// draws an object that requires clipping
DrawClipObject(ClipObject),
}
impl core::convert::TryFrom<& Message> for Opcode {
@ -264,3 +267,18 @@ impl Into<Message> for Opcode {
}
}
}
#[derive(Debug, rkyv::Archive, rkyv::Unarchive, Copy, Clone)]
pub enum ClipObjectType {
Line(Line),
Circ(Circle),
Rect(Rectangle),
RoundRect(RoundedRectangle),
}
#[derive(Debug, rkyv::Archive, rkyv::Unarchive, Copy, Clone)]
pub struct ClipObject {
pub clip: Rectangle,
pub obj: ClipObjectType,
}

View file

@ -157,6 +157,26 @@ impl Rectangle {
self.tl.x = 0;
self.tl.y = 0;
}
// this "margins in" a rectangle on all sides; if the margin is more than the twice any
// dimension it just reduces the rectangle to a line at the midpoint of the axis dimension
pub fn margin(&mut self, margin: Point) {
if margin.x * 2 <= (self.br.x - self.tl.x) {
self.tl.x += margin.x;
self.br.x -= margin.x;
} else {
let midpoint = (self.br.x + self.tl.x) / 2;
self.tl.x = midpoint;
self.br.x = midpoint;
}
if margin.y * 2 <= (self.br.y - self.tl.y) {
self.tl.y += margin.y;
self.br.y -= margin.y;
} else {
let midpoint = (self.br.y + self.tl.y) / 2;
self.tl.y = midpoint;
self.br.y = midpoint;
}
}
/// Make a rectangle of the full screen size
pub fn full_screen() -> Rectangle {
@ -209,6 +229,10 @@ impl Line {
style: style,
}
}
pub fn translate(&mut self, offset: Point) {
self.start = self.start + offset;
self.end = self.end + offset;
}
}
@ -238,6 +262,9 @@ impl Circle {
style,
}
}
pub fn translate(&mut self, offset: Point) {
self.center = self.center + offset;
}
}
//////////////////////// Rounded Rectangle
@ -261,6 +288,9 @@ impl RoundedRectangle {
radius: r_adj,
}
}
pub fn translate(&mut self, offset: Point) {
self.border.translate(offset);
}
}

View file

@ -1,8 +1,9 @@
use utralib::generated::*;
use xous::MemoryRange;
use crate::api::Point;
const FB_WIDTH_WORDS: usize = 11;
// const FB_WIDTH_PIXELS: usize = 336;
const FB_WIDTH_PIXELS: usize = 336;
const FB_LINES: usize = 536;
const FB_SIZE: usize = FB_WIDTH_WORDS * FB_LINES; // 44 bytes by 536 lines
const CONFIG_CLOCK_FREQUENCY: u32 = 100_000_000;
@ -66,6 +67,8 @@ impl XousDisplay {
display
}
pub fn screen_size(&self) -> Point { Point::new(FB_WIDTH_PIXELS as i16, FB_LINES as i16) }
pub fn redraw(&mut self) {
while self.busy() {xous::yield_slice()}
let fb: *mut [u32; FB_SIZE] = self.fb.as_mut_ptr() as *mut [u32; FB_SIZE];

View file

@ -1,4 +1,5 @@
use minifb::{Key, Window, WindowOptions, KeyRepeat};
use crate::api::Point;
const WIDTH: usize = 336;
const HEIGHT: usize = 536;
@ -54,6 +55,8 @@ impl XousDisplay {
}
}
pub fn screen_size(&self) -> Point { Point::new(WIDTH as i16, HEIGHT as i16) }
pub fn blit_screen(&mut self, bmp: [u32; FB_SIZE]) {
for (dest, src) in self.emulated_buffer.iter_mut().zip(bmp.iter()) {
*dest = *src;

View file

@ -2,7 +2,7 @@
// pub mod size;
pub mod api;
pub use api::{Circle, DrawStyle, Line, PixelColor, Point, Rectangle, TextView, TextBounds, Gid, TextOp, RoundedRectangle};
pub use api::{Circle, DrawStyle, Line, PixelColor, Point, Rectangle, TextView, TextBounds, Gid, TextOp, RoundedRectangle, ClipObject, ClipObjectType};
use blitstr_ref as blitstr;
pub use blitstr::{ClipRect, Cursor, GlyphStyle};
use xous::String;
@ -10,6 +10,9 @@ pub mod op;
use xous::{send_message, CID};
use core::fmt::Write;
use rkyv::Write as RkyvWrite;
use rkyv::Unarchive;
pub fn draw_line(cid: CID, line: Line) -> Result<(), xous::Error> {
let m: xous::Message = api::Opcode::Line(line).into();
@ -116,10 +119,6 @@ pub fn glyph_height_hint(cid: CID, glyph: GlyphStyle) -> Result<usize, xous::Err
}
pub fn draw_textview(cid: CID, tv: &mut TextView) -> Result<(), xous::Error> {
use log::info;
use rkyv::Write;
use rkyv::Unarchive;
let rkyv_tv = api::Opcode::DrawTextView(*tv);
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rkyv_tv).expect("couldn't archive textview");
@ -130,12 +129,74 @@ pub fn draw_textview(cid: CID, tv: &mut TextView) -> Result<(), xous::Error> {
let returned = unsafe { rkyv::archived_value::<api::Opcode>(xous_buffer.as_ref(), pos)};
if let rkyv::Archived::<api::Opcode>::DrawTextView(result) = returned {
let tvr: TextView = result.unarchive();
//log::info!("draw_textview: got cursor of {:?}, bounds of {:?}", tvr.cursor, tvr.bounds_computed);
tv.bounds_computed = tvr.bounds_computed;
tv.cursor = tvr.cursor;
Ok(())
} else {
let tvr = returned.unarchive();
info!("draw_textview saw an unhandled return type of {:?}", tvr);
log::info!("draw_textview saw an unhandled return type of {:?}", tvr);
Err(xous::Error::InternalError)
}
}
pub fn draw_line_clipped(cid: xous::CID, line: Line, clip: Rectangle) -> Result<(), xous::Error> {
let rkyv = api::Opcode::DrawClipObject(
ClipObject {
clip: clip,
obj: ClipObjectType::Line(line),
});
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rkyv).expect("GFX_API: couldn't archive ClipObject");
let xous_buffer = writer.into_inner();
xous_buffer.lend(cid, pos as u32).expect("GFX_API: ClipObject operation failure");
Ok(())
}
pub fn draw_circle_clipped(cid: xous::CID, circ: Circle, clip: Rectangle) -> Result<(), xous::Error> {
let rkyv = api::Opcode::DrawClipObject(
ClipObject {
clip: clip,
obj: ClipObjectType::Circ(circ),
});
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rkyv).expect("GFX_API: couldn't archive ClipObject");
let xous_buffer = writer.into_inner();
xous_buffer.lend(cid, pos as u32).expect("GFX_API: ClipObject operation failure");
Ok(())
}
pub fn draw_rectangle_clipped(cid: xous::CID, rect: Rectangle, clip: Rectangle) -> Result<(), xous::Error> {
let rkyv = api::Opcode::DrawClipObject(
ClipObject {
clip: clip,
obj: ClipObjectType::Rect(rect),
});
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rkyv).expect("GFX_API: couldn't archive ClipObject");
let xous_buffer = writer.into_inner();
xous_buffer.lend(cid, pos as u32).expect("GFX_API: ClipObject operation failure");
Ok(())
}
pub fn draw_rounded_rectangle_clipped(cid: xous::CID, rr: RoundedRectangle, clip: Rectangle) -> Result<(), xous::Error> {
let rkyv = api::Opcode::DrawClipObject(
ClipObject {
clip: clip,
obj: ClipObjectType::RoundRect(rr),
});
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rkyv).expect("GFX_API: couldn't archive ClipObject");
let xous_buffer = writer.into_inner();
xous_buffer.lend(cid, pos as u32).expect("GFX_API: ClipObject operation failure");
Ok(())
}

View file

@ -4,7 +4,7 @@
use log::{error, info};
mod api;
use api::Opcode;
use api::{Opcode, ClipObject, ClipObjectType};
use core::pin::Pin;
use rkyv::{archived_value, Unarchive, archived_value_mut};
@ -18,7 +18,7 @@ use core::convert::TryFrom;
mod logo;
use api::{DrawStyle, PixelColor, Rectangle, TextBounds, RoundedRectangle};
use api::{DrawStyle, PixelColor, Rectangle, TextBounds, RoundedRectangle, Point};
use blitstr_ref as blitstr;
mod fontmap;
@ -57,9 +57,13 @@ fn map_fonts() {
#[xous::xous_main]
fn xmain() -> ! {
let debug1 = false;
log_server::init_wait().unwrap();
info!("GFX: my PID is {}", xous::process::id());
let sid = xous_names::register_name(xous::names::SERVER_NAME_GFX).expect("GFX: can't register server");
info!("GFX: Server listening on address {:?}", sid);
// Create a new monochrome simulator display.
let mut display = XousDisplay::new();
@ -71,9 +75,6 @@ fn xmain() -> ! {
let mut current_string_clip = blitstr::ClipRect::full_screen();
let mut current_cursor = blitstr::Cursor::from_top_left_of(current_string_clip);
let sid = xous_names::register_name(xous::names::SERVER_NAME_GFX).expect("GFX: can't register server");
info!("GFX: Server listening on address {:?}", sid);
if false {
// leave this test case around
// for some reason, the top right quadrant draws an extra pixel inside the fill area
@ -88,9 +89,11 @@ fn xmain() -> ! {
stroke_width: 1,
};
let rr = RoundedRectangle::new(r, 16);
op::rounded_rectangle(display.native_buffer(), rr);
op::rounded_rectangle(display.native_buffer(), rr, None);
}
let screen_clip = Rectangle::new(Point::new(0,0), display.screen_size());
display.redraw();
loop {
let msg = xous::receive_message(sid).unwrap();
@ -128,6 +131,24 @@ fn xmain() -> ! {
blitstr::xor_char
);
},
rkyv::Archived::<api::Opcode>::DrawClipObject(rco) => {
let obj: ClipObject = rco.unarchive();
if debug1{info!("GFX: DrawClipObject {:?}", obj);}
match obj.obj {
ClipObjectType::Line(line) => {
op::line(display.native_buffer(), line, Some(obj.clip));
},
ClipObjectType::Circ(circ) => {
op::circle(display.native_buffer(), circ, Some(obj.clip));
},
ClipObjectType::Rect(rect) => {
op::rectangle(display.native_buffer(), rect, Some(obj.clip));
},
ClipObjectType::RoundRect(rr) => {
op::rounded_rectangle(display.native_buffer(), rr, Some(obj.clip));
}
}
},
_ => panic!("GFX: invalid response from server -- corruption occurred in MemoryMessage")
};
} else if let xous::Message::MutableBorrow(m) = &msg.body {
@ -135,27 +156,22 @@ fn xmain() -> ! {
let value = unsafe {
archived_value_mut::<api::Opcode>(Pin::new(buf.as_mut()), m.id as usize)
};
//use rkyv::Write;
//let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let debugtv: bool = false;
match &*value {
rkyv::Archived::<api::Opcode>::DrawTextView(rtv) => {
let mut tv = rtv.unarchive();
if tv.clip_rect.is_none() { continue } // if no clipping rectangle is specified, nothing to draw
let screen_offset: Point = tv.clip_rect.unwrap().tl; // this is the translation vector to and from screen space
let paintfn = if tv.dry_run {
if debugtv { info!("GFX(TV): doing dry run"); }
blitstr::simulate_char
} else {
if debugtv { info!("GFX(TV): drawing"); }
if debugtv { info!("GFX(TV): doing live run"); }
blitstr::xor_char
};
/*
1. figure out text bounds
2. clear background, if requested
3. draw surrounding rectangle, if requested
4. draw text
*/
// first compute the bounding box, if it isn't computed
if tv.bounds_computed.is_none() {
match tv.bounds_hint {
@ -177,7 +193,10 @@ fn xmain() -> ! {
// clear the bounding box if requested
let mut clear_rect = tv.bounds_computed.unwrap();
clear_rect.translate(tv.clip_rect.unwrap().tl);
// move things into screen coordinates
clear_rect.translate(screen_offset);
let bordercolor = if tv.draw_border {
Some(PixelColor::Dark)
} else {
@ -201,37 +220,51 @@ fn xmain() -> ! {
};
if tv.rounded_border.is_some() {
op::rounded_rectangle(display.native_buffer(),
RoundedRectangle::new(clear_rect, tv.rounded_border.unwrap() as _));
RoundedRectangle::new(clear_rect, tv.rounded_border.unwrap() as _), tv.clip_rect);
} else {
if debugtv { info!("GFX(TV): clearing rectangle {:?}", clear_rect); }
op::rectangle(display.native_buffer(), clear_rect);
op::rectangle(display.native_buffer(), clear_rect, tv.clip_rect);
}
// this is the actual draw operation
clear_rect.translate(tv.margin);
/////// TODO: I think we need to clip the clear_rect.tl.x/y to within the screen area for this to be valid?
let mut ref_cursor = blitstr::Cursor{
pt: blitstr::Pt{x: clear_rect.tl.x as u32, y: clear_rect.tl.y as u32},
line_height: 0,
// compute the final clipping region for the string
clear_rect.margin(tv.margin);
let cr = match clear_rect.clip_with(screen_clip) {
Some(r) => r,
_ => continue, // don't draw anything if somehow this doesn't fit in the creen.
};
if debugtv { info!("GFX(TV): paint_str with {:?} | {:?} | {:?} | {:?}", clear_rect, ref_cursor, tv.style, tv.text); }
let mut ref_cursor = blitstr::Cursor::from_top_left_of(cr.into());
if debugtv { info!("GFX(TV): paint_str with {:?} | {:?} | {:?} | {:?}", cr, ref_cursor, tv.style, tv.text); }
blitstr::paint_str(
display.native_buffer(),
clear_rect.into(),
cr.into(),
&mut ref_cursor,
tv.style.into(),
tv.text.as_str().unwrap(),
false,
paintfn
);
tv.cursor = ref_cursor;
// translate the cursor return value back to canvas coordinates
tv.cursor = blitstr::Cursor {
pt: blitstr::Pt::new(
ref_cursor.pt.x - screen_offset.x as u32,
ref_cursor.pt.y - screen_offset.y as u32,
),
line_height: ref_cursor.line_height,
};
if debugtv{info!("GFX(TV): returning cursor of {:?}", tv.cursor);}
// pack our data back into the buffer to return
use rkyv::Write;
let mut writer = rkyv::ArchiveBuffer::new(buf);
writer.archive(&api::Opcode::DrawTextView(tv)).expect("GFX: couldn't re-archive return value");
},
_ => panic!("GFX: invalid mutable borrow message"),
}
};
} else if let Ok(opcode) = Opcode::try_from(&msg.body) {
// info!("GFX: Opcode: {:?}", opcode);
let debugop = false;
if debugop {info!("GFX: Opcode: {:?}", opcode);}
match opcode {
Opcode::Flush => {
display.update();
@ -240,19 +273,19 @@ fn xmain() -> ! {
Opcode::Clear => {
let mut r = Rectangle::full_screen();
r.style = DrawStyle::new(PixelColor::Light, PixelColor::Light, 0);
op::rectangle(display.native_buffer(), r)
op::rectangle(display.native_buffer(), r, None)
}
Opcode::Line(l) => {
op::line(display.native_buffer(), l);
op::line(display.native_buffer(), l, None);
}
Opcode::Rectangle(r) => {
op::rectangle(display.native_buffer(), r);
op::rectangle(display.native_buffer(), r, None);
}
Opcode::RoundedRectangle(rr) => {
op::rounded_rectangle(display.native_buffer(), rr);
op::rounded_rectangle(display.native_buffer(), rr, None);
}
Opcode::Circle(c) => {
op::circle(display.native_buffer(), c);
op::circle(display.native_buffer(), c, None);
}
Opcode::SetGlyphStyle(glyph) => {
current_glyph = glyph;
@ -270,7 +303,8 @@ fn xmain() -> ! {
current_string_clip = r;
}
Opcode::ScreenSize => {
xous::return_scalar2(msg.sender, 336 as usize, 536 as usize)
let pt = display.screen_size();
xous::return_scalar2(msg.sender, pt.x as usize, pt.y as usize)
.expect("GFX: couldn't return ScreenSize request");
}
Opcode::QueryGlyphStyle => {

View file

@ -32,7 +32,7 @@ fn put_pixel(fb: &mut LcdFB, x: i16, y: i16, color: PixelColor) {
fb[clip_y * LCD_WORDS_PER_LINE + (LCD_WORDS_PER_LINE - 1)] |= 0x1_0000;
}
pub fn line(fb: &mut LcdFB, l: Line) {
pub fn line(fb: &mut LcdFB, l: Line, clip: Option<Rectangle>) {
let color: PixelColor;
if l.style.stroke_color.is_some() {
color = l.style.stroke_color.unwrap();
@ -52,7 +52,9 @@ pub fn line(fb: &mut LcdFB, l: Line) {
loop {
/* loop */
if x0 >= 0 && y0 >= 0 && x0 < (WIDTH as _) && y0 < (HEIGHT as _) {
put_pixel(fb, x0 as _, y0 as _, color);
if clip.is_none() || (clip.unwrap().intersects_point(Point::new(x0, y0))) {
put_pixel(fb, x0 as _, y0 as _, color);
}
}
if x0 == x1 && y0 == y1 {
break;
@ -79,6 +81,7 @@ pub struct CircleIterator {
radius: u16,
style: DrawStyle,
p: Point,
clip: Option<Rectangle>
}
impl Iterator for CircleIterator {
@ -98,26 +101,31 @@ impl Iterator for CircleIterator {
let outer_radius_sq = outer_radius * outer_radius;
loop {
let t = self.p;
let len = t.x * t.x + t.y * t.y;
let mut item = None;
let is_border = len > radius_sq - radius && len < outer_radius_sq + radius;
if self.clip.is_none() || // short-circuit evaluation makes this safe
(self.clip.unwrap().intersects_point(self.p)) {
let t = self.p;
let len = t.x * t.x + t.y * t.y;
let is_fill = len <= outer_radius_sq + 1;
let is_border = len > radius_sq - radius && len < outer_radius_sq + radius;
let item = if is_border && self.style.stroke_color.is_some() {
Some(Pixel(
self.center + t,
self.style.stroke_color.expect("Border color not defined"),
))
} else if is_fill && self.style.fill_color.is_some() {
Some(Pixel(
self.center + t,
self.style.fill_color.expect("Fill color not defined"),
))
} else {
None
};
let is_fill = len <= outer_radius_sq + 1;
item = if is_border && self.style.stroke_color.is_some() {
Some(Pixel(
self.center + t,
self.style.stroke_color.expect("Border color not defined"),
))
} else if is_fill && self.style.fill_color.is_some() {
Some(Pixel(
self.center + t,
self.style.fill_color.expect("Fill color not defined"),
))
} else {
None
};
}
self.p.x += 1;
@ -137,12 +145,13 @@ impl Iterator for CircleIterator {
}
}
pub fn circle(fb: &mut LcdFB, circle: Circle) {
pub fn circle(fb: &mut LcdFB, circle: Circle, clip: Option<Rectangle>) {
let c = CircleIterator {
center: circle.center,
radius: circle.radius as _,
style: circle.style,
p: Point::new(-(circle.radius as i16), -(circle.radius as i16)),
clip: clip,
};
for pixel in c {
@ -158,6 +167,7 @@ pub struct RectangleIterator {
bottom_right: Point,
style: DrawStyle,
p: Point,
clip: Option<Rectangle>,
}
impl Iterator for RectangleIterator {
@ -177,30 +187,33 @@ impl Iterator for RectangleIterator {
break None;
}
let border_width = self.style.stroke_width;
let tl = self.top_left;
let br = self.bottom_right;
if self.clip.is_none() || // short-circuit evaluation makes this safe
(self.clip.unwrap().intersects_point(self.p)) {
let border_width = self.style.stroke_width;
let tl = self.top_left;
let br = self.bottom_right;
// Border
if (
// Top border
(self.p.y >= tl.y && self.p.y < tl.y + border_width)
// Bottom border
|| (self.p.y <= br.y && self.p.y > br.y - border_width)
// Left border
|| (self.p.x >= tl.x && self.p.x < tl.x + border_width)
// Right border
|| (self.p.x <= br.x && self.p.x > br.x - border_width)
) && self.style.stroke_color.is_some()
{
out = Some(Pixel(
self.p,
self.style.stroke_color.expect("Expected stroke"),
));
}
// Fill
else if let Some(fill) = self.style.fill_color {
out = Some(Pixel(self.p, fill));
// Border
if (
// Top border
(self.p.y >= tl.y && self.p.y < tl.y + border_width)
// Bottom border
|| (self.p.y <= br.y && self.p.y > br.y - border_width)
// Left border
|| (self.p.x >= tl.x && self.p.x < tl.x + border_width)
// Right border
|| (self.p.x <= br.x && self.p.x > br.x - border_width)
) && self.style.stroke_color.is_some()
{
out = Some(Pixel(
self.p,
self.style.stroke_color.expect("Expected stroke"),
));
}
// Fill
else if let Some(fill) = self.style.fill_color {
out = Some(Pixel(self.p, fill));
}
}
self.p.x += 1;
@ -218,12 +231,13 @@ impl Iterator for RectangleIterator {
}
}
pub fn rectangle(fb: &mut LcdFB, rect: Rectangle) {
pub fn rectangle(fb: &mut LcdFB, rect: Rectangle, clip: Option<Rectangle>) {
let r = RectangleIterator {
top_left: rect.tl,
bottom_right: rect.br,
style: rect.style,
p: rect.tl,
clip: clip,
};
for pixel in r {
@ -248,6 +262,7 @@ pub struct QuadrantIterator {
style: DrawStyle,
p: Point,
quad: Quadrant,
clip: Option<Rectangle>,
}
impl Iterator for QuadrantIterator {
@ -267,26 +282,31 @@ impl Iterator for QuadrantIterator {
let outer_radius_sq = outer_radius * outer_radius;
loop {
let t = self.p;
let len = t.x * t.x + t.y * t.y;
let mut item = None;
if self.clip.is_none() || // short-circuit evaluation makes this safe
(self.clip.unwrap().intersects_point(self.p)) {
let is_border = len > (inner_radius_sq - inner_radius) && len < (outer_radius_sq + inner_radius);
let t = self.p;
let len = t.x * t.x + t.y * t.y;
let is_fill = len <= outer_radius_sq + 1;
let is_border = len > (inner_radius_sq - inner_radius) && len < (outer_radius_sq + inner_radius);
let item = if is_border && self.style.stroke_color.is_some() {
Some(Pixel(
self.center + t,
self.style.stroke_color.expect("Border color not defined"),
))
} else if is_fill && self.style.fill_color.is_some() {
Some(Pixel(
self.center + t,
self.style.fill_color.expect("Fill color not defined"),
))
} else {
None
};
let is_fill = len <= outer_radius_sq + 1;
item = if is_border && self.style.stroke_color.is_some() {
Some(Pixel(
self.center + t,
self.style.stroke_color.expect("Border color not defined"),
))
} else if is_fill && self.style.fill_color.is_some() {
Some(Pixel(
self.center + t,
self.style.fill_color.expect("Fill color not defined"),
))
} else {
None
};
}
self.p.x += 1;
@ -344,7 +364,7 @@ impl Iterator for QuadrantIterator {
}
}
pub fn quadrant(fb: &mut LcdFB, circle: Circle, quad: Quadrant) {
pub fn quadrant(fb: &mut LcdFB, circle: Circle, quad: Quadrant, clip: Option<Rectangle>) {
let starting_pixel = match quad {
Quadrant::TopLeft => {
Point::new( -(circle.radius as i16), -(circle.radius as i16))
@ -365,6 +385,7 @@ pub fn quadrant(fb: &mut LcdFB, circle: Circle, quad: Quadrant) {
style: circle.style,
p: starting_pixel,
quad: quad,
clip: clip,
};
for pixel in q {
@ -382,6 +403,7 @@ pub struct RoundedRectangleIterator {
style: DrawStyle,
radius: i16,
p: Point,
clip: Option<Rectangle>,
// the four quadrants for drawing the rounded corners
tlq: Rectangle,
trq: Rectangle,
@ -405,35 +427,39 @@ impl Iterator for RoundedRectangleIterator {
break None;
}
// suppress the output pixel if we happen to be in the corner quadrant area
if self.tlq.intersects_point(self.p) || self.trq.intersects_point(self.p) ||
self.blq.intersects_point(self.p) || self.brq.intersects_point(self.p) {
out = None
} else {
let border_width = self.style.stroke_width;
let tl = self.top_left;
let br = self.bottom_right;
if self.clip.is_none() || // short-circuit evaluation makes this safe
(self.clip.unwrap().intersects_point(self.p)) {
// Border
if (
// Top border
(self.p.y >= tl.y && self.p.y < tl.y + border_width)
// Bottom border
|| (self.p.y <= br.y && self.p.y > br.y - border_width)
// Left border
|| (self.p.x >= tl.x && self.p.x < tl.x + border_width)
// Right border
|| (self.p.x <= br.x && self.p.x > br.x - border_width)
) && self.style.stroke_color.is_some()
{
out = Some(Pixel(
self.p,
self.style.stroke_color.expect("Expected stroke"),
));
}
// Fill
else if let Some(fill) = self.style.fill_color {
out = Some(Pixel(self.p, fill));
// suppress the output pixel if we happen to be in the corner quadrant area
if self.tlq.intersects_point(self.p) || self.trq.intersects_point(self.p) ||
self.blq.intersects_point(self.p) || self.brq.intersects_point(self.p) {
out = None
} else {
let border_width = self.style.stroke_width;
let tl = self.top_left;
let br = self.bottom_right;
// Border
if (
// Top border
(self.p.y >= tl.y && self.p.y < tl.y + border_width)
// Bottom border
|| (self.p.y <= br.y && self.p.y > br.y - border_width)
// Left border
|| (self.p.x >= tl.x && self.p.x < tl.x + border_width)
// Right border
|| (self.p.x <= br.x && self.p.x > br.x - border_width)
) && self.style.stroke_color.is_some()
{
out = Some(Pixel(
self.p,
self.style.stroke_color.expect("Expected stroke"),
));
}
// Fill
else if let Some(fill) = self.style.fill_color {
out = Some(Pixel(self.p, fill));
}
}
}
@ -453,7 +479,7 @@ impl Iterator for RoundedRectangleIterator {
}
}
pub fn rounded_rectangle(fb: &mut LcdFB, rr: RoundedRectangle) {
pub fn rounded_rectangle(fb: &mut LcdFB, rr: RoundedRectangle, clip: Option<Rectangle>) {
// compute the four quadrants
// call the rr iterator on the rectangle
// then call it on one each of the four circle quadrants
@ -464,6 +490,7 @@ pub fn rounded_rectangle(fb: &mut LcdFB, rr: RoundedRectangle) {
style: rr.border.style,
radius: rr.radius,
p: rr.border.tl,
clip: clip,
tlq: Rectangle::new(
rr.border.tl,
Point::new(rr.border.tl.x + rr.radius, rr.border.tl.y + rr.radius)),
@ -484,18 +511,22 @@ pub fn rounded_rectangle(fb: &mut LcdFB, rr: RoundedRectangle) {
// now draw the corners
quadrant(fb,
Circle::new_with_style(rri.tlq.br, rr.radius, rr.border.style),
Quadrant::TopLeft
Quadrant::TopLeft,
clip
);
quadrant(fb,
Circle::new_with_style(Point::new(rri.trq.tl.x, rri.trq.br.y), rr.radius, rr.border.style),
Quadrant::TopRight
Quadrant::TopRight,
clip
);
quadrant(fb,
Circle::new_with_style(Point::new(rri.blq.br.x, rri.blq.tl.y), rr.radius, rr.border.style),
Quadrant::BottomLeft
Quadrant::BottomLeft,
clip
);
quadrant(fb,
Circle::new_with_style(rri.brq.tl, rr.radius, rr.border.style),
Quadrant::BottomRight
Quadrant::BottomRight,
clip
);
}

View file

@ -9,7 +9,7 @@ use core::fmt::Write;
use log::{error, info};
use graphics_server::{Gid, TextView, Point, TextBounds, Rectangle, Line};
use graphics_server::{Gid, Line, PixelColor, Point, Rectangle, TextBounds, TextView, DrawStyle};
use blitstr_ref as blitstr;
use blitstr::Cursor;
use heapless::Vec;
@ -68,28 +68,44 @@ impl InputTracker {
self.pred_canvas = Some(pred);
}
pub fn is_init(&self) -> bool {
self.input_canvas.is_some() && self.pred_canvas.is_some()
self.input_canvas.is_some() && self.pred_canvas.is_some() && self.predictor.is_some()
}
pub fn update(&mut self, newkeys: [char; 4]) -> Result<(), xous::Error> {
let debug1= true;
let debug1= false;
// just draw a rectangle for the prediction area for now
if let Some(pc) = self.pred_canvas {
if debug1{info!("IMEF: updating prediction area");}
let pc_bounds: Point = gam::get_canvas_bounds(self.gam_conn, pc).expect("IMEF: Couldn't get prediction canvas bounds");
if debug1{info!("IMEF: got pc_bound {:?}", pc_bounds);}
let mut starting_tv = TextView::new(pc, 255,
TextBounds::BoundingBox(Rectangle::new(Point::new(0, 0), pc_bounds)));
starting_tv.draw_border = true;
starting_tv.draw_border = false;
starting_tv.border_width = 1;
starting_tv.clear_area = true;
starting_tv.clear_area = false;
if debug1{info!("IMEF: posting textview {:?}", starting_tv);}
gam::post_textview(self.gam_conn, &mut starting_tv).expect("IMEF: can't draw prediction TextView");
// add the border line on top
gam::draw_line(self.gam_conn, pc,
Line::new_with_style(
Point::new(0,0),
Point::new(pc_bounds.x, 0),
DrawStyle {
fill_color: None,
stroke_color: Some(PixelColor::Dark),
stroke_width: 1,
})
).expect("IMEF: can't draw prediction top border");
}
if let Some(ic) = self.input_canvas {
let ic_bounds: Point = gam::get_canvas_bounds(self.gam_conn, ic).expect("IMEF: Couldn't get input canvas bounds");
if debug1{info!("IMEF: updating input area");}
let mut ic_bounds: Point = gam::get_canvas_bounds(self.gam_conn, ic).expect("IMEF: Couldn't get input canvas bounds");
let mut input_tv = TextView::new(ic, 255,
TextBounds::BoundingBox(Rectangle::new(Point::new(0,0), ic_bounds)));
input_tv.draw_border = true;
TextBounds::BoundingBox(Rectangle::new(Point::new(0,1), ic_bounds)));
input_tv.draw_border = false;
input_tv.border_width = 1;
input_tv.clear_area = true;
@ -105,6 +121,7 @@ impl InputTracker {
self.line.push(k).expect("IMEF: ran out of space pushing character into input line");
write!(input_tv.text, "{}", self.line.as_str().expect("IMEF: couldn't convert str")).expect("IMEF: couldn't update TextView string in input canvas");
gam::post_textview(self.gam_conn, &mut input_tv).expect("IMEF: can't draw input TextView");
if debug1{info!("IMEF: got computed cursor of {:?}", input_tv.cursor);}
if self.insertion.pt.y == input_tv.cursor.pt.y {
self.charwidths[self.line.len()] = (input_tv.cursor.pt.x - self.insertion.pt.x) as u8;
} else {
@ -112,6 +129,8 @@ impl InputTracker {
self.charwidths[self.line.len()] = (input_tv.cursor.pt.x - 0) as u8;
}
self.insertion.pt.y = input_tv.cursor.pt.y;
self.insertion.pt.x = input_tv.cursor.pt.x;
self.insertion.line_height = input_tv.cursor.line_height;
},
}
}
@ -119,8 +138,24 @@ impl InputTracker {
// draw the insertion point
// do a manual type conversion, because external crate etc. etc.
let ins_pt: Point = Point::new(self.insertion.pt.x as i16, self.insertion.pt.y as i16);
if debug1{info!("IMEF: drawing insertion point: {:?}, height: {}", ins_pt, self.insertion.line_height);}
gam::draw_line(self.gam_conn, ic,
Line::new(ins_pt, ins_pt + Point::new(0, self.insertion.line_height as i16 - input_tv.margin.y) )).expect("IMEF: can't draw insertion point");
Line::new(ins_pt,
ins_pt + Point::new(0, self.insertion.line_height as i16 - input_tv.margin.y) ))
.expect("IMEF: can't draw insertion point");
// add the border line on top
gam::draw_line(self.gam_conn, ic,
Line::new_with_style(
Point::new(0,0),
Point::new(ic_bounds.x, 0),
DrawStyle {
fill_color: None,
stroke_color: Some(PixelColor::Dark),
stroke_width: 1,
}))
.expect("IMEF: can't draw input top line border");
}
/*
what else do we need:
@ -133,7 +168,7 @@ impl InputTracker {
#[xous::xous_main]
fn xmain() -> ! {
let debug1 = true;
let debug1 = false;
log_server::init_wait().unwrap();
info!("IMEF: my PID is {}", xous::process::id());
@ -146,7 +181,7 @@ fn xmain() -> ! {
let mut tracker = InputTracker::new(
xous_names::request_connection_blocking(xous::names::SERVER_NAME_GAM).expect("IMEF: can't connect to GAM"),
);
// The first message should be my Gid from the GAM.
// The main lop can't start until we've been assigned Gids from the GAM, and a Predictor.
info!("IMEF: waiting for my canvas Gids");
loop {
let envelope = xous::receive_message(imef_sid).unwrap();
@ -162,6 +197,22 @@ fn xmain() -> ! {
},
_ => info!("IMEF: expected canvas Gid, but got {:?}", opcode)
}
} else if let xous::Message::Borrow(m) = &envelope.body {
let buf = unsafe { xous::XousBuffer::from_memory_message(m) };
let bytes = Pin::new(buf.as_ref());
let value = unsafe {
archived_value::<ImefOpcode>(&bytes, m.id as usize)
};
match &*value {
rkyv::Archived::<ImefOpcode>::SetPredictionServer(rkyv_s) => {
let s: xous::String<256> = rkyv_s.unarchive();
match xous_names::request_connection(s.as_str().expect("IMEF: SetPrediction received malformed server name")) {
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")),
}
},
_ => panic!("IME_SH: invalid response from server -- corruption occurred in MemoryMessage")
};
} else {
info!("IMEF: expected canvas Gid, but got other message first {:?}", envelope);
}
@ -170,6 +221,10 @@ fn xmain() -> ! {
}
}
// force a redraw of the UI with no keys
if debug1{info!("IMEF: forcing initial UI redraw");}
tracker.update(['\u{0000}'; 4]).expect("IMEF: couldn't redraw initial UI");
let mut key_queue: Vec<char, U32> = Vec::new();
info!("IMEF: entering main loop");
loop {

View file

@ -236,7 +236,7 @@ impl Into<Message> for ImefOpcode {
id: 0, arg1: gid.gid()[0] as _, arg2: gid.gid()[1] as _, arg3: gid.gid()[2] as _, arg4: gid.gid()[3] as _
}),
ImefOpcode::SetPredictionCanvas(gid) => Message::Scalar(ScalarMessage {
id: 0, arg1: gid.gid()[0] as _, arg2: gid.gid()[1] as _, arg3: gid.gid()[2] as _, arg4: gid.gid()[3] as _
id: 1, arg1: gid.gid()[0] as _, arg2: gid.gid()[1] as _, arg3: gid.gid()[2] as _, arg4: gid.gid()[3] as _
}),
_ => panic!("IMEF api: Opcode type not handled by into()"),
}

View file

@ -17,7 +17,7 @@ const FAIL_TIMEOUT_MS: u64 = 100;
#[xous::xous_main]
fn xmain() -> ! {
let debug1 = false;
let debug1 = true;
log_server::init_wait().unwrap();
info!("NS: my PID is {}", xous::process::id());