add guru meditations

This commit is contained in:
bunnie 2022-04-10 04:42:02 +08:00
parent 3f962b6bb0
commit 7353c3ab9c
3 changed files with 656 additions and 385 deletions

View file

@ -80,6 +80,27 @@ impl XousDisplay {
display
}
/// This should only be called to initialize the panic handler with its own
/// copy of hardware registers.
///
/// # Safety
///
/// The addresses of these structures are passed as `u32` and unsafely cast back
/// into pointers on the user's side. We do this because the panic handler is special:
/// it grabs ahold of the low-level hardware, yanking control from the higher level
/// control functons, without having to map its own separate pages.
///
/// Of course, "anyone" with a copy of this data can clobber existing graphics operations. Thus,
/// any access to these registers have to be protected with a mutex of some form. In the case of
/// the panic handler, the `is_panic` `AtomicBool` will suppress graphics loop operation
/// in the case of a panic.
pub unsafe fn hw_regs(&self) -> (u32, u32) {
(
self.hwfb.as_mut_ptr() as u32,
self.csr.base as u32
)
}
pub fn suspend(&mut self) {
while self.busy() {
// just wait until any pending FB operations are done

View file

@ -27,6 +27,10 @@ use xous_ipc::Buffer;
mod fontmap;
use api::BulkRead;
mod panic;
use core::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::wordwrap::*;
use core::ops::Add;
@ -65,7 +69,6 @@ fn map_fonts() -> MemoryRange {
"mapping regular font to 0x{:08x}",
fontregion.as_ptr() as usize + fontmap::REGULAR_OFFSET as usize
);
use core::sync::atomic::Ordering;
blitstr2::fonts::bold::GLYPH_LOCATION.store((fontregion.as_ptr() as usize + fontmap::BOLD_OFFSET as usize) as u32, Ordering::SeqCst);
blitstr2::fonts::emoji::GLYPH_LOCATION.store((fontregion.as_ptr() as usize + fontmap::EMOJI_OFFSET as usize) as u32, Ordering::SeqCst);
blitstr2::fonts::ja::GLYPH_LOCATION.store((fontregion.as_ptr() as usize + fontmap::JA_OFFSET as usize) as u32, Ordering::SeqCst);
@ -94,6 +97,21 @@ fn xmain() -> ! {
log::set_max_level(log::LevelFilter::Info);
log::info!("my PID is {}", xous::process::id());
let mut display = XousDisplay::new();
let fontregion = map_fonts();
// install the graphical panic handler. It won't catch really early panics, or panics in this crate,
// but it'll do the job 90% of the time and it's way better than having none at all.
let is_panic = Arc::new(AtomicBool::new(false));
#[cfg(any(target_os = "none", target_os = "xous"))] // only install for hardware targets; hosted mode uses host's panic handler
{
let (hwfb, control) = unsafe{
// this is safe because we are extracting these for use in a Mutex-protected panic handler
display.hw_regs()
};
panic::panic_handler_thread(is_panic.clone(), hwfb, control);
}
let xns = xous_names::XousNames::new().unwrap();
// these connections should be established:
// - GAM
@ -102,15 +120,8 @@ fn xmain() -> ! {
.register_name(api::SERVER_NAME_GFX, Some(2))
.expect("can't register server");
// Create a new monochrome simulator display.
let mut display = XousDisplay::new();
//let mut fb = display.native_buffer();
//let mut b2cursor = blitstr2::Cursor::new(0, 0, 16);
//blitstr2::paint_str(&mut fb, blitstr2::ClipRect::new(0, 0, 100, 100), &mut b2cursor, "test");
draw_boot_logo(&mut display);
let fontregion = map_fonts();
let screen_clip = Rectangle::new(Point::new(0, 0), display.screen_size());
display.redraw();
@ -122,420 +133,426 @@ fn xmain() -> ! {
let mut bulkread = BulkRead::default(); // holding buffer for bulk reads; wastes ~8k when not in use, but saves a lot of copy/init for each iteration of the read
let ticktimer = ticktimer_server::Ticktimer::new().unwrap();
#[cfg(feature = "testing")]
testing::tests();
loop {
let mut msg = xous::receive_message(sid).unwrap();
log::trace!("Message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
display.suspend();
susres
.suspend_until_resume(token)
.expect("couldn't execute suspend/resume");
display.resume();
}),
Some(Opcode::DrawClipObject) => {
let buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let obj = buffer.to_original::<ClipObject, _>().unwrap();
log::trace!("DrawClipObject {:?}", obj);
match obj.obj {
ClipObjectType::Line(line) => {
op::line(display.native_buffer(), line, Some(obj.clip), false);
}
ClipObjectType::XorLine(line) => {
op::line(display.native_buffer(), line, Some(obj.clip), true);
}
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));
}
}
}
Some(Opcode::DrawClipObjectList) => {
let buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let list_ipc = buffer.to_original::<ClipObjectList, _>().unwrap();
for maybe_item in list_ipc.list.iter() {
if let Some(obj) = maybe_item {
match obj.obj {
ClipObjectType::Line(line) => {
op::line(display.native_buffer(), line, Some(obj.clip), false);
}
ClipObjectType::XorLine(line) => {
op::line(display.native_buffer(), line, Some(obj.clip), true);
}
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));
}
if !is_panic.load(Ordering::Relaxed) { // non-panic graphics operations if we are in a panic situation
let mut msg = xous::receive_message(sid).unwrap();
log::trace!("Message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
display.suspend();
susres
.suspend_until_resume(token)
.expect("couldn't execute suspend/resume");
display.resume();
}),
Some(Opcode::DrawClipObject) => {
let buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let obj = buffer.to_original::<ClipObject, _>().unwrap();
log::trace!("DrawClipObject {:?}", obj);
match obj.obj {
ClipObjectType::Line(line) => {
op::line(display.native_buffer(), line, Some(obj.clip), false);
}
ClipObjectType::XorLine(line) => {
op::line(display.native_buffer(), line, Some(obj.clip), true);
}
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));
}
} else {
// stop at the first None entry -- if the sender packed the list with a hole in it, that's their bad
break;
}
}
}
Some(Opcode::DrawTextView) => {
let mut buffer = unsafe {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
};
let mut tv = buffer.to_original::<TextView, _>().unwrap();
if tv.clip_rect.is_none() {
continue;
} // if no clipping rectangle is specified, nothing to draw
// this is the clipping rectangle of the canvas in screen coordinates
let clip_rect = tv.clip_rect.unwrap();
// this is the translation vector to and from screen space
let screen_offset: Point = tv.clip_rect.unwrap().tl;
let typeset_extent = match tv.bounds_hint {
TextBounds::BoundingBox(r) =>
Pt::new(r.br().x - r.tl().x - tv.margin.x * 2, r.br().y - r.tl().y - tv.margin.y * 2),
TextBounds::GrowableFromBr(br, width) =>
Pt::new(width as i16 - tv.margin.x * 2, br.y - tv.margin.y * 2),
TextBounds::GrowableFromBl(bl, width) =>
Pt::new(width as i16 - tv.margin.x * 2, bl.y - tv.margin.y * 2),
TextBounds::GrowableFromTl(tl, width) =>
Pt::new(width as i16 - tv.margin.x * 2, (clip_rect.br().y - clip_rect.tl().y - tl.y) - tv.margin.y * 2),
TextBounds::GrowableFromTr(tr, width) =>
Pt::new(width as i16 - tv.margin.x * 2, (clip_rect.br().y - clip_rect.tl().y - tr.y) - tv.margin.y * 2),
};
let mut typesetter = Typesetter::setup(
tv.to_str(),
&typeset_extent,
&tv.style,
if let Some(i) = tv.insertion { Some(i as usize) } else { None }
);
let composition = typesetter.typeset(
if tv.ellipsis {
OverflowStrategy::Ellipsis
} else {
OverflowStrategy::Abort
Some(Opcode::DrawClipObjectList) => {
let buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let list_ipc = buffer.to_original::<ClipObjectList, _>().unwrap();
for maybe_item in list_ipc.list.iter() {
if let Some(obj) = maybe_item {
match obj.obj {
ClipObjectType::Line(line) => {
op::line(display.native_buffer(), line, Some(obj.clip), false);
}
ClipObjectType::XorLine(line) => {
op::line(display.native_buffer(), line, Some(obj.clip), true);
}
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));
}
}
} else {
// stop at the first None entry -- if the sender packed the list with a hole in it, that's their bad
break;
}
}
);
let composition_top_left = match tv.bounds_hint {
TextBounds::BoundingBox(r) =>
r.tl().add(tv.margin),
TextBounds::GrowableFromBr(br, _width) =>
Point::new(br.x - (composition.bb_width() as i16 + tv.margin.x),
br.y - (composition.bb_height() as i16 + tv.margin.y)),
TextBounds::GrowableFromBl(bl, _width) =>
Point::new(bl.x + tv.margin.x, bl.y - (composition.bb_height() as i16 + tv.margin.y)),
TextBounds::GrowableFromTl(tl, _width) =>
tl.add(tv.margin),
TextBounds::GrowableFromTr(tr, _width) =>
Point::new(tr.x - (composition.bb_width() as i16 + tv.margin.x), tr.y + tv.margin.y),
}
.add(screen_offset);
Some(Opcode::DrawTextView) => {
let mut buffer = unsafe {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
};
let mut tv = buffer.to_original::<TextView, _>().unwrap();
// compute the clear rectangle -- the border is already in screen coordinates, just add the margin around it
let mut clear_rect = match tv.bounds_hint {
TextBounds::BoundingBox(mut r) => {
r.translate(screen_offset);
r
}
_ => {
// composition_top_left already had a screen_offset added when it was computed. just margin it out
let mut r = Rectangle::new(
composition_top_left,
composition_top_left.add(Point::new(composition.bb_width() as _, composition.bb_height() as _))
);
r.margin_out(tv.margin);
r
if tv.clip_rect.is_none() {
continue;
} // if no clipping rectangle is specified, nothing to draw
// this is the clipping rectangle of the canvas in screen coordinates
let clip_rect = tv.clip_rect.unwrap();
// this is the translation vector to and from screen space
let screen_offset: Point = tv.clip_rect.unwrap().tl;
let typeset_extent = match tv.bounds_hint {
TextBounds::BoundingBox(r) =>
Pt::new(r.br().x - r.tl().x - tv.margin.x * 2, r.br().y - r.tl().y - tv.margin.y * 2),
TextBounds::GrowableFromBr(br, width) =>
Pt::new(width as i16 - tv.margin.x * 2, br.y - tv.margin.y * 2),
TextBounds::GrowableFromBl(bl, width) =>
Pt::new(width as i16 - tv.margin.x * 2, bl.y - tv.margin.y * 2),
TextBounds::GrowableFromTl(tl, width) =>
Pt::new(width as i16 - tv.margin.x * 2, (clip_rect.br().y - clip_rect.tl().y - tl.y) - tv.margin.y * 2),
TextBounds::GrowableFromTr(tr, width) =>
Pt::new(width as i16 - tv.margin.x * 2, (clip_rect.br().y - clip_rect.tl().y - tr.y) - tv.margin.y * 2),
};
let mut typesetter = Typesetter::setup(
tv.to_str(),
&typeset_extent,
&tv.style,
if let Some(i) = tv.insertion { Some(i as usize) } else { None }
);
let composition = typesetter.typeset(
if tv.ellipsis {
OverflowStrategy::Ellipsis
} else {
OverflowStrategy::Abort
}
);
let composition_top_left = match tv.bounds_hint {
TextBounds::BoundingBox(r) =>
r.tl().add(tv.margin),
TextBounds::GrowableFromBr(br, _width) =>
Point::new(br.x - (composition.bb_width() as i16 + tv.margin.x),
br.y - (composition.bb_height() as i16 + tv.margin.y)),
TextBounds::GrowableFromBl(bl, _width) =>
Point::new(bl.x + tv.margin.x, bl.y - (composition.bb_height() as i16 + tv.margin.y)),
TextBounds::GrowableFromTl(tl, _width) =>
tl.add(tv.margin),
TextBounds::GrowableFromTr(tr, _width) =>
Point::new(tr.x - (composition.bb_width() as i16 + tv.margin.x), tr.y + tv.margin.y),
}
};
.add(screen_offset);
log::trace!("clip_rect: {:?}", clip_rect);
log::trace!("composition_top_left: {:?}", composition_top_left);
log::trace!("clear_rect: {:?}", clear_rect);
// draw the bubble/border and/or clear the background area
let bordercolor = if tv.draw_border {
Some(PixelColor::Dark)
} else {
None
};
let borderwidth: i16 = if tv.draw_border {
tv.border_width as i16
} else {
0
};
let fillcolor = if tv.clear_area || tv.invert {
if tv.invert {
// compute the clear rectangle -- the border is already in screen coordinates, just add the margin around it
let mut clear_rect = match tv.bounds_hint {
TextBounds::BoundingBox(mut r) => {
r.translate(screen_offset);
r
}
_ => {
// composition_top_left already had a screen_offset added when it was computed. just margin it out
let mut r = Rectangle::new(
composition_top_left,
composition_top_left.add(Point::new(composition.bb_width() as _, composition.bb_height() as _))
);
r.margin_out(tv.margin);
r
}
};
log::trace!("clip_rect: {:?}", clip_rect);
log::trace!("composition_top_left: {:?}", composition_top_left);
log::trace!("clear_rect: {:?}", clear_rect);
// draw the bubble/border and/or clear the background area
let bordercolor = if tv.draw_border {
Some(PixelColor::Dark)
} else {
Some(PixelColor::Light)
}
} else {
None
};
clear_rect.style = DrawStyle {
fill_color: fillcolor,
stroke_color: bordercolor,
stroke_width: borderwidth,
};
if !tv.dry_run() {
if tv.rounded_border.is_some() {
op::rounded_rectangle(
display.native_buffer(),
RoundedRectangle::new(clear_rect, tv.rounded_border.unwrap() as _),
tv.clip_rect,
);
None
};
let borderwidth: i16 = if tv.draw_border {
tv.border_width as i16
} else {
op::rectangle(display.native_buffer(), clear_rect, tv.clip_rect);
0
};
let fillcolor = if tv.clear_area || tv.invert {
if tv.invert {
Some(PixelColor::Dark)
} else {
Some(PixelColor::Light)
}
} else {
None
};
clear_rect.style = DrawStyle {
fill_color: fillcolor,
stroke_color: bordercolor,
stroke_width: borderwidth,
};
if !tv.dry_run() {
if tv.rounded_border.is_some() {
op::rounded_rectangle(
display.native_buffer(),
RoundedRectangle::new(clear_rect, tv.rounded_border.unwrap() as _),
tv.clip_rect,
);
} else {
op::rectangle(display.native_buffer(), clear_rect, tv.clip_rect);
}
}
}
// for now, if we're in braille mode, emit all text to the debug log so we can see it
//if cfg!(feature = "braille") {
// log::info!("{}", tv);
//}
// for now, if we're in braille mode, emit all text to the debug log so we can see it
//if cfg!(feature = "braille") {
// log::info!("{}", tv);
//}
if !tv.dry_run() {
// note: make the clip rect `tv.clip_rect.unwrap()` if you want to debug wordwrapping artifacts; otherwise smallest_rect masks some problems
let smallest_rect = clear_rect.clip_with(tv.clip_rect.unwrap())
.unwrap_or(Rectangle::new(Point::new(0, 0), Point::new(0, 0,)));
composition.render(display.native_buffer(), composition_top_left, tv.invert, smallest_rect);
}
// type mismatch for now, replace this with a simple equals once we sort that out
tv.cursor.pt.x = composition.final_cursor().pt.x;
tv.cursor.pt.y = composition.final_cursor().pt.y;
tv.cursor.line_height = composition.final_cursor().line_height;
if !tv.dry_run() {
// note: make the clip rect `tv.clip_rect.unwrap()` if you want to debug wordwrapping artifacts; otherwise smallest_rect masks some problems
let smallest_rect = clear_rect.clip_with(tv.clip_rect.unwrap())
.unwrap_or(Rectangle::new(Point::new(0, 0), Point::new(0, 0,)));
composition.render(display.native_buffer(), composition_top_left, tv.invert, smallest_rect);
}
// type mismatch for now, replace this with a simple equals once we sort that out
tv.cursor.pt.x = composition.final_cursor().pt.x;
tv.cursor.pt.y = composition.final_cursor().pt.y;
tv.cursor.line_height = composition.final_cursor().line_height;
tv.bounds_computed = Some(
clear_rect
);
log::trace!("cursor ret {:?}, bounds ret {:?}", tv.cursor, tv.bounds_computed);
// pack our data back into the buffer to return
buffer.replace(tv).unwrap();
}
Some(Opcode::Flush) => {
log::trace!("***gfx flush*** redraw##");
display.update();
display.redraw();
}
Some(Opcode::Clear) => {
let mut r = Rectangle::full_screen();
r.style = DrawStyle::new(PixelColor::Light, PixelColor::Light, 0);
op::rectangle(display.native_buffer(), r, screen_clip.into())
}
Some(Opcode::Line) => msg_scalar_unpack!(msg, p1, p2, style, _, {
let l =
Line::new_with_style(Point::from(p1), Point::from(p2), DrawStyle::from(style));
op::line(display.native_buffer(), l, screen_clip.into(), false);
}),
Some(Opcode::Rectangle) => msg_scalar_unpack!(msg, tl, br, style, _, {
let r = Rectangle::new_with_style(
Point::from(tl),
Point::from(br),
DrawStyle::from(style),
);
op::rectangle(display.native_buffer(), r, screen_clip.into());
}),
Some(Opcode::RoundedRectangle) => msg_scalar_unpack!(msg, tl, br, style, r, {
let rr = RoundedRectangle::new(
Rectangle::new_with_style(
tv.bounds_computed = Some(
clear_rect
);
log::trace!("cursor ret {:?}, bounds ret {:?}", tv.cursor, tv.bounds_computed);
// pack our data back into the buffer to return
buffer.replace(tv).unwrap();
}
Some(Opcode::Flush) => {
log::trace!("***gfx flush*** redraw##");
display.update();
display.redraw();
}
Some(Opcode::Clear) => {
let mut r = Rectangle::full_screen();
r.style = DrawStyle::new(PixelColor::Light, PixelColor::Light, 0);
op::rectangle(display.native_buffer(), r, screen_clip.into())
}
Some(Opcode::Line) => msg_scalar_unpack!(msg, p1, p2, style, _, {
let l =
Line::new_with_style(Point::from(p1), Point::from(p2), DrawStyle::from(style));
op::line(display.native_buffer(), l, screen_clip.into(), false);
}),
Some(Opcode::Rectangle) => msg_scalar_unpack!(msg, tl, br, style, _, {
let r = Rectangle::new_with_style(
Point::from(tl),
Point::from(br),
DrawStyle::from(style),
),
r as _,
);
op::rounded_rectangle(display.native_buffer(), rr, screen_clip.into());
}),
Some(Opcode::Circle) => msg_scalar_unpack!(msg, center, radius, style, _, {
let c = Circle::new_with_style(
Point::from(center),
radius as _,
DrawStyle::from(style),
);
op::circle(display.native_buffer(), c, screen_clip.into());
}),
Some(Opcode::ScreenSize) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let pt = display.screen_size();
xous::return_scalar2(msg.sender, pt.x as usize, pt.y as usize)
.expect("couldn't return ScreenSize request");
}),
Some(Opcode::QueryGlyphProps) => msg_blocking_scalar_unpack!(msg, style, _, _, _, {
let glyph = GlyphStyle::from(style);
xous::return_scalar2(
msg.sender,
glyph.into(),
glyph_to_height_hint(glyph),
)
.expect("could not return QueryGlyphProps request");
}),
Some(Opcode::DrawSleepScreen) => msg_scalar_unpack!(msg, _, _, _, _, {
display.blit_screen(&logo::LOGO_MAP);
display.update();
display.redraw();
}),
Some(Opcode::Devboot) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena != 0 {
display.set_devboot(true);
} else {
display.set_devboot(false);
}
}),
Some(Opcode::RestartBulkRead) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
bulkread.from_offset = 0;
xous::return_scalar(msg.sender, 0)
.expect("couldn't ack that bulk read pointer was reset");
}),
Some(Opcode::BulkReadFonts) => {
let fontlen = fontmap::FONT_TOTAL_LEN as u32 + 8;
let mut buf = unsafe {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
};
//let mut bulkread = buf.as_flat::<BulkRead, _>().unwrap(); // try to skip the copy/init step by using a persistent structure
let fontslice = fontregion.as_slice::<u8>();
assert!(fontlen <= fontslice.len() as u32);
if bulkread.from_offset >= fontlen {
log::error!(
"BulkReadFonts attempt to read out of bound on the font area; ignoring!"
);
continue;
}
let readlen = if bulkread.from_offset + bulkread.buf.len() as u32 > fontlen {
// returns what is readable of the last bit; anything longer than the fontlen is undefined/invalid
fontlen as usize - bulkread.from_offset as usize
} else {
bulkread.buf.len()
};
for (&src, dst) in fontslice
[bulkread.from_offset as usize..bulkread.from_offset as usize + readlen]
.iter()
.zip(bulkread.buf.iter_mut())
{
*dst = src;
}
bulkread.len = readlen as u32;
bulkread.from_offset += readlen as u32;
buf.replace(bulkread).unwrap();
}
Some(Opcode::TestPattern) => msg_blocking_scalar_unpack!(msg, duration, _, _, _, {
let mut stashmem = xous::syscall::map_memory(
None,
None,
((backend::FB_SIZE * 4) + 4096) & !4095,
xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map stash frame buffer");
let stash = &mut stashmem.as_slice_mut()[..backend::FB_SIZE];
for (&src, dst) in display.as_slice().iter().zip(stash.iter_mut()) {
*dst = src;
}
for lines in 0..backend::FB_LINES { // mark all lines dirty
stash[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000;
}
let ticktimer = ticktimer_server::Ticktimer::new().unwrap();
let start_time = ticktimer.elapsed_ms();
let mut testmem = xous::syscall::map_memory(
None,
None,
((backend::FB_SIZE * 4) + 4096) & !4095,
xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map stash frame buffer");
let testpat = &mut testmem.as_slice_mut()[..backend::FB_SIZE];
const DWELL: usize = 1000;
while ticktimer.elapsed_ms() - start_time < duration as u64 {
// all black
for w in testpat.iter_mut() {
*w = 0;
}
for lines in 0..backend::FB_LINES { // mark dirty bits
testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000;
}
display.blit_screen(testpat);
op::rectangle(display.native_buffer(), r, screen_clip.into());
}),
Some(Opcode::RoundedRectangle) => msg_scalar_unpack!(msg, tl, br, style, r, {
let rr = RoundedRectangle::new(
Rectangle::new_with_style(
Point::from(tl),
Point::from(br),
DrawStyle::from(style),
),
r as _,
);
op::rounded_rectangle(display.native_buffer(), rr, screen_clip.into());
}),
Some(Opcode::Circle) => msg_scalar_unpack!(msg, center, radius, style, _, {
let c = Circle::new_with_style(
Point::from(center),
radius as _,
DrawStyle::from(style),
);
op::circle(display.native_buffer(), c, screen_clip.into());
}),
Some(Opcode::ScreenSize) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let pt = display.screen_size();
xous::return_scalar2(msg.sender, pt.x as usize, pt.y as usize)
.expect("couldn't return ScreenSize request");
}),
Some(Opcode::QueryGlyphProps) => msg_blocking_scalar_unpack!(msg, style, _, _, _, {
let glyph = GlyphStyle::from(style);
xous::return_scalar2(
msg.sender,
glyph.into(),
glyph_to_height_hint(glyph),
)
.expect("could not return QueryGlyphProps request");
}),
Some(Opcode::DrawSleepScreen) => msg_scalar_unpack!(msg, _, _, _, _, {
display.blit_screen(&logo::LOGO_MAP);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
// all white
for w in testpat.iter_mut() {
*w = 0xFFFF_FFFF;
}),
Some(Opcode::Devboot) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena != 0 {
display.set_devboot(true);
} else {
display.set_devboot(false);
}
}),
Some(Opcode::RestartBulkRead) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
bulkread.from_offset = 0;
xous::return_scalar(msg.sender, 0)
.expect("couldn't ack that bulk read pointer was reset");
}),
Some(Opcode::BulkReadFonts) => {
let fontlen = fontmap::FONT_TOTAL_LEN as u32 + 8;
let mut buf = unsafe {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
};
//let mut bulkread = buf.as_flat::<BulkRead, _>().unwrap(); // try to skip the copy/init step by using a persistent structure
let fontslice = fontregion.as_slice::<u8>();
assert!(fontlen <= fontslice.len() as u32);
if bulkread.from_offset >= fontlen {
log::error!(
"BulkReadFonts attempt to read out of bound on the font area; ignoring!"
);
continue;
}
let readlen = if bulkread.from_offset + bulkread.buf.len() as u32 > fontlen {
// returns what is readable of the last bit; anything longer than the fontlen is undefined/invalid
fontlen as usize - bulkread.from_offset as usize
} else {
bulkread.buf.len()
};
for (&src, dst) in fontslice
[bulkread.from_offset as usize..bulkread.from_offset as usize + readlen]
.iter()
.zip(bulkread.buf.iter_mut())
{
*dst = src;
}
bulkread.len = readlen as u32;
bulkread.from_offset += readlen as u32;
buf.replace(bulkread).unwrap();
}
Some(Opcode::TestPattern) => msg_blocking_scalar_unpack!(msg, duration, _, _, _, {
let mut stashmem = xous::syscall::map_memory(
None,
None,
((backend::FB_SIZE * 4) + 4096) & !4095,
xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map stash frame buffer");
let stash = &mut stashmem.as_slice_mut()[..backend::FB_SIZE];
for (&src, dst) in display.as_slice().iter().zip(stash.iter_mut()) {
*dst = src;
}
for lines in 0..backend::FB_LINES { // mark all lines dirty
stash[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000;
}
// dirty bits already set
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
// vertical bars
for lines in 0..backend::FB_LINES {
for words in 0..backend::FB_WIDTH_WORDS {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xaaaa_aaaa;
let start_time = ticktimer.elapsed_ms();
let mut testmem = xous::syscall::map_memory(
None,
None,
((backend::FB_SIZE * 4) + 4096) & !4095,
xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map stash frame buffer");
let testpat = &mut testmem.as_slice_mut()[..backend::FB_SIZE];
const DWELL: usize = 1000;
while ticktimer.elapsed_ms() - start_time < duration as u64 {
// all black
for w in testpat.iter_mut() {
*w = 0;
}
}
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
for lines in 0..backend::FB_LINES {
for words in 0..backend::FB_WIDTH_WORDS {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x5555_5555;
for lines in 0..backend::FB_LINES { // mark dirty bits
testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000;
}
}
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
// horiz bars
for lines in 0..backend::FB_LINES {
for words in 0..backend::FB_WIDTH_WORDS {
if lines % 2 == 0 {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x0;
} else {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xffff_ffff;
// all white
for w in testpat.iter_mut() {
*w = 0xFFFF_FFFF;
}
// dirty bits already set
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
// vertical bars
for lines in 0..backend::FB_LINES {
for words in 0..backend::FB_WIDTH_WORDS {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xaaaa_aaaa;
}
}
testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000;
}
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
for lines in 0..backend::FB_LINES {
for words in 0..backend::FB_WIDTH_WORDS {
if lines % 2 == 1 {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x0;
} else {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xffff_ffff;
for lines in 0..backend::FB_LINES {
for words in 0..backend::FB_WIDTH_WORDS {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x5555_5555;
}
}
testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000;
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
// horiz bars
for lines in 0..backend::FB_LINES {
for words in 0..backend::FB_WIDTH_WORDS {
if lines % 2 == 0 {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x0;
} else {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xffff_ffff;
}
}
testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000;
}
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
for lines in 0..backend::FB_LINES {
for words in 0..backend::FB_WIDTH_WORDS {
if lines % 2 == 1 {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0x0;
} else {
testpat[lines * backend::FB_WIDTH_WORDS + words] = 0xffff_ffff;
}
}
testpat[lines * backend::FB_WIDTH_WORDS + (backend::FB_WIDTH_WORDS - 1)] |= 0x1_0000;
}
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
}
display.blit_screen(testpat);
display.update();
display.redraw();
ticktimer.sleep_ms(DWELL).unwrap();
display.blit_screen(stash);
xous::return_scalar(msg.sender, duration).expect("couldn't ack test pattern");
}),
Some(Opcode::Quit) => break,
None => {
log::error!("received opcode scalar that is not handled");
}
display.blit_screen(stash);
xous::return_scalar(msg.sender, duration).expect("couldn't ack test pattern");
}),
Some(Opcode::Quit) => break,
None => {
log::error!("received opcode scalar that is not handled");
}
} else {
// this is effectively an abort, because this is long enough for the WDT to fire and reboot the system
ticktimer.sleep_ms(10_000).unwrap();
}
}
log::trace!("main loop exit, destroying servers");

View file

@ -0,0 +1,233 @@
use std::thread;
use core::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use utralib::generated::*;
const PANIC_STD_SERVER: &[u8; 16] = b"panic-to-screen!";
/// We can have no allocations inside this, and ideally, it's as minimal as possible.
///
/// The graphics handler code and font renderer code are duplicated into this module to
/// minimize cross-thread dependencies.
///
/// Some simplifying assumptions include:
/// - Only Latin, monospace (16-px wide) characters from the `mono` font set.
/// - Panics occupy a fixed area in the center of the screen, that can only hold
/// a limited amount of text: 304-px x 384-px text area = 40 char x 24 lines = 960 chars
/// - The Panic frame is slightly larger to give a cosmetic border, a total of 320 x 400 px
/// - Panics are black background with white text to distinguish them as secured system messages.
/// - The glyph set is passed into the handler as a static structure.
/// - Panics can't be dismissed, and should persist even if other threads are capable of running.
/// Thus there is a variable shared with the parent thread to stop redraws permanently in the
/// case of a panic.
///
/// Frame buffer is 336 px wide, which is 10.5 32-bit words. The excess 16 bits are the dirty bit field.
use crate::{
backend::{FB_WIDTH_PIXELS, FB_WIDTH_WORDS, FB_SIZE},
api::{PixelColor, GlyphSprite}, blitstr2::NULL_GLYPH_SPRITE
};
const TOP_OFFSET: usize = 48;
const WIDTH_CHARS: usize = 40;
const HEIGHT_CHARS: usize = 24;
const TOTAL_CHARS: usize = WIDTH_CHARS * HEIGHT_CHARS;
// these are fixed by the monospace font
const GLYPH_HEIGHT: usize = 15;
const GLYPH_WIDTH: usize = 7;
// this can be adjusted to create more border around the panic box
const TEXT_MARGIN: usize = 8;
// some derived constants to help with layout
const BOTTOM_LINE: usize = TOP_OFFSET + HEIGHT_CHARS * GLYPH_HEIGHT + TEXT_MARGIN * 2;
const LEFT_EDGE: usize = (FB_WIDTH_PIXELS - (WIDTH_CHARS * GLYPH_WIDTH + TEXT_MARGIN * 2)) / 2; // 24
const RIGHT_EDGE: usize = FB_WIDTH_PIXELS - LEFT_EDGE; // 312
pub(crate) fn panic_handler_thread(
is_panic: Arc::<AtomicBool>,
hwfb: u32,
control: u32,
) {
thread::spawn({
move || {
let panic_server = xous::create_server_with_address(PANIC_STD_SERVER)
.expect("Couldn't create panic server");
let mut display = unsafe { PanicDisplay::new(hwfb, control) };
let mut panic_text = xous_ipc::String::<TOTAL_CHARS>::new();
loop {
let msg = xous::receive_message(panic_server).unwrap();
// this will put the graphics renderer in panic mode.
if !is_panic.load(Ordering::Relaxed) {
// this locks out updates from the main loop
is_panic.store(true, Ordering::Relaxed);
display.panic_rectangle();
display.append_string(" ~~Guru Meditation~~\n\n");
display.update_dirty();
}
let body = match msg.body.memory_message() {
Some(body) => body,
None => {
log::error!("Incorrect message type to panic renderer");
return;
}
};
let len = match body.valid {
Some(v) => v,
None => continue, // ignore, don't fail
}.get();
let s = unsafe{core::str::from_utf8_unchecked(
&body.buf.as_slice()[..len]
)};
display.append_string(s);
panic_text.append(
unsafe{
core::str::from_utf8_unchecked(
&body.buf.as_slice()[..len]
)
}
).ok();
}
}
});
}
/// All-in-one object to manage a framebuffer and layout text.
struct PanicDisplay<'a> {
fb: &'a mut [u32],
csr: CSR::<u32>,
x: usize,
y: usize,
}
impl<'a> PanicDisplay<'a> {
/// # Safety
///
/// This function takes "plain old 32-bit numbers" and transforms them
/// into hardware pointers to the frame buffer and CSR offsets. It's meant
/// to be pared with the `hw_regs` output from the XousDisplay object, and
/// there will be frame buffer conflicts unless some kind of mutex is wrapped
/// around any other code that might compete for access to these resources.
unsafe fn new(raw_fb: u32, control: u32) -> Self {
PanicDisplay {
fb: core::slice::from_raw_parts_mut(raw_fb as *mut u32, FB_SIZE),
csr: CSR::new(control as *mut u32),
x: TEXT_MARGIN,
y: TEXT_MARGIN,
}
}
fn update_dirty(&mut self) {
self.csr.wfo(utra::memlcd::COMMAND_UPDATEDIRTY, 1);
while self.busy() {}
}
fn busy(&self) -> bool {
self.csr.rf(utra::memlcd::BUSY_BUSY) == 1
}
fn put_pixel(&mut self, x: usize, y: usize, color: PixelColor) {
if color == PixelColor::Light {
self.fb[(x + y * FB_WIDTH_WORDS * 32) / 32] |= 1 << (x % 32)
} else {
self.fb[(x + y * FB_WIDTH_WORDS * 32) / 32] &= !(1 << (x % 32))
}
// set the dirty bit on the line that contains the pixel
self.fb[y * FB_WIDTH_WORDS + (FB_WIDTH_WORDS - 1)] |= 0x1_0000;
}
/// draw a black rectangle into which all the characters are placed.
fn panic_rectangle(&mut self) {
for y in TOP_OFFSET..BOTTOM_LINE {
for x in LEFT_EDGE..RIGHT_EDGE {
self.put_pixel(x, y, PixelColor::Dark);
}
}
}
/// Blit a glyph
/// Examples of word alignment for destination frame buffer:
/// 1. Fits in word: xr:1..7 => (data[0].bit_30)->(data[0].bit_26), mask:0x7c00_0000
/// 2. Spans words: xr:30..36 => (data[0].bit_01)->(data[1].bit_29), mask:[0x0000_0003,0xe000_000]
///
fn draw_glyph(&mut self, x: usize, y: usize, gs: GlyphSprite) {
const SPRITE_PX: i16 = 16;
const SPRITE_WORDS: i16 = 8;
if gs.glyph.len() < SPRITE_WORDS as usize {
// Fail silently if the glyph slice was too small
// TODO: Maybe return an error? Not sure which way is better.
return;
}
let high = gs.high as i16;
let wide = gs.wide as i16;
if high > SPRITE_PX || wide > SPRITE_PX {
// Fail silently if glyph height or width is out of spec
// TODO: Maybe return an error?
return;
}
// Calculate word alignment for destination buffer
let x0 = (x + LEFT_EDGE) as i16;
let x1 = (x + LEFT_EDGE) as i16 + wide - 1;
let dest_low_word = x0 >> 5;
let dest_high_word = x1 >> 5;
let px_in_dest_low_word = 32 - (x0 & 0x1f);
// Blit it (use glyph height to avoid blitting empty rows)
let mut row_base = (y + TOP_OFFSET) as i16 * FB_WIDTH_WORDS as i16;
let row_upper_limit = BOTTOM_LINE as i16 * FB_WIDTH_WORDS as i16;
let row_lower_limit = TOP_OFFSET as i16 * FB_WIDTH_WORDS as i16;
let glyph = gs.glyph;
for y in 0..high as usize {
if row_base >= row_upper_limit {
// Clip anything that would run off the end of the frame buffer
break;
}
if row_base >= row_lower_limit {
// Unpack pixels for this glyph row.
// CAUTION: some math magic happening here...
// when y==0, this does (glyph[0] >> 0) & mask,
// when y==1, this does (glyph[0] >> 16) & mask,
// when y==2, this does (glyph[1] >> 0) & mask,
// ...
let mask = 0x0000ffff as u32;
let shift = (y as u32 & 1) << 4;
let pattern = (glyph[y >> 1] >> shift) & mask;
// compute partial masks to prevent glyphs from "spilling over" the clip rectangle
let mut partial_mask_lo = 0xffff_ffff;
let mut partial_mask_hi = 0xffff_ffff;
if x0 < LEFT_EDGE as i16 || x1 >= RIGHT_EDGE as i16 {
let x0a = if x0 < LEFT_EDGE as i16 { RIGHT_EDGE as i16 } else { x0 };
let x1a = if x1 >= LEFT_EDGE as i16 { RIGHT_EDGE as i16 } else { x1 };
let mut ones = (1u64 << ((x1a - x0a) as u64 + 1)) - 1;
ones <<= x0a as u64 & 0x1f;
partial_mask_lo = ones as u32;
partial_mask_hi = (ones >> 32) as u32;
}
// XOR glyph pixels onto destination buffer. Note that despite the masks above, we will not render
// partial glyphs that cross the absolute bounds of the left and right edge of the screen.
if x0 >= 0 && x1 < FB_WIDTH_PIXELS as i16 {
self.fb[(row_base + dest_low_word) as usize] ^= (pattern << (32 - px_in_dest_low_word)) & partial_mask_lo;
if wide > px_in_dest_low_word {
self.fb[(row_base + dest_high_word) as usize] ^= (pattern >> px_in_dest_low_word) & partial_mask_hi;
}
}
self.fb[(row_base as usize + FB_WIDTH_WORDS - 1) as usize] |= 0x1_0000; // set the dirty bit on the line
}
// Advance destination offset using + instead of * to maybe save some CPU cycles
row_base += FB_WIDTH_WORDS as i16;
}
}
/// start laying out the string from the top left and just wrap character by character, considering newlines
fn append_string(&mut self, s: &str) {
for ch in s.chars() {
if ch == '\n' {
self.y += GLYPH_HEIGHT;
self.x = TEXT_MARGIN;
continue;
}
self.draw_glyph(self.x, self.y, crate::blitstr2::mono_glyph(ch).unwrap_or(NULL_GLYPH_SPRITE));
self.x += GLYPH_WIDTH;
if self.x >= WIDTH_CHARS * GLYPH_WIDTH {
self.x = TEXT_MARGIN;
self.y += GLYPH_HEIGHT;
}
}
}
}