diff --git a/services/graphics-server/src/blitstr2/blit.rs b/services/graphics-server/src/blitstr2/blit.rs index 3e21441fc..e0cf16a68 100644 --- a/services/graphics-server/src/blitstr2/blit.rs +++ b/services/graphics-server/src/blitstr2/blit.rs @@ -13,6 +13,9 @@ pub const NULL_GLYPH_SPRITE: fonts::GlyphSprite = fonts::GlyphSprite { glyph: &NULL_GLYPH, wide: 8u8, high: 12u8, + ch: '\u{0}', + invert: false, + insert: false, }; /// Unicode replacement character diff --git a/services/graphics-server/src/blitstr2/cursor.rs b/services/graphics-server/src/blitstr2/cursor.rs index b6eeaa6d4..b5f0ef996 100644 --- a/services/graphics-server/src/blitstr2/cursor.rs +++ b/services/graphics-server/src/blitstr2/cursor.rs @@ -48,21 +48,6 @@ impl Cursor { line_height: self.line_height.max(other.line_height) } } - - // adds a space or newline to the cursor depending on if it would fit in the - // max width. Returns `true` if a space is added. Resets the cursor to - // the carriage return "x" specified by `cr_x` if a newline is done. - pub fn space_or_newline(&mut self, space: &GlyphSprite, maxwidth: usize, cr_x: usize) -> bool { - if (self.pt.x + space.wide as usize) < maxwidth { - self.pt.x += space.wide as usize; - true - } else { - self.pt.x = cr_x; - self.pt.y += self.line_height; - self.line_height = 0; - false - } - } } #[cfg(test)] diff --git a/services/graphics-server/src/blitstr2/fonts.rs b/services/graphics-server/src/blitstr2/fonts.rs index a9094f1f8..e9ec48062 100644 --- a/services/graphics-server/src/blitstr2/fonts.rs +++ b/services/graphics-server/src/blitstr2/fonts.rs @@ -27,6 +27,12 @@ pub struct GlyphSprite { pub glyph: &'static [u32], pub wide: u8, pub high: u8, + // the original character + pub ch: char, + // invert rendering for the character - for copy/paste selection regions + pub invert: bool, + // drawn an insertion point after this character + pub insert: bool, } pub fn small_glyph(ch: char) -> Result { @@ -39,6 +45,9 @@ pub fn small_glyph(ch: char) -> Result { glyph: &small::GLYPHS[offset..end], wide: small::WIDTHS[n], high: small::MAX_HEIGHT, + ch, + invert: false, + insert: false, }), false => Err(0), } @@ -57,6 +66,9 @@ pub fn regular_glyph(ch: char) -> Result { glyph: ®ular::GLYPHS[offset..end], wide: regular::WIDTHS[n], high: regular::MAX_HEIGHT, + ch, + invert: false, + insert: false, }), false => Err(0), } @@ -75,6 +87,9 @@ pub fn bold_glyph(ch: char) -> Result { glyph: &bold::GLYPHS[offset..end], wide: bold::WIDTHS[n], high: bold::MAX_HEIGHT, + ch, + invert: false, + insert: false, }), false => Err(0), } @@ -93,6 +108,9 @@ pub fn mono_glyph(ch: char) -> Result { glyph: &mono::GLYPHS[offset..end], wide: mono::WIDTHS[n], high: mono::MAX_HEIGHT, + ch, + invert: false, + insert: false, }), false => Err(0), } @@ -111,6 +129,9 @@ pub fn emoji_glyph(ch: char) -> Result { glyph: &emoji::GLYPHS[offset..end], wide: emoji::MAX_HEIGHT, // yes, use height for wide high: emoji::MAX_HEIGHT, + ch, + invert: false, + insert: false, }), false => Err(0), } @@ -129,6 +150,9 @@ pub fn zh_glyph(ch: char) -> Result { glyph: &zh::GLYPHS[offset..end], wide: zh::MAX_HEIGHT, // yes, use height for wide high: zh::MAX_HEIGHT, + ch, + invert: false, + insert: false, }), false => Err(0), } @@ -147,6 +171,9 @@ pub fn ja_glyph(ch: char) -> Result { glyph: &ja::GLYPHS[offset..end], wide: ja::MAX_HEIGHT, // yes, use height for wide high: ja::MAX_HEIGHT, + ch, + invert: false, + insert: false, }), false => Err(0), } @@ -165,6 +192,9 @@ pub fn kr_glyph(ch: char) -> Result { glyph: &kr::GLYPHS[offset..end], wide: kr::MAX_HEIGHT, // yes, use height for wide high: kr::MAX_HEIGHT, + ch, + invert: false, + insert: false, }), false => Err(0), } diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index f3efba908..b529ffbef 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -32,6 +32,9 @@ use xous_ipc::Buffer; mod fontmap; use api::BulkRead; +use crate::wordwrap::*; +use core::ops::Add; + fn draw_boot_logo(display: &mut XousDisplay) { display.blit_screen(&poweron::LOGO_MAP); } @@ -199,92 +202,52 @@ fn xmain() -> ! { // this is the clipping rectangle of the canvas in screen coordinates let clip_rect = tv.clip_rect.unwrap(); - // the bounds hint is given in relative coordinates from the textview's origin. Translate it to screen coordinates. - let bounds_hint_screen = tv.bounds_hint.translate(clip_rect.tl()); - let mut border = if let Some(mut precomputed) = tv.bounds_computed { - // preferentially use a pre-computed bounds, if there is one - // translate the precomputed rectangle to screen coordinates - precomputed.translate(clip_rect.tl()); - blitstr2::ClipRect::new( - precomputed.tl().x as usize, - precomputed.tl().y as usize, - precomputed.br().x as usize, - precomputed.br().y as usize) - } else { - match bounds_hint_screen { - // bounding box is literally this box, no other margining to be considered - TextBounds::BoundingBox(r) => { - blitstr2::ClipRect::new( - r.tl().x as usize, - r.tl().y as usize, - r.br().x as usize, - r.br().y as usize, - ) - } - TextBounds::GrowableFromBr(br, width) => { - if !clip_rect.intersects_point(br) { - continue; - } - blitstr2::ClipRect::new( - if (br.x - width as i16) > (clip_rect.tl().x + tv.margin.x) { - (br.x - width as i16) as usize - } else { - (clip_rect.tl().x + tv.margin.x) as usize - }, - (clip_rect.tl().y + tv.margin.y) as usize, - (br.x - tv.margin.x) as usize, - (br.y - tv.margin.y) as usize, - ) - } - TextBounds::GrowableFromTl(tl, width) => { - if !clip_rect.intersects_point(tl) { - continue; - } - blitstr2::ClipRect::new( - (tl.x + tv.margin.x) as usize, - (tl.y + tv.margin.y) as usize, - if (tl.x + width as i16 + 2 * tv.margin.x) < clip_rect.br().x { - (tl.x + width as i16 + tv.margin.x) as usize - } else { - (clip_rect.br.x - tv.margin.x) as usize - }, - (clip_rect.br.y - tv.margin.y) as usize - ) - } - TextBounds::GrowableFromBl(bl, width) => { - blitstr2::ClipRect::new( - (bl.x + tv.margin.x) as usize, - (clip_rect.tl.y + tv.margin.y) as usize, - if (bl.x + width as i16 + 2 * tv.margin.x) < clip_rect.br().x { - (bl.x + width as i16 + tv.margin.x) as usize - } else { - (clip_rect.br().x - tv.margin.x) as usize - }, - (bl.y - tv.margin.y) as usize - ) - } - } + let typeset_extent = match tv.bounds_hint { + TextBounds::BoundingBox(r) => + blitstr2::Pt::new((r.br().x - r.tl().x - tv.margin.x * 2) as usize, (r.br().y - r.tl().y - tv.margin.y * 2) as usize), + TextBounds::GrowableFromBr(br, width) => + blitstr2::Pt::new(width as usize - tv.margin.x as usize * 2, br.y as usize - tv.margin.y as usize * 2), + TextBounds::GrowableFromBl(bl, width) => + blitstr2::Pt::new(width as usize - tv.margin.x as usize * 2, bl.y as usize - tv.margin.y as usize * 2), + TextBounds::GrowableFromTl(tl, width) => + blitstr2::Pt::new(width as usize - tv.margin.x as usize * 2, (clip_rect.br().y - clip_rect.tl().y) as usize - tv.margin.y as usize * 2), }; - let mut overflow = false; - log::info!("typesetting {} border {:?}, bounds {:?}", tv.text, border, bounds_hint_screen); let base_style = match tv.style { // a connector for now, we'll eventually depricate the old API GlyphStyle::Small => blitstr2::GlyphStyle::Small, GlyphStyle::Regular => blitstr2::GlyphStyle::Regular, GlyphStyle::Bold => blitstr2::GlyphStyle::Bold, }; - let typeset_words = wordwrap::fit_str_to_clip( - tv.text.as_str().unwrap_or("UTF-8 error"), - &mut border, - &bounds_hint_screen, - /*&tv.style,*/ &base_style, - &mut tv.cursor, - &mut overflow); - - log::info!("wrapped to {:?}", border); + let mut typesetter = Typesetter::setup( + tv.to_str(), + &typeset_extent, + &base_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) + }; // compute the clear rectangle -- the border is already in screen coordinates, just add the margin around it - let mut clear_rect = border.to_rect(); + let mut clear_rect = Rectangle::new( + composition_top_left, + composition_top_left.add(Point::new(composition.bb_width() as _, composition.bb_height() as _)) + ); clear_rect.margin_out(tv.margin); let bordercolor = if tv.draw_border { @@ -327,30 +290,19 @@ fn xmain() -> ! { if cfg!(feature = "braille") { log::info!("{}", tv); } - if !tv.dry_run() { - let mut insert_point = 0; - for word in typeset_words.iter() { - let mut p = word.origin.clone(); - for glyph in word.gs.iter() { - /// TODO: need to redo the word wrap algorithm to not skip over whitespace entries so that insertion points work with multiple spaces - if let Some(ipoint) = tv.insertion { - if ipoint == insert_point { - let top = Point::new(p.x as _, p.y as _); - let bot = Point::new(p.x as _, (p.y + word.height) as _); - let line = Line::new(top, bot); - op::line(display.native_buffer(), - line, Some(clear_rect), tv.invert); - } - } - // log::info!("drawing {:?} at {:?}", glyph, p); - blitstr2::xor_glyph(display.native_buffer(), &p, *glyph, tv.invert); - p.x += glyph.wide as usize; // words after word-wrapping are guaranteed to be on the same line - insert_point += 1; - } - } - } - log::info!("(TV): returning cursor of {:?}", tv.cursor); + if !tv.dry_run() { + composition.render(display.native_buffer(), composition_top_left, tv.invert); + } + // type mismatch for now, replace this with a simple equals once we sort that out + tv.cursor.pt.x = composition.final_cursor().pt.x as i32; + tv.cursor.pt.y = composition.final_cursor().pt.y as i32; + tv.cursor.line_height = composition.final_cursor().line_height as i32; + + tv.bounds_computed = Some( + clear_rect + ); + log::info!("cursor ret {:?}, bounds ret {:?}", tv.cursor, tv.bounds_computed); // pack our data back into the buffer to return buffer.replace(tv).unwrap(); } @@ -401,11 +353,11 @@ fn xmain() -> ! { .expect("couldn't return ScreenSize request"); }), Some(Opcode::QueryGlyphProps) => msg_blocking_scalar_unpack!(msg, style, _, _, _, { - let glyph = GlyphStyle::from(style); + let glyph = blitstr2::GlyphStyle::from(style); xous::return_scalar2( msg.sender, glyph.into(), - blitstr::glyph_to_height_hint(glyph), + blitstr2::glyph_to_height_hint(glyph), ) .expect("could not return QueryGlyphProps request"); }), diff --git a/services/graphics-server/src/wordwrap.rs b/services/graphics-server/src/wordwrap.rs index bb0f7b420..6ed320c2e 100644 --- a/services/graphics-server/src/wordwrap.rs +++ b/services/graphics-server/src/wordwrap.rs @@ -1,3 +1,6 @@ +use crate::api::{Point, TextBounds}; + +use crate::backend::{FB_SIZE, FB_WIDTH_PIXELS, FB_LINES}; /// Wordwrap stratgey /// /// Strings are submitted to the Wordwrapper, and they are split into lines, and then into lexical words. @@ -24,7 +27,7 @@ /// If the overall string cannot fit within the absolute bounds defined by the `max` area and/or the `bounds`, /// the rendering is halted, and ellipses are inserted at the end. -use crate::blitstr2::*; +use crate::blitstr2::{self, *}; use crate::style_macros::*; /// A TypesetWord is a Word that has beet turned into sprites and placed at a specific location on the canvas, @@ -32,26 +35,40 @@ use crate::style_macros::*; /// a rasterizer for rendering. #[derive(Debug)] pub struct TypesetWord { + /// glyph data to directly render the word pub gs: Vec::, + /// top left origin point for rendering of the glyphs pub origin: Pt, + /// width of the word pub width: usize, + /// overall height for the word pub height: usize, + /// set if this `word` is not drawable, e.g. a newline placeholder. + /// *however* the Vec should still be checked for an insertion point, so that + /// successive newlines properly get their insertion point drawn + pub non_drawable: bool, + /// the position in the originating abstract string of the first character in the word + pub strpos: usize, } impl TypesetWord { - pub fn new(origin: Pt) -> Self { + pub fn new(origin: Pt, strpos: usize) -> Self { TypesetWord { gs: Vec::::new(), origin, width: 0, height: 0, + non_drawable: false, + strpos, } } - pub fn one_glyph(origin: Pt, gs: GlyphSprite) -> Self { + pub fn one_glyph(origin: Pt, gs: GlyphSprite, strpos: usize) -> Self { TypesetWord { gs: vec![gs], origin, width: gs.wide as usize, height: gs.high as usize, + non_drawable: false, + strpos, } } pub fn push(&mut self, gs: GlyphSprite) { @@ -59,6 +76,15 @@ impl TypesetWord { self.height = self.height.max(gs.high as usize); self.gs.push(gs); } + /// if the pop is invalid, we'll return an invalid character. Just...don't do that. k? + pub fn pop(&mut self) -> GlyphSprite { + let gs = self.gs.pop().unwrap_or(NULL_GLYPH_SPRITE); + self.width -= gs.wide as usize; + // we can't undo any height transformations, unfortunately, because we don't know what the previous state was + // but it's fairly minor if text is set funny on a line because text overflowed and had e.g. emoji buried amongst + // small font text... + gs + } /// offset has to take an explicit x/y set because Pt is defined as a usize, so we can't do negative offsets pub fn offset(&mut self, x: i16, y: i16) { let ox = self.origin.x as i16 + x; @@ -66,197 +92,461 @@ impl TypesetWord { self.origin.x = if ox > 0 { ox as usize } else { 0 }; self.origin.y = if oy > 0 { oy as usize } else { 0 }; } + /// sets the y coordinate to the given value. Returns the y coordinate of the next line based on just this word's height. + /// multi-word lines will want to track the return value and pick the maximum one as the overall line height + pub fn set_y(&mut self, y: usize) -> usize { + self.origin.y = y; + self.origin.y + self.height + } } -use crate::api::TextBounds; -//use graphics_server::TextBounds; -/// The TypesetWords in this case are defined by a bounding box into which they can -/// be directly rendered. -/// -/// All coordinates must be specified in terms of absolute screen coordinates. -/// The resulting `TypesetWord` vector is in absolute screen coordinates. -/// -/// `border` defines the maximum space available for rending the growable types. It -/// must always be able to contain any elements specified with the `bounds` requirement -/// specified in TextBounds. If the border is smaller than the bounds requirement, -/// then unpredictable results will occur. There is (currently) no error checking for this condition. -/// -/// Upon return, `border` is shrunk to the actual amount of space used by the renderer, if and only -/// if the `bounds` spec is not `BoundingBox`. -/// -/// An artifact of this rendering is that all whitespace is stripped and replaced with -/// a single "space" character. Multiple whitespace will have to be a special case -/// down the road, probably the domain of a "mono" glyph style, where no word wrapping -/// is done, and just clipping. -pub fn fit_str_to_clip( - s: &str, - border: &mut ClipRect, - bounds: &TextBounds, - base_style: &GlyphStyle, - cursor_state: &mut graphics_server::Cursor, - overflow: &mut bool -) -> Vec:: { - *overflow = false; - let space = style_glyph(' ', base_style); - let ellipsis = find_glyph_latin_small('…'); +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum OverflowStrategy { + /// overflow text is truncated and replaced with an ellipsis + Ellipsis, + /// stop rendering at overflow + Abort, + /// render exactly one line of text; reset the renderer for a new line at the top left of the max bb area + /// This will yield only whole words if the next word could fit in a single line; otherwise, it will split + /// a longer-than-one-line word unceremoniously into multiple lines + OneLineIterator, +} - // compute the renderable extent of the text region. This is the largest region allowed by the TextBounds specifier. - // we'll shrink this down after we're done rendering - let renderable = match *bounds { - TextBounds::BoundingBox(r) => { - ClipRect::new(r.tr().x as _, r.tr().y as _, r.bl().x as _, r.bl().y as _) +/// ComposedType is text that has been laid out and wrapped, along with metadata about the bounds +/// of the final composition. ComposedType coordinates are always in screen-space. +pub(crate) struct ComposedType { + words: Vec::, + bounding_box: ClipRect, + cursor: Cursor, +} +impl ComposedType { + pub fn new(words: Vec::, bounds: ClipRect, cursor: Cursor) -> Self { + ComposedType { + words, + bounding_box: bounds, + cursor, } - TextBounds::GrowableFromBr(br, width) => { - let min_x = if br.x - (width as i16) < 0 { 0usize } else { (br.x - width as i16) as usize }; - let min_y = border.min.y; - let max_x = br.x as usize; - let max_y = br.y as usize; - ClipRect::new(min_x as _, min_y as _, max_x as _, max_y as _) - } - TextBounds::GrowableFromTl(tl, width) => { - let min_x = tl.x as usize; - let min_y = tl.y; - let max_x = if (tl.x + width as i16) as usize > border.max.x { border.max.x } else { (tl.x + width as i16) as usize }; - let max_y = border.max.y; - ClipRect::new(min_x as _, min_y as _, max_x as _, max_y as _) - } - TextBounds::GrowableFromBl(bl, width) => { - let min_x = bl.x as usize; - let min_y = border.min.y as usize; - let max_x = if (bl.x + width as i16) as usize > border.max.x { border.max.x } else {(bl.x + width as i16) as usize}; - let max_y = bl.y as usize; - ClipRect::new(min_x as _, min_y as _, max_x as _, max_y as _) - } - }; - // now let's start rending from the "top left" of the renderable space. - let mut words = Vec::::new(); - let mut cursor = Cursor::new( - renderable.min.x + cursor_state.pt.x as usize, - renderable.min.y + cursor_state.pt.y as usize, - 0 + cursor_state.line_height as usize - ); // line_height tracks the tallest char so far - let lines = s.split('\n'); - for line in lines { - // for now, all white spaces are stripped and condensed into a single "space" character - for word in line.split_whitespace() { - // for each word, first compute the candidate's overall width and height - // the origin point is 0,0, because we will translate it to the correct spot later - let mut tsw = TypesetWord::new(Pt::new(0, 0)); - for ch in word.chars() { - let gs = style_glyph(ch, base_style); - tsw.push(gs); - } - // there are five cases from here: - // 1. The word fits in the remaining space on the line. - // 2. The word doesn't fit in the remaining space on the line, but it could fit on a new line - // 3. The word doesn't fit in the remaining space on the line, and there is no space for a new line (insert ellipses) - // 4. The word can't fit in the width of a single line and must be broken up into two parts, and there's a new line - // 5. The word can't fit in the width of a single line and there's no new lines avaliable to break it up (terminate with ellipses) - if tsw.width >= renderable.max.x // word is longer than our renderable width - { - // case 4 and 5, word is longer than a line. - // start by laying out characters until the line is "full", then, either wrap or ellipses depending upon new line state - for gs in tsw.gs { - if cursor.pt.x + (gs.wide as usize) < renderable.max.x { - let before = cursor.pt.clone(); - cursor.update_glyph(&gs); - words.push(TypesetWord::one_glyph(before, gs)); - } else if tsw.height + cursor.pt.y + cursor.line_height < renderable.max.y { // there's a new line available for more chars - // put the cursor on the next line - cursor.pt.x = renderable.min.x; - cursor.pt.y += cursor.line_height; - cursor.line_height = 0; - // now push the next char - let before = cursor.pt.clone(); - cursor.update_glyph(&gs); - words.push(TypesetWord::one_glyph(before, gs)); - } else { // no more lines available, push an ellipsis and bail - *overflow = true; - words.push(TypesetWord::one_glyph(cursor.pt.clone(), ellipsis.clone())); - cursor.update_glyph(&ellipsis); - break + } + pub fn bb_width(&self) -> usize { + self.bounding_box.max.x - self.bounding_box.min.x + } + pub fn bb_height(&self) -> usize { + self.bounding_box.max.y - self.bounding_box.min.y + } + pub fn render(&self, frbuf: &mut [u32; FB_SIZE], offset: Point, invert: bool) { + for word in self.words.iter() { + let mut point = word.origin.clone(); + for glyph in word.gs.iter() { + // the offset can actually be negative for good reasons, e.g., we're doing a scrollable buffer, + // but the blitstr2 was written assuming only positive offsets. Handle this here. + let maybe_x = offset.x + point.x as i16; + let maybe_y = offset.y + point.y as i16; + let mut renderable = true; + if maybe_x < 0 || maybe_x > FB_WIDTH_PIXELS as i16 { + renderable = false; + } + if maybe_y < 0 || maybe_y > FB_LINES as i16 as i16 { + renderable = false; + } + point.x += glyph.wide as usize; // keep scorekeeping on this, because it could eventually become renderable + if !renderable { + continue; + } else { + // note: I am pretty sure we're going to throw an error for stuff that goes off screen to the + // right and left with the current implemntation, but that clipping should happen within the + // xor_glyph engine and not chekced up here -- because what we want is a partial character to + // render, not have a margin of no-mans land a character width from the edge. + blitstr2::xor_glyph( + frbuf, + &Pt::new(maybe_x as usize, maybe_y as usize), + *glyph, + glyph.invert ^ invert + ); + if glyph.insert { + // draw the insertion point after the glyph's position + crate::op::line(frbuf, + crate::api::Line::new( + crate::api::Point::new(point.x as _, point.y as _), + crate::api::Point::new(point.x as _, point.y as i16 + glyph.high as i16) + ), + None, + invert + ); } } - if *overflow { // abort further rendering if we hit an overflow condition - break; - } - } else if tsw.width + cursor.pt.x < renderable.max.x { - // case 1, everything fits. Push the word into the rendering set, and add a space or newline to prep for the next word - tsw.offset(cursor.pt.x as _, cursor.pt.y as _); // offset the rendering location of the word to the current cursor location - cursor.update_word(&tsw); // move the cursor location based on the absolute width/height of the word - words.push(tsw); // store the word - // add a trailing space or new line - let before = cursor.pt.clone(); - if cursor.space_or_newline(&space, renderable.max.x, renderable.min.x) { - words.push(TypesetWord::one_glyph(before, space.clone())); - } - } else if (tsw.width + cursor.pt.x >= renderable.max.x) // it's longer than our current line - && (tsw.height + cursor.pt.y + cursor.line_height < renderable.max.y) // there's a new line available to hold the whole word - && (tsw.width < renderable.max.x) // the whole word could fit on a new line - { // case 2, put the word on a new line - // put the cursor on a new line - cursor.pt.x = renderable.min.x; - cursor.pt.y += cursor.line_height; - cursor.line_height = 0; - // now push the word - tsw.offset(cursor.pt.x as _, cursor.pt.y as _); - cursor.update_word(&tsw); - words.push(tsw); - // add a trailing space or new line - let before = cursor.pt.clone(); - if cursor.space_or_newline(&space, renderable.max.x, renderable.min.x) { - words.push(TypesetWord::one_glyph(before, space.clone())); - } - } else if (tsw.width + cursor.pt.x >= renderable.max.x) // it's longer than our current line - && (tsw.height + cursor.pt.y + cursor.line_height >= renderable.max.y) // there's no lines available - { // case 3, no more space for words - *overflow = true; - words.push(TypesetWord::one_glyph(cursor.pt.clone(), ellipsis.clone())); - cursor.update_glyph(&ellipsis); - break - } else { - // unhandled case, log the parameters so we can handle it - log::error!("Unhandled case in word wrapper: new word width {} height {}, cursor {:?}, renderable {:?}", tsw.width, tsw.height, cursor, renderable); } } - // don't render any more lines if we hit an overflow condition - if *overflow { - break; - } } - // now update the computed bounds, based on the final value of the cursor - let actual_width = cursor.pt.x - renderable.min.x; - let actual_height = (cursor.pt.y + cursor.line_height) - renderable.min.y; - match &bounds { - TextBounds::BoundingBox(_) => { - // do nothing, this is a fixed box and we just fill it in from the top left. - } - TextBounds::GrowableFromBr(br, width) => { - border.min.x = br.x as usize - actual_width; - border.min.y = br.y as usize - actual_height; - border.max.x = br.x as usize; - border.max.y = br.y as usize; - } - TextBounds::GrowableFromTl(tl, width) => { - border.min.x = tl.x as usize; - border.min.y = tl.y as usize; - border.max.x = tl.x as usize + actual_width; - border.max.y = tl.y as usize + actual_height; - } - TextBounds::GrowableFromBl(bl, width) => { - border.min.x = bl.x as usize; - border.min.y = bl.y as usize - actual_height; - border.max.x = bl.x as usize + actual_width; - border.max.y = bl.y as usize; - } + pub fn final_cursor(&self) -> Cursor { + self.cursor } - // update the cursor based on the final state - cursor_state.pt.x = (cursor.pt.x - renderable.min.x) as i32; - cursor_state.pt.y = (cursor.pt.y - renderable.min.y) as i32; - - words } +/// Typesetter takes a string and attempts to lay it out within a region defined by +/// a single point known as the "Extent". This is the maximum extent allowable for +/// the type. +/// +/// The string may overflow the provided Extent. The strategy for handling the overflow +/// is specified with the `OverflowStrategy`, specified at the time of the typesetting call. +/// +/// The Typesetter can run in essentially two modes: Line-by-line, or Fill-to-overflow. The +/// terminus of Fill-to-overflow can be either ellipses at the end, or a simple truncation. +/// +/// When the Typesetter ends, the Typesetter will leave off in a way that Typesetting can +/// resume according to the specified mode. For Line-by-Line, it will resume Typesetting at +/// the top left of the bounding box. For other modes, it will resume at the point of overflow; +/// one must "rewind" the Typesetter, before calling it again. +/// +/// The Typesetter returns a `ComposedType` object which is a `Vec` of `TypesetWord` along +/// with a helper field that summarizes the actual bounding box of the text, along with the +/// final cursor position. +/// +/// An insertion point cursor will be injected into the TypesetWord stream at the character offset in +/// the input `string` if it is specified as `Some(usize)`. +pub(crate) struct Typesetter { + charpos: usize, + cursor: Cursor, // indicates the current insertion point for a candidate. it is not updated as the candidates are formed. + candidate: TypesetWord, + bb: ClipRect, + space: GlyphSprite, + ellipsis: GlyphSprite, + insertion_point: Option, + s: String, + base_style: GlyphStyle, + overflow: bool, + max_width: usize, +} +impl Typesetter { + pub fn setup( + s: &str, + extent: &Pt, + base_style: &GlyphStyle, + insertion_point: Option, + ) -> Self { + let bb = ClipRect::new(0, 0, extent.x, extent.y); + // now initialize the Typesetter to the "top left" of the bb space. + Typesetter { + charpos: 0, + cursor: Cursor::new(0, 0, 0), + candidate: TypesetWord::new(Pt::new(0, 0), 0), // first word candidate starts at the top left corner + bb, + space: style_glyph(' ', base_style), + ellipsis: find_glyph_latin_small('…'), + base_style: base_style.clone(), + s: String::from(s), + insertion_point, + overflow: false, + max_width: 0, + } + } + pub fn last_line_height(&self) -> usize { + self.cursor.line_height + } + /// Wrap the words in the string until the space overflows, leaving ellipsis at the end. + /// Any prior result in self.words is overwritten. + /// + /// For overflow strategies that are not OneLineIterator, + /// the caller must reset the cursor to the desired resume position, otherwise it will pick + /// up again at the overflow position. + /// + /// The final Vec:: is snapped to the top left of the Renderable region. This + /// needs to be transformed into the final screen coordinate space before blitting. + pub fn typeset(&mut self, strat: OverflowStrategy) -> ComposedType { + // a composition only lasts as long as the lifetime of this call, and is passed back to the caller + // at the end. Thus, we create it here and pass it out in the end. It's a bad idea to make it + // part of the core `struct` because then you'd have to wrap it in an Option to deal with the object + // going out of scope at the end of the call. + let mut composition = Vec::::new(); + + if self.bb.max.x - self.bb.min.y < glyph_to_height_hint(GlyphStyle::Regular) { + log::error!("Words cannot be typset because the width of the typset region is too narrow."); + return ComposedType::new(composition, + ClipRect::new(self.bb.min.x, self.bb.min.y, self.bb.min.x, self.bb.min.y), + self.cursor + ); + } + if self.bb.max.y - self.bb.min.y < glyph_to_height_hint(GlyphStyle::Regular) { + log::error!("Words cannot be typset because the height of the typset region is too low."); + return ComposedType::new(composition, + ClipRect::new(self.bb.min.x, self.bb.min.y, self.bb.min.x, self.bb.min.y), + self.cursor + ); + } + // algorithm: + // - If not a whitespace or newline: + // 1. append a character to the current word (candidate) + // 2. Test if the new character would overflow. If so, move the word to a new line, or exit with overflow. + // Thus upon entry to this loop, the `candidate` is always guaranteed to be a fitting word at its current point + // of rendering. + // - If a whitespace: + // 1. put the `candidate` into the `words` field + // 2. Test to see if we can fit a whitespace at the end of this line. If we can't, insert a newline, or overflow. + // - If a newline: + // 1. put the `candidate` into the `words` field + // 2. Test to see if we can add a newline. If we can't, overflow. + let working_string = self.s.to_string(); // allocate a full copy to avoid interior mutability issues in the loop below. :-/ ugh. + // there's probably a more space-efficient way to deal with this using interior mutability but fuck it, I need to get this code working. + for ch in working_string.chars().skip(self.charpos) { // .skip() allows us to resume typesetting where we last left off + if ch == '\n' { + // handle the explicit newline case + match strat { + OverflowStrategy::OneLineIterator => { + if self.candidate.gs.len() > 0 { // this test is here in case we have multiple spaces or newlines in a row + self.commit_candidate_word(&mut composition); + } + self.oneline_epilogue(); + break; + } + _ => { + if self.candidate.gs.len() > 0 { // stash the word we just made; if this is 0, we're encounting multiple \n\n in a row + self.commit_candidate_word(&mut composition); + } + if self.is_newline_available() { + self.move_candidate_to_newline(); + // hard newlines are marked by a non-drawable space at the beginning of a line + // this also allows us to place a cursor to "delete" a stray newline since it has the size and shape of a space + if !self.try_append_space(&mut composition) { + log::error!("Internal error: cursor was set to a newline, yet no space for new characters??"); + } + } else { + self.overflow_typesetting(&mut composition, strat); + break; + } + } + } + } else if ch.is_whitespace() { + if self.candidate.gs.len() > 0 { // this test is here in case we have multiple spaces or newlines in a row + self.commit_candidate_word(&mut composition); + } + if !self.try_append_space(&mut composition) { + match strat { + OverflowStrategy::OneLineIterator => { + self.oneline_epilogue(); + break; + } + _ => { + if self.is_newline_available() { + self.move_candidate_to_newline(); + // the call below automatically handles the case of non-drawable spaces at the beginning of newlines + if !self.try_append_space(&mut composition) { + log::error!("Internal error: cursor was set to a newline, yet no space for new characters??"); + } + } else { + self.overflow_typesetting(&mut composition, strat); + break; + } + } + } + } + } else { + // at this point, we get a glyph. This next glyph can cause one of the following situations to occur: + // 1. The evolving word fits. + // 2. The evolving word is longer than a single line, and there are more lines available. + // 3. The evolving word is longer than a single line, and there are no more lines available. + // 4. The evolving word fits a line but doesn't fit this line, and there is space on a new line for it. + // 5. The evolving word fits a line but doesn't fit this line, and there is no more space at all. + let mut gs = style_glyph(ch, &self.base_style); + if self.is_insert_point() { + gs.insert = true; + } + self.candidate.push(gs.clone()); + if self.is_word_longer_than_line() { // cases 2 & 3 + match strat { + OverflowStrategy::OneLineIterator => { // case 2 is not an option with the OneLine strategy + // this exit is weird. We need to commit the partially typeset word, and reset the rendering state. + // remove the character that caused the overflow. + let _gs_pop = self.candidate.pop(); + self.commit_candidate_word(&mut composition); + // we have to rewind the character position, because the commit_candidate_word side effects that, + // and doesn't know about the removed character. This is sort of ugly. + self.charpos -= 1; + // now reset us for the next call + self.oneline_epilogue(); + // typesetting will resume at the broken-off word, because the charpos was left there. + break; + } + _ => { + // self.char_pos + // v|v gs_pop + // 012345|678 + // abcdef|hij + if self.is_newline_available() { // case 2 + // commit the fragment of the word to the current line + let gs_pop = self.candidate.pop(); + self.commit_candidate_word(&mut composition); + // set the cursor to the next line + self.move_candidate_to_newline(); + // now set the overflowed character on the new line so our state is synched up + self.candidate.push(gs_pop); + } else { // case 3 + // similar to the one-line iterator exit, but with a call to overflow at the end. + let _gs_pop = self.candidate.pop(); + self.commit_candidate_word(&mut composition); + self.charpos -= 1; + self.overflow_typesetting(&mut composition, strat); + break; + } + } + } + } else if !self.does_word_fit_on_line() { // this is case 4 & 5 -- candidate is shorter than a line, but doesn't fit on this line + match strat { + OverflowStrategy::OneLineIterator => { // case 4 is not an option + // now exit + self.reject_candidate_word(); + self.oneline_epilogue(); + break; + } + _ => { + if self.is_newline_available() { // case 4 + self.move_candidate_to_newline(); + self.commit_candidate_glyph(&gs); + } else { // case 5 + self.reject_candidate_word(); + self.overflow_typesetting(&mut composition, strat); + break; + } + } + } + } else { // case 1 -- everything fits + self.commit_candidate_glyph(&gs); + } + } + } + let ret = ComposedType::new(composition, + ClipRect::new( + self.bb.min.x, self.bb.min.y, + self.max_width, self.cursor.pt.y + self.cursor.line_height, + ), + self.cursor + ); + // cleanup any state based on the overflow strategy + match strat { + OverflowStrategy::OneLineIterator => { + self.max_width = 0; // it's a fresh line every time + assert!(self.cursor.pt.x == self.bb.min.x, "internal logic did not clean up the cursor state for the one line iterator") + } + _ => { + // other states "start where they left off" + } + } + ret + } + fn is_newline_available(&self) -> bool { + self.candidate.height + self.cursor.pt.y + self.cursor.line_height < self.bb.max.y + } + fn does_word_fit_on_line(&self) -> bool { + self.candidate.width + self.cursor.pt.x < self.bb.max.x + } + fn is_word_longer_than_line(&self) -> bool { + self.candidate.width >= (self.bb.max.x - self.bb.min.x) + } + fn is_insert_point(&self) -> bool { + if let Some(ip) = self.insertion_point { + if ip == self.charpos { + true + } else { + false + } + } else { + false + } + } + fn commit_candidate_word(&mut self, composition: &mut Vec::) { + if !self.candidate.non_drawable { // this is mainly for "non-drawable spaces" at the beginning of a line + self.max_width = self.max_width.max(self.candidate.width + self.candidate.origin.x); + self.cursor.pt.x += self.candidate.width; + self.cursor.line_height = self.cursor.line_height.max(self.candidate.height); + } + self.charpos += 1; + composition.push( + std::mem::replace( + &mut self.candidate, + // prepare a fresh "candidate" starting at the next character position + TypesetWord::new(self.cursor.pt, self.charpos) + ) + ); + } + fn commit_candidate_glyph(&mut self, _gs: &GlyphSprite) { + self.charpos += 1; + } + fn reject_candidate_word(&mut self) { + // back the rendering up to the starting point of the current word under consideration + self.charpos = self.candidate.strpos; + self.cursor.pt = self.candidate.origin; + self.cursor.line_height = 0; + // discard the current word, since we're going to start over again on the next call + self.candidate = TypesetWord::new(self.cursor.pt, self.charpos); + } + fn move_candidate_to_newline(&mut self) { + // advance the rendering line, without inserting a newline placeholder + self.cursor.pt.y += self.cursor.line_height; + self.cursor.pt.x = self.bb.min.x; + self.cursor.line_height = self.candidate.height; + // now set the current candidate word's origin to the beginning of this new line + self.candidate.origin = self.cursor.pt; + } + + fn overflow_typesetting(&mut self, composition: &mut Vec::, strat: OverflowStrategy) { + self.overflow = true; + match strat { + OverflowStrategy::Ellipsis => { + let mut ov_word = TypesetWord::one_glyph(self.cursor.pt.clone(), self.ellipsis.clone(), self.charpos); + if self.is_insert_point() { + ov_word.gs[0].insert = true; + } + composition.push(ov_word); + // the ellipsis is meta, so when we resume rendering it won't exist. thus don't update the cursor over it. + // self.cursor.update_glyph(&self.ellipsis); + } + _ => { + () // do nothing + } + } + } + + /// tries to add a space after the current cursor point. If this would overflow the bb bounds, + /// it returns false. + /// The rule is, we must always enter this with a "brand new" TypesetWord entry with the charpos + /// set to our space point, because the caller will have already stashed the previously formed word + fn try_append_space(&mut self, composition: &mut Vec::) -> bool { + assert!(self.candidate.gs.len() == 0, "self.candidate was not set to a new state prior to this call"); + if (self.cursor.pt.x + self.space.wide as usize) < self.bb.max.x { + // our candidate word is "just as space" + self.candidate.push(self.space.clone()); + // if we're at the beginning of a line, mark the candidate word (that just contains a space) as non-drawable + if self.cursor.pt.x == self.bb.min.x { + self.candidate.non_drawable = true; + } + // now commit it + self.commit_candidate_word(composition); + true + } else { + false + } + } + /// resets the cursor state to the top left of the box for the next line to render. + fn oneline_epilogue(&mut self) { + self.cursor.pt.y = 0; // this should be redundant, as we never have more than one line in this mode + self.cursor.pt.x = self.bb.min.x; + if self.cursor.line_height == 0 { // in case we have successive newlines, just default to the "regular" height + self.cursor.line_height = glyph_to_height_hint(GlyphStyle::Regular); + } + } +} +/* +/// This iterator will go through the string and return successive lines that fit +/// within the width of the bb region. Each time the line is typeset to +/// have its origin snapped to the top left of the bb region. This iterator +/// is useful for doing a multi-line text buffer where lines that don't fit within +/// the bb region "pop off the top"; the lines can be kept in a vector, and +/// then directly rendered later on, line-by-line, as needed. +impl Iterator for Typesetter { + type Item = Vec::; + fn next(&mut self) -> Option { + None + } +} +*/ /// Find glyph for char using latin regular, emoji, ja, zh, and kr font data pub fn style_glyph(ch: char, base_style: &GlyphStyle) -> GlyphSprite { diff --git a/services/modals/Cargo.toml b/services/modals/Cargo.toml index e2722a8b9..bc3ec35f4 100644 --- a/services/modals/Cargo.toml +++ b/services/modals/Cargo.toml @@ -24,4 +24,4 @@ utralib = { path = "../../utralib"} [features] ux_tests = [] -default = [] +default = ["ux_tests"] diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index da1f5e871..19e4ea4fe 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -462,6 +462,7 @@ fn xmain() -> ! { } }); // try to mount the PDDB automatically before starting the server + #[cfg(any(windows, unix))] // skip this step if running in hosted mode, for now... if pddb_os.rootkeys_initialized() { tt.sleep_ms(1000).unwrap(); // wait 1 second after boot before attempting to mount, to let the boot screen finish redrawing (cometic issue). if ensure_password(&modals, &mut pddb_os) { diff --git a/services/status/src/main.rs b/services/status/src/main.rs index ed1805b6f..87d89b959 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -164,7 +164,7 @@ fn xmain() -> ! { )), ); uptime_tv.untrusted = false; - uptime_tv.style = blitstr::GlyphStyle::Small; + uptime_tv.style = blitstr::GlyphStyle::Regular; uptime_tv.draw_border = false; uptime_tv.margin = Point::new(3, 0); write!(uptime_tv, "Booting up...").expect("|status: couldn't init uptime text"); @@ -181,7 +181,7 @@ fn xmain() -> ! { Point::new(screensize.x, screensize.y / 2 - 1), )), ); - battstats_tv.style = blitstr::GlyphStyle::Small; + battstats_tv.style = blitstr::GlyphStyle::Regular; battstats_tv.draw_border = false; battstats_tv.margin = Point::new(0, 0); gam.post_textview(&mut battstats_tv) @@ -237,7 +237,7 @@ fn xmain() -> ! { Point::new(screensize.x, screensize.y - 1), )), ); - security_tv.style = blitstr::GlyphStyle::Small; + security_tv.style = blitstr::GlyphStyle::Regular; security_tv.draw_border = false; security_tv.margin = Point::new(0, 0); security_tv.token = gam.claim_token("status").expect("couldn't request token"); // this is a shared magic word to identify this process