mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-03 22:40:27 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a526c03c12 | ||
|
|
18f4fe32cb | ||
|
|
7ed38e7cb3 |
@@ -155,6 +155,11 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-21: Page text on the shared page view is sharp again. After the port, pages were rasterised at the view's own scale and rounded up to whole pixels, which left a picture a pixel or two larger than its place on screen (2017 × 2852 for 2016 × 2851); the shared painter fits a picture into its place, so it was squeezed by a twentieth of a percent and the text slid off the pixel grid and back down the page: a reporter's screenshot showed baselines spread over three pixel rows. Pictures are now made exactly as many pixels each way as the place the view last rested at, which the painter draws one pixel for one. A headless test through the real page view and picture store holds this at three zooms and two screen densities. Not yet seen in the running app. Readiness estimates unchanged.
|
||||
- 2026-11-20: The sharper page text, subpixel (LCD) text and the Screen text smoothing option are ported onto the shared page view and Options that the UI port (#7101) brought. Two things changed on the way. The page view asks for page pictures rounded up to a multiple of 16 pixels and scales them into place, which resamples every glyph (A4 at 100 % on a 2x screen: 2256 pixels for 2245), so pages are now rasterised at the view's own scale wherever it accounts for the side asked for, and subpixel text is drawn only on such pictures. And the app no longer reads the system's text settings itself: system access moved to craft-libs' `platform::appearance`, which has none, so pages are drawn each platform's fixed way plus the user's own Screen text smoothing choice until craft-libs reports them (the 2026-11-19 entry on following the system no longer holds). Two shared-API gaps are recorded in `docs/ui-parity.md`: the text settings reader, and drawing a screen-scale page picture at its own pixel size. Run on macOS only; not seen in the running app since the port. Readiness estimates unchanged.
|
||||
- 2026-11-19: Page text can be drawn with subpixel (LCD) antialiasing: File › Options › General › Screen text smoothing offers Use system setting, Grayscale and Subpixel (LCD); `view.textSmoothing` reaches the same setting headlessly. A page is rasterised three times with only its text a third of a pixel apart and each colour channel is taken from the pass that matches its stripe, so drawing order, coloured text, dark pages and rotated text need no special cases and nothing but text gets coloured edges. Once the system settings are read (nothing reads them yet), "Use system setting" will turn it on where the system asks for it (ClearType, or `rgba` antialiasing on a Linux desktop) on screens below 2x; macOS never asks, so there it is the user's choice. Exports are unchanged. Run on macOS only, on headless rasters: not yet seen on a 1x LCD, on Windows or on Linux, and not timed. Readiness estimates unchanged.
|
||||
- 2026-11-19: Page drawing can take the system's text settings (darkening strength, hinting, subpixel order), but nothing reads them from the system yet, so pages are drawn each platform's fixed way and "Use system setting" is greyscale. Readiness estimates unchanged.
|
||||
- 2026-11-19: Page text on macOS and Windows is no longer soft. Baselines sit on whole device pixels, so the feet of the letters fill one pixel row instead of greying two; and the macOS font smoothing we imitate thickens letters sideways only, by widening each outline and filling it once, where a stroke all round added a third of a pixel of grey above and below every letter. Found by comparing 144 dpi screenshots of the same paragraph in WordCraft, Preview and OpenOffice: none of the three used subpixel antialiasing; WordCraft alone had its serifs spread over two rows. Linux and BSD text was already hinted onto the grid; exports are unchanged. Readiness estimates unchanged.
|
||||
- 2026-12-01: Hindi interface language (`hi`): File › Options › Interface language offers हिन्दी, and `hi`, `hi-IN` and `hi_IN.UTF-8` system locales pick it. The catalog is craft-i18n's `locales/hi/wordcraft.tsv` (`craft-i18n.rev` at 217f413); interface text is drawn by the embedded Noto Sans Devanagari face. No Hindi proofing, so the Hindi interface doesn't set the language of new documents. Readiness estimates unchanged.
|
||||
- 2026-11-28: Layout indexes numbering definitions for each list and STYLEREF walk. List labels still follow the document's literal labels, start overrides and nested restart rules (#3615).
|
||||
|
||||
|
||||
@@ -52,6 +52,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
Ok(json!({"paperColor": color}))
|
||||
}).params(r#"{"value": "document" | "green" | "cream" | "gray"}"#).pure(),
|
||||
// How the edges of page text are smoothed on screen. Screen only; never in the document.
|
||||
CommandSpec::new("view.textSmoothing", "Screen Text Smoothing", "View › Display", |s, v| {
|
||||
let smoothing: TextSmoothing = serde_json::from_value(v.get("value").cloned().unwrap_or(Value::Null))
|
||||
.map_err(|_| CmdError::Params("screen text smoothing must be system, grayscale, or subpixel".into()))?;
|
||||
s.prefs.text_smoothing = smoothing;
|
||||
Ok(json!({"textSmoothing": smoothing}))
|
||||
})
|
||||
.params(r#"{"value": "system" | "grayscale" | "subpixel"}"#)
|
||||
.pure(),
|
||||
// Print Layout: hide the white space (margins, headers, footers) between pages. Screen only.
|
||||
CommandSpec::new("view.hideWhiteSpace", "Hide White Space", "View › Show", |s, v| toggle(s, v, |x| &mut x.hide_white_space))
|
||||
.params(r#"{"value"?: bool}"#)
|
||||
@@ -349,6 +358,35 @@ fn read_line_spacing(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"spacing": spacing}))
|
||||
}
|
||||
|
||||
/// How the edges of page text are smoothed on screen, saved with user preferences, never in the
|
||||
/// document. Exports, prints and PDFs are not affected.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TextSmoothing {
|
||||
/// As the system is set: subpixel where it asks for it (ClearType on Windows, `rgba`
|
||||
/// antialiasing on a Linux desktop) and the screen is not a high-density one, else
|
||||
/// greyscale. macOS never asks for it.
|
||||
#[default]
|
||||
System,
|
||||
/// Greyscale antialiasing: grey edges, no colour.
|
||||
Grayscale,
|
||||
/// Subpixel (LCD) antialiasing, whatever the system says: edges three times as fine
|
||||
/// sideways, with faint colour in them. In the system's stripe order, RGB when it gives none.
|
||||
Subpixel,
|
||||
}
|
||||
|
||||
impl TextSmoothing {
|
||||
pub const ALL: [Self; 3] = [Self::System, Self::Grayscale, Self::Subpixel];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "Use system setting",
|
||||
Self::Grayscale => "Grayscale",
|
||||
Self::Subpixel => "Subpixel (LCD)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Screen-only paper presets, saved with user preferences, never in the document.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -10,6 +10,10 @@ pub struct Prefs {
|
||||
/// On-screen paper for pages without a document background; excluded from saved documents.
|
||||
#[serde(deserialize_with = "lenient_paper_color")]
|
||||
pub paper_color: crate::cmd::view::PaperColor,
|
||||
/// How the edges of page text are smoothed on screen (`view.textSmoothing`); excluded from
|
||||
/// saved documents.
|
||||
#[serde(deserialize_with = "lenient_text_smoothing")]
|
||||
pub text_smoothing: crate::cmd::view::TextSmoothing,
|
||||
/// Track Changes Options: what markup shows and how revisions are drawn (per user, as in
|
||||
/// Word).
|
||||
pub markup: wordcraft_layout::display::MarkupOptions,
|
||||
@@ -72,6 +76,7 @@ impl Default for Prefs {
|
||||
fn default() -> Self {
|
||||
Prefs {
|
||||
paper_color: Default::default(),
|
||||
text_smoothing: Default::default(),
|
||||
count_notes: true,
|
||||
markup: Default::default(),
|
||||
print_markup: false,
|
||||
@@ -119,6 +124,12 @@ fn lenient_paper_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::
|
||||
Ok(serde_json::from_value(value).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Ignore an invalid saved text smoothing without discarding other preferences.
|
||||
fn lenient_text_smoothing<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::TextSmoothing, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(serde_json::from_value(value).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Ignore an invalid saved Page Color without discarding other preferences.
|
||||
fn lenient_read_page_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::ReadPageColor, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
|
||||
@@ -15279,6 +15279,37 @@ fn export_png_rejects_a_page_number_that_does_not_fit() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_text_smoothing_is_a_persistent_preference_not_document_formatting() {
|
||||
use crate::cmd::view::TextSmoothing;
|
||||
let mut s = s();
|
||||
run(&mut s, "text.insert", json!({"text": "Screen text test", "raw": true}));
|
||||
let before = serde_json::to_value(&s.doc).unwrap();
|
||||
let docx_before = wordcraft_docx::write(&s.doc).unwrap();
|
||||
s.dirty = false;
|
||||
assert_eq!(s.prefs.text_smoothing, TextSmoothing::System, "follows the system until the user chooses");
|
||||
for (value, expected) in [("subpixel", TextSmoothing::Subpixel), ("grayscale", TextSmoothing::Grayscale), ("system", TextSmoothing::System)] {
|
||||
let r = run(&mut s, "view.textSmoothing", json!({"value": value}));
|
||||
assert_eq!(r["textSmoothing"], value);
|
||||
assert_eq!(s.prefs.text_smoothing, expected);
|
||||
assert_eq!(serde_json::to_value(&s.doc).unwrap(), before);
|
||||
assert!(!s.dirty);
|
||||
assert_eq!(wordcraft_docx::write(&s.doc).unwrap(), docx_before);
|
||||
let restored: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
|
||||
assert_eq!(restored.text_smoothing, expected);
|
||||
}
|
||||
run(&mut s, "view.textSmoothing", json!({"value": "subpixel"}));
|
||||
for v in [json!({}), json!({"value": "lcd"}), json!({"value": 42}), json!({"value": null}), json!({"value": ["subpixel"]})] {
|
||||
assert!(s.run("view.textSmoothing", &v).is_err(), "{v}");
|
||||
assert_eq!(s.prefs.text_smoothing, TextSmoothing::Subpixel, "a refused value changes nothing");
|
||||
}
|
||||
let legacy: crate::Prefs = serde_json::from_value(json!({})).unwrap();
|
||||
assert_eq!(legacy.text_smoothing, TextSmoothing::System);
|
||||
let future: crate::Prefs = serde_json::from_value(json!({"textSmoothing":"future", "countNotes":false})).unwrap();
|
||||
assert_eq!(future.text_smoothing, TextSmoothing::System);
|
||||
assert!(!future.count_notes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_paper_color_is_a_persistent_preference_not_document_formatting() {
|
||||
use crate::cmd::view::PaperColor;
|
||||
|
||||
+260
-54
@@ -159,13 +159,29 @@ pub struct RenderOptions {
|
||||
/// Colour for formatting marks.
|
||||
pub mark_color: Rgb,
|
||||
/// Thicken glyphs slightly the way macOS draws text on screen ("font smoothing"), so pages
|
||||
/// look like they do in other Mac apps. For on-screen rasters only: exports stay exact.
|
||||
pub text_darkening: bool,
|
||||
/// look like they do in other Mac apps: 0 is none, 1 the system's default strength
|
||||
/// ([`stem_darkening`]), and other values scale it, up to twice (the system's own setting
|
||||
/// has a lighter and a stronger step). A value that isn't a number is none. For on-screen
|
||||
/// rasters only: exports stay exact.
|
||||
pub text_darkening: f32,
|
||||
/// Put every glyph's baseline on a whole device pixel, for text that is neither rotated nor
|
||||
/// mirrored. A baseline between two pixel rows spreads the feet of the letters (serifs, the
|
||||
/// bottoms of stems) over both rows as two grey rows instead of one solid one, which reads as
|
||||
/// blur. A glyph moves by half a pixel at most and never sideways, so lines break as without
|
||||
/// it. Hinted text already sits like this. For on-screen rasters only: exports stay exact.
|
||||
pub baseline_snap: bool,
|
||||
/// Hint text for the screen the way FreeType's `hintslight` does on Linux desktops: glyph
|
||||
/// baselines sit on whole pixels and their horizontal edges (x-height, cap height) are moved
|
||||
/// onto the pixel grid, so text looks as crisp as in other apps there. Nothing moves
|
||||
/// sideways, so lines break as without it. For on-screen rasters only: exports stay exact.
|
||||
pub hinting: bool,
|
||||
/// Subpixel (LCD) antialiasing for text, for a screen whose colour stripes run in this order
|
||||
/// (see [`LcdOrder`]); `None` is greyscale antialiasing. Text gets three times the detail
|
||||
/// sideways, where slanted and round strokes need it most, at the price of faint colour at
|
||||
/// its edges, and the page is rasterised three times. Everything but text is drawn as
|
||||
/// without it. For on-screen rasters only, and only where the raster's pixels are the
|
||||
/// screen's own: exports stay exact.
|
||||
pub lcd: Option<LcdOrder>,
|
||||
/// Dark page (View › Switch Modes): every colour but pictures has its lightness inverted, so
|
||||
/// white paper turns black and black text white while hues stay the same. Screen only.
|
||||
pub dark: bool,
|
||||
@@ -176,6 +192,20 @@ pub struct RenderOptions {
|
||||
pub read_paper: Option<Rgb>,
|
||||
}
|
||||
|
||||
/// The order of a screen's red, green and blue stripes, left to right, within each pixel.
|
||||
///
|
||||
/// With [`RenderOptions::lcd`] set, each colour channel of a pixel takes the text's coverage
|
||||
/// around its own stripe, a third of a pixel to one side of the pixel's middle or the other,
|
||||
/// instead of all three taking the coverage of the whole pixel. A pixel's stripes are a pixel
|
||||
/// wide in all, so each channel still averages over one pixel's width: this is the result of
|
||||
/// rasterising text at three times the width and averaging three neighbours (the box filter
|
||||
/// FreeType calls its light LCD filter), with no sharper filter and no fringe reduction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum LcdOrder {
|
||||
Rgb,
|
||||
Bgr,
|
||||
}
|
||||
|
||||
/// Default grey for a dark page's paper.
|
||||
pub const DARK_PAPER: u8 = 0x33;
|
||||
|
||||
@@ -267,8 +297,10 @@ impl Default for RenderOptions {
|
||||
display: DisplayOptions::default(),
|
||||
paper: Rgb::WHITE,
|
||||
mark_color: Rgb(0x2B, 0x57, 0x9A),
|
||||
text_darkening: false,
|
||||
text_darkening: 0.0,
|
||||
baseline_snap: false,
|
||||
hinting: false,
|
||||
lcd: None,
|
||||
dark: false,
|
||||
dark_paper: DARK_PAPER,
|
||||
read_paper: None,
|
||||
@@ -296,6 +328,52 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
|
||||
// Over the cap the whole picture is drawn smaller, not cropped.
|
||||
let view = if (cw, ch) == (w, h) { view } else { Affine::scale_non_uniform(cw as f64 / w as f64, ch as f64 / h as f64) * view };
|
||||
let (w16, h16) = (cw as u16, ch as u16);
|
||||
let drew_text = std::cell::Cell::new(false);
|
||||
let mut pixels = raster_page(doc, page, (w16, h16), view, opts, Pass { shift: 0.0, drew_text: &drew_text });
|
||||
// Subpixel text: the page twice more, its text a third of a pixel to each side, for the
|
||||
// channels whose stripes sit there. A page without text is the same all three times.
|
||||
if let Some(order) = opts.lcd
|
||||
&& drew_text.get()
|
||||
{
|
||||
let side = |shift: f64| raster_page(doc, page, (w16, h16), view, opts, Pass { shift, drew_text: &drew_text });
|
||||
let (text_right, text_left) = (side(LCD_SHIFT), side(-LCD_SHIFT));
|
||||
let (red, blue) = match order {
|
||||
LcdOrder::Rgb => (&text_right, &text_left),
|
||||
LcdOrder::Bgr => (&text_left, &text_right),
|
||||
};
|
||||
take_lcd_channels(&mut pixels, red, blue);
|
||||
}
|
||||
Rendered { width: w16 as u32, height: h16 as u32, pixels }
|
||||
}
|
||||
|
||||
/// How far, in device pixels, the middle of a pixel's first or last colour stripe is from the
|
||||
/// middle of the pixel.
|
||||
const LCD_SHIFT: f64 = 1.0 / 3.0;
|
||||
|
||||
/// One rasterisation of a page among the one or three that make its raster.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Pass<'a> {
|
||||
/// How far to the right text is drawn from its place, in device pixels (see
|
||||
/// [`RenderOptions::lcd`]). Nothing else moves.
|
||||
shift: f64,
|
||||
/// Set once the pass has drawn text that `shift` moves.
|
||||
drew_text: &'a std::cell::Cell<bool>,
|
||||
}
|
||||
|
||||
/// The red of `pixels` from `red` and its blue from `blue`, two rasters of the same size
|
||||
/// (premultiplied RGBA8). Text shifted right puts under each pixel's middle what lay a third of a
|
||||
/// pixel to its left, where an RGB screen's red stripe is, and so on. The alpha stays, and
|
||||
/// no channel is left above it.
|
||||
fn take_lcd_channels(pixels: &mut [u8], red: &[u8], blue: &[u8]) {
|
||||
for ((px, r), b) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(red.as_chunks::<4>().0).zip(blue.as_chunks::<4>().0) {
|
||||
px[0] = r[0].min(px[3]);
|
||||
px[2] = b[2].min(px[3]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rasterise a page into `size` pixels (premultiplied RGBA8) with `view` (page points → pixels).
|
||||
fn raster_page(doc: &Document, page: &Page, size: (u16, u16), view: Affine, opts: &RenderOptions, pass: Pass) -> Vec<u8> {
|
||||
let (w16, h16) = size;
|
||||
let mut ctx = context_pool::CONTEXTS.take(w16, h16);
|
||||
ctx.set_transform(Affine::IDENTITY);
|
||||
ctx.set_paint(color(opts.paper_of(doc), 1.0));
|
||||
@@ -314,7 +392,7 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
|
||||
ctx.push_opacity_layer(alpha);
|
||||
}
|
||||
for it in &items {
|
||||
draw(&mut ctx, doc, it, view, &visible, opts);
|
||||
draw(&mut ctx, doc, it, view, &visible, opts, pass);
|
||||
}
|
||||
if faded {
|
||||
ctx.pop_layer();
|
||||
@@ -327,7 +405,7 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
|
||||
ctx.render(pm, &mut res);
|
||||
}
|
||||
context_pool::CONTEXTS.give_back(ctx);
|
||||
Rendered { width: w16 as u32, height: h16 as u32, pixels }
|
||||
pixels
|
||||
}
|
||||
|
||||
/// The on-screen colour behind page point (`x`, `y`): the paper (page colour), then any
|
||||
@@ -495,24 +573,30 @@ fn draw_watermark(ctx: &mut RenderContext, view: Affine, page: &Page, wm: &wordc
|
||||
|
||||
/// Does `view` map page points to device pixels without rotation, skew or mirroring, scaling both
|
||||
/// axes alike? Only then do hinted outlines (made on the pixel grid) line up with the screen.
|
||||
/// "Alike" allows the two axes a fifth of a percent apart: a page raster made to fill a whole
|
||||
/// number of pixels each way ([`render_area_to`]) is scaled that little differently across and
|
||||
/// down (a pixel in some two thousand), and is as upright as any.
|
||||
fn is_upright(view: Affine) -> bool {
|
||||
let [a, b, c, d, e, f] = view.as_coeffs();
|
||||
[a, b, c, d, e, f].iter().all(|v| v.is_finite()) && b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= a * 1e-6
|
||||
[a, b, c, d, e, f].iter().all(|v| v.is_finite()) && b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= a * 2e-3
|
||||
}
|
||||
|
||||
/// How far, in device pixels, macOS-style font smoothing pushes each side of a glyph outline out
|
||||
/// at `ppem` device pixels per em. Values from Pathfinder (MIT/Apache-2.0), which measured them
|
||||
/// against macOS: 1.21% of the pixel size horizontally and 1.25 times that vertically, each
|
||||
/// capped at 0.3 px, and no darkening past 72 px per em. We stroke the outline, which grows it
|
||||
/// evenly, so this is the mean of the two.
|
||||
/// sideways at `ppem` device pixels per em. The value is Pathfinder's (MIT/Apache-2.0), which
|
||||
/// measured it against macOS: 1.21% of the pixel size, capped at 0.3 px, and no darkening past
|
||||
/// 72 px per em. Pathfinder also grows glyphs up and down (1.25 times as far). We don't: a third
|
||||
/// of a pixel of grey above and below every letter is what made page text look out of focus
|
||||
/// beside other Mac apps, whose letters end on a clean pixel row. Stems get thicker, which is
|
||||
/// the weight the smoothing is for; the tops and feet of the letters stay where the font puts
|
||||
/// them.
|
||||
pub fn stem_darkening(ppem: f64) -> f64 {
|
||||
const FACTOR: [f64; 2] = [0.0121, 0.0121 * 1.25];
|
||||
const FACTOR: f64 = 0.0121;
|
||||
const MAX_PX: f64 = 0.3;
|
||||
const MAX_PPEM: f64 = 72.0;
|
||||
if !ppem.is_finite() || ppem <= 0.0 || ppem > MAX_PPEM {
|
||||
return 0.0;
|
||||
}
|
||||
FACTOR.iter().map(|f| (ppem * f).min(MAX_PX)).sum::<f64>() / 2.0
|
||||
(ppem * FACTOR).min(MAX_PX)
|
||||
}
|
||||
|
||||
/// A wavy line from `(x0, y0)` to `(x1, y1)`; at most 20 000 units long, so a huge extent can't make it endless.
|
||||
@@ -596,6 +680,7 @@ struct Frame<'a> {
|
||||
opts: &'a RenderOptions,
|
||||
view: Affine,
|
||||
visible: &'a kurbo::Rect,
|
||||
pass: Pass<'a>,
|
||||
}
|
||||
|
||||
/// The rectangle in kurbo's terms.
|
||||
@@ -607,12 +692,12 @@ fn kurbo_rect(rect: &wordcraft_geom::Rect) -> kurbo::Rect {
|
||||
/// `visible` is a culling area in those point coordinates; nested clips intersect it and turns
|
||||
/// transform it into the child's coordinates. Shape and path strokes apply their stored caps,
|
||||
/// while ink uses its tool's round ends and joins.
|
||||
fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visible: &kurbo::Rect, opts: &RenderOptions) {
|
||||
let fr = Frame { doc, opts, view, visible };
|
||||
fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visible: &kurbo::Rect, opts: &RenderOptions, pass: Pass) {
|
||||
let fr = Frame { doc, opts, view, visible, pass };
|
||||
match it {
|
||||
Draw::Figure { draws, .. } => {
|
||||
for d in draws {
|
||||
draw(ctx, doc, d, view, visible, opts);
|
||||
draw(ctx, doc, d, view, visible, opts, pass);
|
||||
}
|
||||
}
|
||||
Draw::Fill { .. } => draw_fill(ctx, &fr, it),
|
||||
@@ -634,7 +719,7 @@ fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visibl
|
||||
ctx.push_clip_layer(&r.to_path(0.1));
|
||||
let local = r.intersect(*visible);
|
||||
for it in items {
|
||||
draw(ctx, doc, it, view, &local, opts);
|
||||
draw(ctx, doc, it, view, &local, opts, pass);
|
||||
}
|
||||
ctx.pop_layer();
|
||||
}
|
||||
@@ -642,14 +727,14 @@ fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visibl
|
||||
let m = Affine::new(Draw::turn_matrix(*turn, *x, *y).map(f64::from));
|
||||
let local = m.inverse().transform_rect_bbox(*visible);
|
||||
for it in items {
|
||||
draw(ctx, doc, it, view * m, &local, opts);
|
||||
draw(ctx, doc, it, view * m, &local, opts, pass);
|
||||
}
|
||||
}
|
||||
Draw::Rotated { cx, cy, spin, items } => {
|
||||
let m = Affine::new(spin.matrix(*cx, *cy).map(f64::from));
|
||||
let local = m.inverse().transform_rect_bbox(*visible);
|
||||
for it in items {
|
||||
draw(ctx, doc, it, view * m, &local, opts);
|
||||
draw(ctx, doc, it, view * m, &local, opts, pass);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -704,7 +789,8 @@ fn draw_line(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
}
|
||||
_ => {
|
||||
let (st, off) = match snap_rule(fr.view, (x0, y0, x1, y1), w) {
|
||||
Some((w_px, off)) => (kurbo::Stroke { width: w_px / fr.view.as_coeffs()[0], ..st }, off),
|
||||
// The width is across the rule: in points by the scale that way.
|
||||
Some((w_px, off)) => (kurbo::Stroke { width: w_px / rule_scale(fr.view, y0 == y1), ..st }, off),
|
||||
None => (st, (0.0, 0.0)),
|
||||
};
|
||||
ctx.set_stroke(st);
|
||||
@@ -721,11 +807,13 @@ fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -
|
||||
if !is_upright(view) {
|
||||
return None;
|
||||
}
|
||||
let [k, _, _, _, tx, ty] = view.as_coeffs();
|
||||
let [_, _, _, _, tx, ty] = view.as_coeffs();
|
||||
if y0 == y1 && x0 != x1 {
|
||||
let k = rule_scale(view, true);
|
||||
let (w_px, c) = snap_hairline(y0 * k + ty, width * k);
|
||||
Some((w_px, (0.0, (c - ty) / k - y0)))
|
||||
} else if x0 == x1 && y0 != y1 {
|
||||
let k = rule_scale(view, false);
|
||||
let (w_px, c) = snap_hairline(x0 * k + tx, width * k);
|
||||
Some((w_px, ((c - tx) / k - x0, 0.0)))
|
||||
} else {
|
||||
@@ -733,6 +821,16 @@ fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -
|
||||
}
|
||||
}
|
||||
|
||||
/// Device pixels per point across a rule: down the page for a level rule, across it for an
|
||||
/// upright one. An upright view ([`is_upright`]) may scale the two a little differently (a page
|
||||
/// raster made to fill a whole number of pixels each way), and a rule's place and width are
|
||||
/// measured across it: with the other scale, a level rule low on such a page was snapped up to
|
||||
/// a pixel from where it lies, its edges between pixel rows.
|
||||
fn rule_scale(view: Affine, level: bool) -> f64 {
|
||||
let [across, _, _, down, ..] = view.as_coeffs();
|
||||
if level { down } else { across }
|
||||
}
|
||||
|
||||
/// A line `width_px` wide centred at device coordinate `centre`, moved so both edges fall on whole
|
||||
/// pixels. Returns the width, made a whole number of pixels (at least one), and the new centre.
|
||||
fn snap_hairline(centre: f64, width_px: f64) -> (f64, f64) {
|
||||
@@ -762,23 +860,25 @@ fn draw_glyphs(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
// Scaled letters (`w:w`): each glyph stretched across from its pen position.
|
||||
let sx = if x_scale.is_finite() && *x_scale > 0.0 { f64::from(*x_scale) } else { 1.0 };
|
||||
let skew = Affine::scale_non_uniform(sx, 1.0) * skew;
|
||||
// Outline strokes, in font units: synthetic bold, then on-screen stem darkening (a
|
||||
// stroke grows the outline by half its width on each side). Darkening is skipped for
|
||||
// translucent text, where the stroke overlapping the fill would show as a darker rim.
|
||||
// Synthetic bold strokes the outline, in font units.
|
||||
let px_per_pt = view.determinant().abs().sqrt();
|
||||
let darken_px = if opts.text_darkening && *alpha >= 1.0 { stem_darkening(*size as f64 * px_per_pt) } else { 0.0 };
|
||||
let darken = if darken_px > 0.0 && k * px_per_pt > 0.0 { 2.0 * darken_px / (k * px_per_pt) } else { 0.0 };
|
||||
let outline_stroke = if *synth_bold { face.upem * 0.03 } else { 0.0 } + darken;
|
||||
let join = if darken > 0.0 { kurbo::Join::Round } else { kurbo::Join::Miter };
|
||||
let outline_stroke = if *synth_bold { face.upem * 0.03 } else { 0.0 };
|
||||
if outline_stroke > 0.0 {
|
||||
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(join));
|
||||
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(kurbo::Join::Miter));
|
||||
}
|
||||
// Emoji and other colour glyphs (#1269) are drawn from the font's colour data.
|
||||
let colour = face.has_color_glyphs();
|
||||
let ppem = *size as f64 * px_per_pt;
|
||||
// Hinted outlines are in device pixels: only for an upright, unmirrored, evenly scaled
|
||||
// view (not rotated text boxes), where the pixel grid lines up with the glyphs.
|
||||
let hint_ppem = (opts.hinting && !colour && is_upright(view)).then_some(ppem as f32);
|
||||
// On-screen stem darkening: each outline is widened along its own x axis, in one piece (see
|
||||
// [`stem_darkening`] and [`widened`]). Skipped for translucent text, as it always was.
|
||||
let strength = if opts.text_darkening.is_finite() { f64::from(opts.text_darkening).clamp(0.0, 2.0) } else { 0.0 };
|
||||
let darken_px = if *alpha >= 1.0 { stem_darkening(ppem) * strength } else { 0.0 };
|
||||
// Hinted outlines are in device pixels, and a snapped baseline is a row of them: only for an
|
||||
// upright, unmirrored, evenly scaled view (not rotated text boxes), where the pixel grid
|
||||
// lines up with the glyphs.
|
||||
let upright = is_upright(view);
|
||||
let hint_ppem = (opts.hinting && !colour && upright).then_some(ppem as f32);
|
||||
let snap = opts.baseline_snap && upright;
|
||||
// The outline strokes in device pixels, for the hinted outlines.
|
||||
let stroke_px = outline_stroke * k * px_per_pt;
|
||||
let mut hinted_stroke = false;
|
||||
@@ -795,39 +895,130 @@ fn draw_glyphs(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
ctx.set_paint(color(opts.ink(*c), *alpha));
|
||||
continue;
|
||||
}
|
||||
if let Some(o) = hint_ppem.and_then(|p| db.hinted_outline(face, *gid, p)) {
|
||||
if o.elements().is_empty() {
|
||||
continue;
|
||||
let pen = view * kurbo::Point::new(gx, gy);
|
||||
let hinted = hint_ppem.and_then(|p| db.hinted_outline(face, *gid, p));
|
||||
let hinted_now = hinted.is_some();
|
||||
let (o, at) = if let Some(o) = hinted {
|
||||
if outline_stroke > 0.0 && !hinted_stroke {
|
||||
ctx.set_stroke(kurbo::Stroke::new(stroke_px).with_join(kurbo::Join::Miter));
|
||||
hinted_stroke = true;
|
||||
}
|
||||
// The baseline on a whole pixel, as the hinting assumes.
|
||||
let at = view * kurbo::Point::new(gx, gy);
|
||||
ctx.set_transform(Affine::translate((at.x, at.y.round())) * skew);
|
||||
ctx.fill_path(&o);
|
||||
if outline_stroke > 0.0 {
|
||||
if !hinted_stroke {
|
||||
ctx.set_stroke(kurbo::Stroke::new(stroke_px).with_join(join));
|
||||
hinted_stroke = true;
|
||||
}
|
||||
ctx.stroke_path(&o);
|
||||
(o, Affine::translate((pen.x, pen.y.round())) * skew)
|
||||
} else {
|
||||
if outline_stroke > 0.0 && hinted_stroke {
|
||||
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(kurbo::Join::Miter));
|
||||
hinted_stroke = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let o = db.outline(face, *gid);
|
||||
let at = view * Affine::translate((gx, gy)) * skew * Affine::scale(k);
|
||||
// The same baseline for text drawn from the font's own outlines.
|
||||
let lift = if snap && pen.y.is_finite() { pen.y.round() - pen.y } else { 0.0 };
|
||||
(db.outline(face, *gid), Affine::translate((0.0, lift)) * at)
|
||||
};
|
||||
if o.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
ctx.set_transform(view * Affine::translate((gx, gy)) * skew * Affine::scale(k));
|
||||
ctx.fill_path(&o);
|
||||
// This pass's sideways shift, across the screen whichever way the text is turned.
|
||||
fr.pass.drew_text.set(true);
|
||||
ctx.set_transform(Affine::translate((fr.pass.shift, 0.0)) * at);
|
||||
// The darkened outline is the glyph: synthetic bold strokes it too. Stroking the font's own
|
||||
// outline there would cover the widening (the stroke reaches further than it does) and
|
||||
// leave such text as light as without darkening.
|
||||
let wide = (darken_px > 0.0).then(|| widened(&o, darken_px / widen_unit(hinted_now, k * px_per_pt, sx)));
|
||||
let shape = wide.as_ref().unwrap_or(&o);
|
||||
ctx.fill_path(shape);
|
||||
if outline_stroke > 0.0 {
|
||||
if hinted_stroke {
|
||||
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(join));
|
||||
hinted_stroke = false;
|
||||
}
|
||||
ctx.stroke_path(&o);
|
||||
ctx.stroke_path(shape);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many device pixels one unit of a glyph outline is across the screen, for turning a
|
||||
/// widening in device pixels into the outline's own units: a hinted outline is in device pixels
|
||||
/// already and the font's own in font units (`font_px` device pixels each), and both are then
|
||||
/// stretched `stretch` times across by scaled letters (`w:w`). Without the stretch for hinted
|
||||
/// outlines, text scaled to 400 % was widened four times too far.
|
||||
fn widen_unit(hinted: bool, font_px: f64, stretch: f64) -> f64 {
|
||||
if hinted { stretch } else { font_px * stretch }
|
||||
}
|
||||
|
||||
/// `path` with every edge moved `d` sideways, away from the ink: the shape a glyph makes when it
|
||||
/// is smeared `d` to the left and `d` to the right, so stems get `2 d` thicker while nothing
|
||||
/// grows up or down. One outline, filled once, so partly covered pixels are counted once (the
|
||||
/// outline drawn again beside itself counted them two and three times, which read as bold).
|
||||
///
|
||||
/// Each point moves with the edges it joins: by `d` where both face the same side, or one of
|
||||
/// them is level; not at all at the top or the foot of a curve, where one faces left and the
|
||||
/// other right. Curve control points move by the same rule along the control polygon. Which side
|
||||
/// of an edge is ink follows from the direction the outline runs in, read off its signed area,
|
||||
/// so the holes of letters narrow as their stems widen. An outline with no area, or with
|
||||
/// numbers that aren't finite, is returned as it is.
|
||||
fn widened(path: &BezPath, d: f64) -> BezPath {
|
||||
use kurbo::PathEl;
|
||||
let els = path.elements();
|
||||
// The control polygon of each contour, as (first point index, point count).
|
||||
let mut pts: Vec<kurbo::Point> = Vec::with_capacity(els.len() * 2);
|
||||
let mut contours: Vec<(usize, usize)> = Vec::new();
|
||||
let mut start = 0;
|
||||
for el in els {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
if pts.len() > start {
|
||||
contours.push((start, pts.len() - start));
|
||||
}
|
||||
start = pts.len();
|
||||
pts.push(*p);
|
||||
}
|
||||
PathEl::LineTo(p) => pts.push(*p),
|
||||
PathEl::QuadTo(c, p) => pts.extend([*c, *p]),
|
||||
PathEl::CurveTo(c1, c2, p) => pts.extend([*c1, *c2, *p]),
|
||||
PathEl::ClosePath => {}
|
||||
}
|
||||
}
|
||||
if pts.len() > start {
|
||||
contours.push((start, pts.len() - start));
|
||||
}
|
||||
let ring = |first: usize, n: usize, i: usize| pts.get(first + i % n.max(1)).copied().unwrap_or_default();
|
||||
let area: f64 =
|
||||
contours.iter().map(|&(first, n)| (0..n).map(|i| ring(first, n, i).to_vec2().cross(ring(first, n, i + 1).to_vec2())).sum::<f64>()).sum();
|
||||
if !(d.is_finite() && d > 0.0 && area.is_finite() && area != 0.0) {
|
||||
return path.clone();
|
||||
}
|
||||
// Which way the edge from `a` to `b` faces: 1 right, -1 left, 0 for a level edge.
|
||||
let faces = |a: kurbo::Point, b: kurbo::Point| {
|
||||
let (run, rise) = ((b.x - a.x).abs(), b.y - a.y);
|
||||
if rise.abs() <= 1e-6 * (run + rise.abs()) { 0.0 } else { (rise * area).signum() }
|
||||
};
|
||||
let mut moved = pts.clone();
|
||||
for &(first, n) in &contours {
|
||||
for i in 0..n {
|
||||
let at = ring(first, n, i);
|
||||
// The nearest different points before and after: a contour may repeat a point (a
|
||||
// run of more than a few is left where it is).
|
||||
let before = (1..n.min(8)).map(|step| ring(first, n, i + n - step)).find(|p| *p != at);
|
||||
let after = (1..n.min(8)).map(|step| ring(first, n, i + step)).find(|p| *p != at);
|
||||
let (Some(before), Some(after)) = (before, after) else { continue };
|
||||
let push = (faces(before, at) + faces(at, after)).clamp(-1.0, 1.0);
|
||||
if let Some(p) = moved.get_mut(first + i) {
|
||||
p.x += push * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut next = moved.into_iter();
|
||||
let mut take = || next.next().unwrap_or_default();
|
||||
let mut out = BezPath::with_capacity(els.len());
|
||||
for el in els {
|
||||
out.push(match el {
|
||||
PathEl::MoveTo(_) => PathEl::MoveTo(take()),
|
||||
PathEl::LineTo(_) => PathEl::LineTo(take()),
|
||||
PathEl::QuadTo(..) => PathEl::QuadTo(take(), take()),
|
||||
PathEl::CurveTo(..) => PathEl::CurveTo(take(), take(), take()),
|
||||
PathEl::ClosePath => PathEl::ClosePath,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn draw_mark(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
|
||||
let Draw::Mark { x, baseline, size, ch, color: mark } = it else { return };
|
||||
let face = wordcraft_fonts::word::resolve("Source Sans 3", false, false).face;
|
||||
@@ -1280,6 +1471,19 @@ pub fn render_area(doc: &Document, page: &Page, area: wordcraft_geom::Rect, scal
|
||||
render_region(doc, page, pw, ph, view, opts)
|
||||
}
|
||||
|
||||
/// Render the page `area` (points) into exactly `w`×`h` pixels: the area fills the raster, scaled
|
||||
/// across and down by whatever that takes. For a raster that must be a given number of device
|
||||
/// pixels each way, where [`render_area`]'s single scale gives the next whole pixel up: a picture
|
||||
/// one pixel larger than its place on screen is scaled into it, and every glyph resampled.
|
||||
pub fn render_area_to(doc: &Document, page: &Page, area: wordcraft_geom::Rect, w: u32, h: u32, opts: &RenderOptions) -> Rendered {
|
||||
let (w, h) = (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE));
|
||||
let (sx, sy) = (f64::from(w) / f64::from(area.w), f64::from(h) / f64::from(area.h));
|
||||
let fine = |v: f64| v.is_finite() && v > 0.0;
|
||||
let (sx, sy) = if fine(sx) && fine(sy) && area.x.is_finite() && area.y.is_finite() { (sx, sy) } else { (1.0, 1.0) };
|
||||
let (x, y) = if area.x.is_finite() && area.y.is_finite() { (f64::from(area.x), f64::from(area.y)) } else { (0.0, 0.0) };
|
||||
render_region(doc, page, w, h, Affine::scale_non_uniform(sx, sy) * Affine::translate((-x, -y)), opts)
|
||||
}
|
||||
|
||||
/// Draw `items` (page points) alone, on nothing, over the page `area` (points) at `scale` px/pt:
|
||||
/// no paper, no watermark. A dragged object's preview.
|
||||
pub fn render_items(doc: &Document, items: &[Draw], area: wordcraft_geom::Rect, scale: f32, opts: &RenderOptions) -> Rendered {
|
||||
@@ -1293,8 +1497,10 @@ pub fn render_items(doc: &Document, items: &[Draw], area: wordcraft_geom::Rect,
|
||||
* Affine::translate((-x as f64, -y as f64));
|
||||
let mut ctx = RenderContext::new_with(w16, h16, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() });
|
||||
let visible = view.inverse().transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, w16 as f64, h16 as f64)).inflate(40.0, 40.0);
|
||||
// One pass, text in its place: an area raster (a preview, a dragged object) is greyscale.
|
||||
let drew_text = std::cell::Cell::new(false);
|
||||
for it in items {
|
||||
draw(&mut ctx, doc, it, view, &visible, opts);
|
||||
draw(&mut ctx, doc, it, view, &visible, opts, Pass { shift: 0.0, drew_text: &drew_text });
|
||||
}
|
||||
ctx.flush();
|
||||
let mut pixels = vec![0u8; w16 as usize * h16 as usize * 4];
|
||||
|
||||
+358
-3
@@ -265,7 +265,7 @@ fn stem_darkening_follows_the_macos_curve() {
|
||||
assert_eq!(stem_darkening(f64::NAN), 0.0);
|
||||
assert_eq!(stem_darkening(-5.0), 0.0);
|
||||
// Small text grows in proportion to its pixel size...
|
||||
assert!((stem_darkening(10.0) - 10.0 * 0.0121 * 2.25 / 2.0).abs() < 1e-9);
|
||||
assert!((stem_darkening(10.0) - 10.0 * 0.0121).abs() < 1e-9);
|
||||
// ...body text on a Retina screen hits the 0.3 px cap...
|
||||
assert_eq!(stem_darkening(30.0), 0.3);
|
||||
assert_eq!(stem_darkening(72.0), 0.3);
|
||||
@@ -283,12 +283,29 @@ fn text_darkening_adds_ink_on_screen_only() {
|
||||
let d = Document::from_text("Marketing analytics lead with twelve years of measurement work.");
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let plain = render_page(&d, &l.pages[0], 2.0, &RenderOptions::default());
|
||||
let dark = render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: true, ..Default::default() });
|
||||
let dark = render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: 1.0, ..Default::default() });
|
||||
let (a, b) = (ink(&plain), ink(&dark));
|
||||
// About 0.3 px more on every edge of an 11 pt line at 2x: clearly more ink, not bold.
|
||||
assert!(b as f64 > a as f64 * 1.08 && (b as f64) < a as f64 * 1.6, "plain {a}, darkened {b}");
|
||||
// Off by default: exports and thumbnails are untouched.
|
||||
assert!(!RenderOptions::default().text_darkening);
|
||||
assert_eq!(RenderOptions::default().text_darkening, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_darkening_is_a_strength() {
|
||||
let d = Document::from_text("Marketing analytics lead with twelve years of measurement work.");
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let at = |strength: f32| ink(&render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: strength, ..Default::default() }));
|
||||
// The system's lighter, default and stronger steps each add ink.
|
||||
let (none, light, default, strong) = (at(0.0), at(0.5), at(1.0), at(1.5));
|
||||
assert!(none < light && light < default && default < strong, "{none} {light} {default} {strong}");
|
||||
assert_eq!(none, ink(&render_page(&d, &l.pages[0], 2.0, &RenderOptions::default())));
|
||||
// No more than twice the default, and junk is no darkening at all.
|
||||
assert_eq!(at(2.0), at(50.0));
|
||||
assert_eq!(at(2.0), at(f32::INFINITY.min(f32::MAX)));
|
||||
for junk in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0] {
|
||||
assert_eq!(at(junk), none, "{junk}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Inked pixels that are only partly covered (grey): an edge between two pixel rows.
|
||||
@@ -303,6 +320,315 @@ fn ink_columns(img: &Rendered) -> (usize, usize) {
|
||||
(inked.iter().copied().min().unwrap_or(0), inked.iter().copied().max().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// The first and last pixel rows with any ink.
|
||||
fn ink_row_span(img: &Rendered) -> (usize, usize) {
|
||||
let w = img.width as usize;
|
||||
let inked: Vec<usize> = img.pixels.as_chunks::<4>().0.iter().enumerate().filter(|(_, p)| p[0] < 250).map(|(i, _)| i / w.max(1)).collect();
|
||||
(inked.iter().copied().min().unwrap_or(0), inked.iter().copied().max().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// One line of flat-footed capitals in a bundled face: no letter dips under the baseline.
|
||||
fn flat_capitals() -> (Document, wordcraft_layout::DocLayout) {
|
||||
let mut d = Document::from_text("THE FELT HILT FILE LIFT HEFT TILT");
|
||||
let styles = std::sync::Arc::make_mut(&mut d.styles);
|
||||
styles.default_chr.font = Some("Source Sans 3".into());
|
||||
styles.default_chr.size = Some(12.0);
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
(d, l)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapped_baseline_ends_the_letters_on_a_whole_pixel_row() {
|
||||
let (d, l) = flat_capitals();
|
||||
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
// Scales that put the baseline at different places between two pixel rows.
|
||||
let mut sharper = 0;
|
||||
for scale in [1.0, 1.25, 1.45, 96.0 / 72.0 * 1.45, 2.0, 2.3] {
|
||||
let plain = render_page(&d, &l.pages[0], scale, &RenderOptions::default());
|
||||
let snapped = render_page(&d, &l.pages[0], scale, &snap);
|
||||
// The row under the letters' feet: all of it white once the baseline is on a pixel
|
||||
// boundary, where the unsnapped feet leave a grey row or end a row early.
|
||||
let (_, foot) = ink_row_span(&snapped);
|
||||
let w = snapped.width as usize;
|
||||
let foot_row = &snapped.pixels[foot * w * 4..(foot + 1) * w * 4];
|
||||
let darkest = foot_row.as_chunks::<4>().0.iter().map(|p| p[0]).min().unwrap_or(255);
|
||||
assert!(darkest < 16, "scale {scale}: the feet fill their last row (darkest pixel {darkest})");
|
||||
let (g0, g1) = (grey(&plain), grey(&snapped));
|
||||
assert!(g1 <= g0, "scale {scale}: grey pixels: plain {g0}, snapped {g1}");
|
||||
sharper += usize::from(g1 < g0);
|
||||
// The same weight, and nothing moves sideways.
|
||||
let (a, b) = (ink(&plain), ink(&snapped));
|
||||
assert!((b as f64 - a as f64).abs() < a as f64 * 0.02, "scale {scale}: ink: plain {a}, snapped {b}");
|
||||
assert_eq!(ink_columns(&plain), ink_columns(&snapped), "scale {scale}");
|
||||
// No more than half a pixel up or down.
|
||||
let ((t0, b0), (t1, b1)) = (ink_row_span(&plain), ink_row_span(&snapped));
|
||||
assert!(t0.abs_diff(t1) <= 1 && b0.abs_diff(b1) <= 1, "scale {scale}: plain {t0}..{b0}, snapped {t1}..{b1}");
|
||||
}
|
||||
assert!(sharper >= 3, "snapping sharpened {sharper} of 6 scales");
|
||||
// Off by default: exports and thumbnails are untouched.
|
||||
assert!(!RenderOptions::default().baseline_snap);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_views_keep_their_baselines() {
|
||||
let (d, l) = flat_capitals();
|
||||
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
let view = Affine::translate((300.0, -50.0)) * Affine::rotate(0.3) * Affine::scale(1.9);
|
||||
let plain = render_region(&d, &l.pages[0], 600, 300, view, &RenderOptions::default());
|
||||
assert!(ink(&plain) > 0);
|
||||
assert_eq!(plain.pixels, render_region(&d, &l.pages[0], 600, 300, view, &snap).pixels);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn darkening_thickens_stems_and_leaves_the_tops_and_feet_of_letters_alone() {
|
||||
let (d, l) = flat_capitals();
|
||||
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
let dark = RenderOptions { text_darkening: 1.0, ..snap.clone() };
|
||||
for scale in [1.0, 1.45, 2.0] {
|
||||
let plain = render_page(&d, &l.pages[0], scale, &snap);
|
||||
let darkened = render_page(&d, &l.pages[0], scale, &dark);
|
||||
// More ink, in the same pixel rows: nothing is added above the letters or under them
|
||||
// (the stroke this replaces put a third of a pixel of grey on both).
|
||||
assert!(ink(&darkened) as f64 > ink(&plain) as f64 * 1.05, "scale {scale}");
|
||||
assert_eq!(ink_row_span(&plain), ink_row_span(&darkened), "scale {scale}");
|
||||
// Sideways, less than a pixel each way.
|
||||
let ((l0, r0), (l1, r1)) = (ink_columns(&plain), ink_columns(&darkened));
|
||||
assert!(l1 <= l0 && l0 - l1 <= 1 && r1 >= r0 && r1 - r0 <= 1, "scale {scale}: plain {l0}..{r0}, darkened {l1}..{r1}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_moves_edges_sideways_away_from_the_ink() {
|
||||
// A 10 x 10 square with a 4 x 4 hole, the hole running the other way round.
|
||||
let mut ring = kurbo::Rect::new(0.0, 0.0, 10.0, 10.0).to_path(0.1);
|
||||
ring.move_to((3.0, 3.0));
|
||||
for p in [(3.0, 7.0), (7.0, 7.0), (7.0, 3.0)] {
|
||||
ring.line_to(p);
|
||||
}
|
||||
ring.close_path();
|
||||
for path in [ring.clone(), ring.reverse_subpaths()] {
|
||||
let wide = widened(&path, 0.5);
|
||||
// The square is 1 wider and the hole 1 narrower; neither is any taller.
|
||||
let b = wide.bounding_box();
|
||||
assert_eq!((b.x0, b.x1, b.y0, b.y1), (-0.5, 10.5, 0.0, 10.0));
|
||||
assert!((wide.area().abs() - (11.0 * 10.0 - 3.0 * 4.0)).abs() < 1e-9, "{}", wide.area());
|
||||
assert_eq!(wide.elements().len(), path.elements().len());
|
||||
}
|
||||
// A round shape: wider, no taller, and its top and bottom points stay put.
|
||||
let disc = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(1e-3);
|
||||
let b = widened(&disc, 0.25).bounding_box();
|
||||
assert!((b.width() - 10.5).abs() < 0.02 && (b.height() - 10.0).abs() < 0.02, "{b:?}");
|
||||
// Nothing to widen, or nothing to widen by: the path comes back as it was.
|
||||
let line = BezPath::from_vec(vec![kurbo::PathEl::MoveTo((0.0, 0.0).into()), kurbo::PathEl::LineTo((5.0, 5.0).into())]);
|
||||
for (path, d) in [(&line, 0.5), (&ring, 0.0), (&ring, -1.0), (&ring, f64::NAN), (&ring, f64::INFINITY), (&BezPath::new(), 0.5)] {
|
||||
assert_eq!(widened(path, d).elements(), path.elements(), "{d}");
|
||||
}
|
||||
// Hostile outlines don't panic: points that aren't numbers, and one point repeated.
|
||||
let mut odd = BezPath::new();
|
||||
odd.move_to((f64::NAN, 0.0));
|
||||
odd.line_to((1.0, f64::INFINITY));
|
||||
odd.quad_to((2.0, 2.0), (0.0, 0.0));
|
||||
let _ = widened(&odd, 0.5);
|
||||
let mut same = BezPath::new();
|
||||
same.move_to((1.0, 1.0));
|
||||
for _ in 0..50 {
|
||||
same.line_to((1.0, 1.0));
|
||||
}
|
||||
same.line_to((4.0, 1.0));
|
||||
same.line_to((4.0, 5.0));
|
||||
same.close_path();
|
||||
assert_eq!(widened(&same, 0.5).elements().len(), same.elements().len());
|
||||
}
|
||||
|
||||
/// The sum of one colour channel's distance from white.
|
||||
fn channel_ink(img: &Rendered, channel: usize) -> u64 {
|
||||
img.pixels.as_chunks::<4>().0.iter().map(|p| 255 - p[channel] as u64).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lcd_text_takes_each_channel_from_around_its_own_stripe() {
|
||||
let d = Document::from_text("Nobody has assembled this board yet. Italic and round strokes gain the most.");
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let (w, h) = (700, 200);
|
||||
let view = Affine::scale(1.25);
|
||||
let lcd = |order| RenderOptions { lcd: Some(order), ..Default::default() };
|
||||
let grey = render_region(&d, &l.pages[0], w, h, view, &RenderOptions::default());
|
||||
let rgb = render_region(&d, &l.pages[0], w, h, view, &lcd(LcdOrder::Rgb));
|
||||
let bgr = render_region(&d, &l.pages[0], w, h, view, &lcd(LcdOrder::Bgr));
|
||||
assert!(ink(&grey) > 0);
|
||||
// The page a third of a pixel to the right and to the left, in greyscale.
|
||||
let moved = |dx: f64| render_region(&d, &l.pages[0], w, h, Affine::translate((dx, 0.0)) * view, &RenderOptions::default());
|
||||
let (right, left) = (moved(1.0 / 3.0), moved(-1.0 / 3.0));
|
||||
let mut coloured = 0;
|
||||
let rasters = [&grey, &rgb, &bgr, &right, &left].map(|r| r.pixels.as_chunks::<4>().0);
|
||||
for i in 0..rasters[0].len() {
|
||||
let [g, c, m, r, l] = rasters.map(|px| px[i]);
|
||||
// Green sits in the middle of the pixel: it and the alpha are the greyscale raster's.
|
||||
assert_eq!((c[1], c[3]), (g[1], g[3]));
|
||||
// Red is what a pixel a third to the left would see, blue a third to the right.
|
||||
assert_eq!((c[0], c[2]), (r[0], l[2]), "pixel {i}");
|
||||
// BGR stripes are the mirror image.
|
||||
assert_eq!((m[0], m[1], m[2], m[3]), (c[2], c[1], c[0], c[3]));
|
||||
coloured += usize::from(c[0] != c[2]);
|
||||
}
|
||||
assert!(coloured > 200, "{coloured} pixels have red and blue apart");
|
||||
// No colour cast: each channel carries the same ink, to within a hundredth.
|
||||
let [r, g, b] = [0, 1, 2].map(|c| channel_ink(&rgb, c) as f64);
|
||||
assert!((r - g).abs() < g * 0.01 && (b - g).abs() < g * 0.01, "{r} {g} {b}");
|
||||
// Off by default: exports and thumbnails are untouched.
|
||||
assert_eq!(RenderOptions::default().lcd, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lcd_changes_nothing_but_text() {
|
||||
let lcd = RenderOptions { lcd: Some(LcdOrder::Rgb), ..Default::default() };
|
||||
// A page with no text: the same raster, from one pass.
|
||||
let mut blank = Document::from_text("");
|
||||
blank.settings.page_color = Some(Rgb(0x20, 0x60, 0xA0));
|
||||
let l = layout(&blank, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
assert_eq!(render_page(&blank, &l.pages[0], 0.5, &lcd).pixels, render_page(&blank, &l.pages[0], 0.5, &RenderOptions::default()).pixels);
|
||||
// A page with text on a page colour: pixels differ only where the text is.
|
||||
let mut d = Document::from_text("Coloured paper under one line of text.");
|
||||
d.settings.page_color = Some(Rgb(0xFF, 0xF0, 0xC0));
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let (grey, sub) = (render_page(&d, &l.pages[0], 1.25, &RenderOptions::default()), render_page(&d, &l.pages[0], 1.25, &lcd));
|
||||
let w = grey.width as usize;
|
||||
let paper = grey.pixels[..4].to_vec();
|
||||
let inked: Vec<usize> = grey.pixels.as_chunks::<4>().0.iter().enumerate().filter(|(_, p)| p[..] != paper[..]).map(|(i, _)| i).collect();
|
||||
let (top, bottom) = (inked.iter().map(|i| i / w).min().unwrap(), inked.iter().map(|i| i / w).max().unwrap());
|
||||
let (first, last) = (inked.iter().map(|i| i % w).min().unwrap(), inked.iter().map(|i| i % w).max().unwrap());
|
||||
let mut changed = 0;
|
||||
for (i, (a, b)) in grey.pixels.as_chunks::<4>().0.iter().zip(sub.pixels.as_chunks::<4>().0).enumerate() {
|
||||
if a != b {
|
||||
changed += 1;
|
||||
let (x, y) = (i % w, i / w);
|
||||
assert!((top..=bottom).contains(&y) && x + 1 >= first && x <= last + 1, "pixel {x},{y} is outside the text");
|
||||
}
|
||||
}
|
||||
assert!(changed > 50, "{changed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lcd_channels_never_exceed_the_alpha() {
|
||||
// Premultiplied pixels: a colour above its alpha would be brighter than white.
|
||||
let mut px = vec![10, 20, 30, 40, 200, 200, 200, 255];
|
||||
take_lcd_channels(&mut px, &[90, 0, 0, 255, 7, 0, 0, 255], &[0, 0, 80, 255, 0, 0, 9, 255]);
|
||||
assert_eq!(px, [40, 20, 40, 40, 7, 200, 9, 255]);
|
||||
// Rasters of other sizes leave the rest alone and don't panic.
|
||||
let mut px = vec![1, 2, 3, 255, 4, 5, 6, 255, 9];
|
||||
take_lcd_channels(&mut px, &[50, 0, 0, 255], &[]);
|
||||
assert_eq!(px, [1, 2, 3, 255, 4, 5, 6, 255, 9]);
|
||||
}
|
||||
|
||||
/// The glyph runs of `text` in a bundled face at 12 pt, as the page draws them, each changed by
|
||||
/// `change`; and the area they are in.
|
||||
fn glyph_runs(text: &str, change: impl Fn(&mut Draw)) -> (Document, Vec<Draw>, wordcraft_geom::Rect) {
|
||||
let mut d = Document::from_text(text);
|
||||
let styles = std::sync::Arc::make_mut(&mut d.styles);
|
||||
styles.default_chr.font = Some("Source Sans 3".into());
|
||||
styles.default_chr.size = Some(12.0);
|
||||
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
|
||||
let page = &l.pages[0];
|
||||
let mut runs: Vec<Draw> = page_layers(&d, page, &DisplayOptions::default())
|
||||
.into_iter()
|
||||
.flat_map(|(_, items)| items)
|
||||
.filter(|it| matches!(it, Draw::Glyphs { .. }))
|
||||
.collect();
|
||||
assert!(!runs.is_empty());
|
||||
runs.iter_mut().for_each(change);
|
||||
(d, runs, wordcraft_geom::Rect::new(0.0, 0.0, page.w, 200.0))
|
||||
}
|
||||
|
||||
/// How much is drawn on nothing: the sum of the pixels' opacity.
|
||||
fn opacity(img: &Rendered) -> u64 {
|
||||
img.pixels.as_chunks::<4>().0.iter().map(|p| p[3] as u64).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_bold_is_darkened_too() {
|
||||
// A face with no bold of its own is made bold by stroking its outlines. The stroke reaches
|
||||
// further than the darkening does, so it has to stroke the darkened outline: the darkening
|
||||
// then moves the bold text's edges as far as the regular text's, and adds about as much ink.
|
||||
let added = |bold: bool, scale: f32| {
|
||||
let (d, runs, area) = glyph_runs("Bold made by stroking the outline", |run| {
|
||||
if let Draw::Glyphs { synth_bold, .. } = run {
|
||||
*synth_bold = bold;
|
||||
}
|
||||
});
|
||||
let dark = RenderOptions { text_darkening: 1.0, ..Default::default() };
|
||||
let (plain, darkened) =
|
||||
(opacity(&render_items(&d, &runs, area, scale, &RenderOptions::default())), opacity(&render_items(&d, &runs, area, scale, &dark)));
|
||||
assert!(plain > 0 && darkened > plain, "bold {bold}: plain {plain}, darkened {darkened}");
|
||||
(darkened - plain) as f64
|
||||
};
|
||||
for scale in [1.0, 2.0] {
|
||||
let (regular, bold) = (added(false, scale), added(true, scale));
|
||||
assert!(bold > regular * 0.75, "scale {scale}: ink added: {regular} regular, {bold} bold");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stretched_hinted_text_is_darkened_as_far_as_unstretched() {
|
||||
// One letter, hinted, at its own width and scaled to 400 % (`w:w`): the darkening moves each
|
||||
// edge the same distance on screen, so it adds about the same ink to both.
|
||||
let added = |stretch: f32| {
|
||||
let (d, runs, area) = glyph_runs("H", |run| {
|
||||
if let Draw::Glyphs { x_scale, .. } = run {
|
||||
*x_scale = stretch;
|
||||
}
|
||||
});
|
||||
let hint = RenderOptions { hinting: true, ..Default::default() };
|
||||
let dark = RenderOptions { text_darkening: 1.0, ..hint.clone() };
|
||||
let (plain, darkened) = (opacity(&render_items(&d, &runs, area, 2.0, &hint)), opacity(&render_items(&d, &runs, area, 2.0, &dark)));
|
||||
assert!(darkened > plain, "stretch {stretch}: plain {plain}, darkened {darkened}");
|
||||
(darkened - plain) as f64
|
||||
};
|
||||
let (own, stretched) = (added(1.0), added(4.0));
|
||||
assert!(stretched < own * 1.5 && stretched > own * 0.6, "ink added: {own} unstretched, {stretched} stretched");
|
||||
// The conversion itself: a widening of `px` device pixels, in outline units, is `px` again
|
||||
// once the outline is on screen.
|
||||
for (hinted, font_px, stretch) in [(true, 0.02, 1.0), (true, 0.02, 4.0), (false, 0.02, 1.0), (false, 0.02, 4.0)] {
|
||||
let on_screen = if hinted { stretch } else { font_px * stretch };
|
||||
assert!((0.25 / widen_unit(hinted, font_px, stretch) * on_screen - 0.25).abs() < 1e-12, "{hinted} {stretch}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_area_rendered_to_a_pixel_size_fills_it_and_keeps_its_text_on_the_grid() {
|
||||
let (d, l) = flat_capitals();
|
||||
let page = &l.pages[0];
|
||||
let area = wordcraft_geom::Rect::new(0.0, 0.0, page.w, page.h);
|
||||
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
// A page 1746.155 × 2469.544 pixels at its scale, made 1746 × 2470: a pixel in two thousand off each way.
|
||||
let scale = 1746.155 / page.w;
|
||||
let (w, h) = (1746, (page.h * scale).round() as u32 + 1);
|
||||
let exact = render_area_to(&d, page, area, w, h, &snap);
|
||||
assert_eq!((exact.width, exact.height), (w, h));
|
||||
// One scale gives the next whole pixel up each way: not the size asked for.
|
||||
let up = render_area(&d, page, area, scale, &snap);
|
||||
assert_eq!(up.width, 1747);
|
||||
// The text is as it is at the page's own scale, feet on a whole pixel row: scaled that little differently
|
||||
// across and down, the page is still upright.
|
||||
let foot_is_dark = |img: &Rendered| {
|
||||
let (_, foot) = ink_row_span(img);
|
||||
let w = img.width as usize;
|
||||
img.pixels[foot * w * 4..(foot + 1) * w * 4].as_chunks::<4>().0.iter().map(|p| p[0]).min().unwrap_or(255) < 16
|
||||
};
|
||||
assert!(foot_is_dark(&exact) && foot_is_dark(&up));
|
||||
assert!(is_upright(Affine::scale_non_uniform(2.0, 2.002)) && is_upright(Affine::scale_non_uniform(2.933, 2.9334)));
|
||||
assert!(!is_upright(Affine::scale_non_uniform(2.0, 2.01)));
|
||||
// Hostile sizes and areas: clamped, never a panic.
|
||||
for (area, w, h) in [
|
||||
(wordcraft_geom::Rect::new(0.0, 0.0, 0.0, 0.0), 10, 10),
|
||||
(wordcraft_geom::Rect::new(f32::NAN, f32::INFINITY, f32::NAN, -5.0), 10, 10),
|
||||
(area, 0, 0),
|
||||
(area, u32::MAX, 3),
|
||||
] {
|
||||
let img = render_area_to(&d, page, area, w, h, &snap);
|
||||
assert!(img.width >= 1 && img.height >= 1 && img.pixels.len() == img.width as usize * img.height as usize * 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hinting_sharpens_screen_text_without_making_it_bolder_or_moving_it() {
|
||||
let mut d =
|
||||
@@ -2053,6 +2379,35 @@ fn rules_of_one_width_cover_the_same_whole_pixels_at_every_zoom() {
|
||||
assert!(snap_rule(Affine::scale(2.0), (0.0, 0.0, 9.0, 4.0), 0.5).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_snap_by_the_scale_across_them_on_a_page_scaled_a_little_differently_each_way() {
|
||||
// A page raster made to fill a whole number of pixels is scaled a pixel in a thousand or two
|
||||
// differently across and down. A level rule lies where the scale down the page puts it, and
|
||||
// an upright one where the scale across does.
|
||||
for (kx, ky) in [(2.0, 2.002), (2.002, 2.0), (2.933, 2.9334), (1.3333, 1.3329)] {
|
||||
let view = Affine::new([kx, 0.0, 0.0, ky, 37.3, 12.9]);
|
||||
assert!(is_upright(view));
|
||||
for i in 0..40 {
|
||||
let pos = 10.0 + f64::from(i) * 17.37;
|
||||
let (w_h, (_, oy)) = snap_rule(view, (5.0, pos, 400.0, pos), 0.5).unwrap();
|
||||
let (w_v, (ox, _)) = snap_rule(view, (pos, 5.0, pos, 400.0), 0.5).unwrap();
|
||||
for (w, centre, lies) in [(w_h, (pos + oy) * ky + 12.9, pos * ky + 12.9), (w_v, (pos + ox) * kx + 37.3, pos * kx + 37.3)] {
|
||||
let edge = centre - w / 2.0;
|
||||
assert!((edge - edge.round()).abs() < 1e-9, "scales {kx} {ky}: edge {edge} is off the pixel grid");
|
||||
// Snapped onto the grid from where it lies: never further than its own width and half a pixel.
|
||||
assert!((centre - lies).abs() <= w / 2.0 + 0.5 + 1e-9, "scales {kx} {ky}: moved {} px", centre - lies);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The case from review: a level rule at 250 pt, half a point wide, at 2.0 across and 2.002 down, is a pixel
|
||||
// wide and centred on 500.5 already. It stays there.
|
||||
let view = Affine::scale_non_uniform(2.0, 2.002);
|
||||
let (w, (_, oy)) = snap_rule(view, (5.0, 250.0, 400.0, 250.0), 0.5).unwrap();
|
||||
assert_eq!(w, 1.0);
|
||||
assert!(((250.0 + oy) * 2.002 - 500.5).abs() < 1e-9, "centre {}", (250.0 + oy) * 2.002);
|
||||
assert_eq!((rule_scale(view, true), rule_scale(view, false)), (2.002, 2.0));
|
||||
}
|
||||
|
||||
/// The same three pictures that don't draw as in the PDF test: each stays a grey box, and the page's
|
||||
/// pixels are what they were before strict export existed (#6005).
|
||||
#[test]
|
||||
|
||||
@@ -1302,6 +1302,7 @@ pub(crate) fn works_without_document(id: &str) -> bool {
|
||||
| "tools.customizeRibbon"
|
||||
| "view.darkMode"
|
||||
| "view.paperColor"
|
||||
| "view.textSmoothing"
|
||||
| "view.marks"
|
||||
| "view.ruler"
|
||||
| "view.numeral"
|
||||
|
||||
@@ -60,7 +60,7 @@ impl ThumbSource<ThumbKey> for TemplateThumbs {
|
||||
let Some(page) = layout.pages.first() else { return ThumbRender::Blank };
|
||||
// The longest side of the page is `request.side` pixels; the store never asks for zero.
|
||||
let scale = request.side as f32 / page.w.max(page.h).max(1.0);
|
||||
let image = wordcraft_render::render_page(&session.doc, page, scale, &crate::canvas::screen_render_options());
|
||||
let image = wordcraft_render::render_page(&session.doc, page, scale, &crate::canvas::thumbnail_render_options());
|
||||
let pixels = image.to_straight();
|
||||
ThumbRender::Ready(egui::ColorImage::from_rgba_unmultiplied([image.width as usize, image.height as usize], &pixels))
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ pub(crate) use links::follow_link;
|
||||
use links::{field_link, is_followable_link, is_generated_bookmark_link};
|
||||
pub use navigation::page_to_screen;
|
||||
use navigation::viewed_page;
|
||||
pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options};
|
||||
pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options, thumbnail_render_options};
|
||||
use pages::{page_render_options, shown_layout};
|
||||
use reading::{reading_anchor_page, reading_page_start, web_layout_width};
|
||||
use story::dims_body;
|
||||
@@ -111,6 +111,11 @@ pub struct CanvasState {
|
||||
/// The page asks for the keyboard between this pass and the next ([`CanvasState::focus_page_after_pass`]): always
|
||||
/// (no ids), or only while focus is still on one of the ids.
|
||||
focus_after_pass: Option<Vec<egui::Id>>,
|
||||
/// Where the page view put its pages (page, place in screen points) the last time two passes running put
|
||||
/// them in the same places: the view at rest. Page pictures are made to fill these places exactly
|
||||
/// (`source::WordPages`); while the view moves they stay as they were, so a scroll or a zoom under way makes
|
||||
/// no picture again for a place it is only passing through.
|
||||
pub(crate) settled_pages: Vec<(usize, Rect)>,
|
||||
/// How many page pictures the page view kept resident after the last pass (S-L352).
|
||||
pub(crate) resident_pictures: usize,
|
||||
/// The caret's glide and blink.
|
||||
@@ -421,6 +426,7 @@ impl Default for CanvasState {
|
||||
shown: ShownPages::default(),
|
||||
focus_pending: true,
|
||||
focus_after_pass: None,
|
||||
settled_pages: Vec::new(),
|
||||
resident_pictures: 0,
|
||||
glide: crate::caret_glide::CaretGlide::default(),
|
||||
comments: Default::default(),
|
||||
@@ -751,7 +757,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
|
||||
let columns = Rect::from_min_max(full.min, pos2(full.max.x, (full.max.y - metrics.nav_bar).max(full.min.y)));
|
||||
let footer = Rect::from_min_max(pos2(full.min.x, columns.max.y), full.max);
|
||||
let mut state = std::mem::take(&mut app.canvas.reading);
|
||||
let source = source::WordPages::new(app, layout, false, None);
|
||||
// Read Mode sizes its columns itself: no view scale to rasterise at.
|
||||
let source = source::WordPages::new(app, layout, false, None, None);
|
||||
let out = ReadingView::new(tl!("Document"), &source, &mut state, paper).zoom(zoom).show_at(ui, columns);
|
||||
// The page-turn row sits at the bottom right, as in v0.19.1 (the far end, so the bottom left in a right-to-left UI),
|
||||
// the page view's side margin in from the edge.
|
||||
@@ -840,7 +847,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
let options =
|
||||
LayoutOptions { markup: f64::from(markup_width(app)), min_columns: if app.session.view.multi_page { 2 } else { 1 }, ..LayoutOptions::WORD };
|
||||
let paper = DataColor::new(paper_color(app));
|
||||
let source = source::WordPages::new(app, layout, dim_body, hidden);
|
||||
let source = source::WordPages::new(app, layout, dim_body, hidden, Some(scale as f32));
|
||||
// The describer owns its snapshot, as the source does, so the page view can hold it while the body edits the app.
|
||||
let described = preview_sel(app).unwrap_or(app.session.sel_ends()).clone();
|
||||
let describer = crate::a11y::DocumentDescriber::new(source.doc(), layout.clone(), (described.anchor.clone(), described.focus.clone()));
|
||||
@@ -1033,6 +1040,14 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
// A window's page has the keyboard from its first pass (production's `want_focus` started on), so typing lands
|
||||
// without a click; a modal dialog keeps the keyboard until it closes.
|
||||
let view_rect = body_view.map_or(body_rect, |v| v.rect);
|
||||
// The same places two passes running: the view is at rest, and these are the places pictures are made for.
|
||||
let placed = |pages: &[PlacedPage]| pages.iter().map(|p| (p.page, p.rect)).collect::<Vec<_>>();
|
||||
let now = placed(&out.pages);
|
||||
if now == placed(&app.canvas.shown.pages) && now != app.canvas.settled_pages {
|
||||
app.canvas.settled_pages = now;
|
||||
// The pictures of the places just settled are made on the next pass.
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
app.canvas.shown =
|
||||
ShownPages { rect: body_rect, pages: out.pages.clone(), laid: laid_rects(&out), view: view_rect, canvas: Some(out.canvas.response.id) };
|
||||
if app.canvas.focus_pending && !app.modal_open() {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use craft::ui::primitives::textures::MAX_TEXTURE;
|
||||
|
||||
use super::{DocLayout, Hash, Hasher, Page, Placed, Pos, Rect, WordApp, json};
|
||||
|
||||
/// Streams `Debug` formatting directly into a [`Hasher`] without intermediate `String` allocations.
|
||||
@@ -20,6 +22,9 @@ impl std::fmt::Write for HashFmt<'_> {
|
||||
// revision that the pages' pictures key on directly.
|
||||
pub(super) fn view_key(app: &WordApp, dim_body: bool, hidden: Option<&Pos>) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
// A page drawn under the system's earlier text settings, or the user's earlier smoothing choice, must not pass
|
||||
// for one drawn under these.
|
||||
(crate::screen_text::current().key(), app.session.prefs.text_smoothing).hash(&mut h);
|
||||
let v = &app.session.view;
|
||||
(v.marks, app.session.prefs.marks, v.show_markup, v.dark_mode, wordcraft_render::DARK_PAPER, v.hide_ink, v.draw.replay).hash(&mut h);
|
||||
(v.read_mode, v.read_page_color, app.session.prefs.paper_color).hash(&mut h);
|
||||
@@ -180,6 +185,9 @@ pub(crate) fn dark_page(app: &WordApp) -> bool {
|
||||
/// Render options for this view's page rasters: marks, markup, dark page, header/body dimming.
|
||||
pub(super) fn page_render_options(app: &WordApp, dim_body: bool) -> wordcraft_render::RenderOptions {
|
||||
let mut opts = screen_render_options();
|
||||
// Pages, and only pages, follow the system's own text settings once they are known ([`crate::screen_text`]);
|
||||
// `view_key` has them, so a change redraws the pages.
|
||||
crate::screen_text::current().apply(&mut opts);
|
||||
opts.display.marks = app.session.view.marks;
|
||||
opts.display.always = app.session.prefs.marks;
|
||||
opts.display.placeholders = true;
|
||||
@@ -208,15 +216,107 @@ pub(super) fn page_render_options(app: &WordApp, dim_body: bool) -> wordcraft_re
|
||||
opts
|
||||
}
|
||||
|
||||
/// Render options for page rasters shown on screen, so a page looks as text does in the
|
||||
/// platform's other apps (exports never change): on macOS, text is darkened the way the system
|
||||
/// draws it; on Linux and the BSDs it is hinted lightly, as FreeType's `hintslight` draws it
|
||||
/// there (not darkened: hinted text already has FreeType's weight, and darkening made it
|
||||
/// look semi-bold).
|
||||
pub(crate) fn screen_render_options() -> wordcraft_render::RenderOptions {
|
||||
wordcraft_render::RenderOptions {
|
||||
text_darkening: cfg!(target_os = "macos"),
|
||||
hinting: cfg!(all(unix, not(target_os = "macos"))),
|
||||
..Default::default()
|
||||
/// Subpixel (LCD) text for the page rasters of a screen with `ppp` device pixels per point, as File › Options ›
|
||||
/// General › Screen text smoothing says. "Use system setting" draws it where the system asks for it
|
||||
/// ([`crate::screen_text`]) and the screen is below two device pixels per point: on a denser screen the stripes are
|
||||
/// too fine to gain from, and a page has four times the pixels to rasterise three times. "Subpixel (LCD)" draws it
|
||||
/// on any screen, in the system's stripe order, RGB when it names none (macOS never does).
|
||||
pub(super) fn lcd_for(
|
||||
choice: wordcraft_engine::cmd::view::TextSmoothing,
|
||||
asked: Option<crate::screen_text::SubpixelOrder>,
|
||||
stripes: Option<crate::screen_text::SubpixelOrder>,
|
||||
ppp: f32,
|
||||
) -> Option<wordcraft_render::LcdOrder> {
|
||||
use crate::screen_text::SubpixelOrder;
|
||||
use wordcraft_engine::cmd::view::TextSmoothing;
|
||||
use wordcraft_render::LcdOrder;
|
||||
let order = |stripes: SubpixelOrder| match stripes {
|
||||
SubpixelOrder::Rgb => LcdOrder::Rgb,
|
||||
SubpixelOrder::Bgr => LcdOrder::Bgr,
|
||||
};
|
||||
match choice {
|
||||
TextSmoothing::Grayscale => None,
|
||||
// The user's own choice, in the order of their screen even where the system has smoothing off (a BGR panel
|
||||
// with ClearType off must not get RGB edges).
|
||||
TextSmoothing::Subpixel => Some(asked.or(stripes).map(order).unwrap_or(LcdOrder::Rgb)),
|
||||
// Written so a density that isn't a number is greyscale too.
|
||||
TextSmoothing::System => asked.map(order).filter(|_| ppp < 2.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The scale (pixels per document point) to rasterise a page picture at, and whether that is the screen's own.
|
||||
///
|
||||
/// The page view asks for a picture by its longest side in pixels, `side`, rounded up to a multiple of `step`, and
|
||||
/// scales what it gets to the page's place on screen. Rasterised at `side`, a page is up to `step` pixels larger
|
||||
/// than it shows and every glyph is resampled on the way to the screen, which undoes baselines put on whole pixels
|
||||
/// and makes subpixel text wrong (each colour's edge off its stripe). `native` is the view's own scale, device
|
||||
/// pixels per document point, when it is known: where it accounts for the side asked for (the page's `longest`
|
||||
/// side, in points, at that scale rounds up to `side`), the picture is rasterised at exactly that scale, one raster
|
||||
/// pixel per device pixel. Otherwise (another view's request, a fit zoom not settled yet, a part of a page shown
|
||||
/// reduced) it is rasterised at the side asked for, as before, and is not the screen's own.
|
||||
pub(super) fn raster_scale(side: u32, step: u32, longest: f32, native: Option<f32>) -> (f32, bool) {
|
||||
let largest = MAX_TEXTURE as f32;
|
||||
// `side / longest * longest` can come out a hair over `side`, which rounds up to a pixel too many for a texture.
|
||||
let mut asked = side as f32 / longest;
|
||||
if side <= MAX_TEXTURE && (longest * asked).ceil() > largest {
|
||||
asked = asked.next_down().next_down();
|
||||
}
|
||||
let fits = |scale: f32| {
|
||||
let pixels = longest * scale;
|
||||
scale.is_finite() && scale > 0.0 && pixels.is_finite() && pixels <= side as f32 + 0.5 && pixels > side as f32 - step as f32 - 0.5
|
||||
// A pixel over the largest texture and the store halves the whole picture.
|
||||
&& pixels.ceil() <= largest
|
||||
};
|
||||
match native.filter(|scale| longest.is_finite() && longest > 0.0 && step > 0 && fits(*scale)) {
|
||||
Some(scale) => (scale, true),
|
||||
None => (asked, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The size in device pixels of the place on screen a page's picture is drawn in, when a picture of about
|
||||
/// `expected` pixels (its size at the view's scale) is that place's own.
|
||||
///
|
||||
/// The page view draws a picture as its painter does every picture: the place (`page`, in screen points, or the
|
||||
/// part `region` of it, in fractions) is rounded to whole pixels, and the picture is fitted inside it by its own
|
||||
/// proportions. A picture of exactly the rounded place's size is drawn one pixel for one. Any other is scaled:
|
||||
/// rasterised a whole pixel up each way, as a single scale gives, a 2016 × 2851 pixel place gets a 2017 × 2852
|
||||
/// picture squeezed by a twentieth of a percent, and the text slides off the pixel grid and back down the page.
|
||||
/// The rounded size depends on where the place starts, so it comes from where the view last put the page, not
|
||||
/// from the page's size. `None` where the place is not within a pixel and a half of `expected` each way: a
|
||||
/// place left over from another zoom, or numbers that aren't.
|
||||
pub(super) fn picture_pixels(page: egui::Rect, region: Option<egui::Rect>, ppp: f32, expected: (f32, f32)) -> Option<(u32, u32)> {
|
||||
let place = match region {
|
||||
Some(part) => {
|
||||
let at = |f: egui::Pos2| egui::pos2(page.min.x + f.x * page.width(), page.min.y + f.y * page.height());
|
||||
egui::Rect::from_min_max(at(part.min), at(part.max))
|
||||
}
|
||||
None => page,
|
||||
};
|
||||
let side = |lo: f32, hi: f32, expected: f32| {
|
||||
let pixels = (hi * ppp).round() - (lo * ppp).round();
|
||||
(pixels.is_finite() && expected.is_finite() && pixels >= 1.0 && (pixels - expected).abs() <= 1.5).then_some(pixels as u32)
|
||||
};
|
||||
Some((side(place.min.x, place.max.x, expected.0)?, side(place.min.y, place.max.y, expected.1)?))
|
||||
}
|
||||
|
||||
/// Render options for rasters shown on screen other than the pages themselves (style and font previews, a dragged
|
||||
/// object), so their text looks as it does in the platform's other apps (exports never change): on macOS it is
|
||||
/// darkened the way the system draws it; on Linux and the BSDs it is hinted lightly, as FreeType's `hintslight`
|
||||
/// draws it there (not darkened: hinted text already has FreeType's weight, and darkening made it look semi-bold).
|
||||
/// Baselines sit on whole device pixels (hinting does that; unhinted text is moved there). These are fixed per
|
||||
/// platform: such rasters are cached without the system's text settings in their keys, so they must not follow
|
||||
/// them. Pages do ([`page_render_options`]).
|
||||
pub(crate) fn screen_render_options() -> wordcraft_render::RenderOptions {
|
||||
let mut opts = wordcraft_render::RenderOptions { baseline_snap: true, ..Default::default() };
|
||||
crate::screen_text::ScreenText::PLATFORM.apply(&mut opts);
|
||||
opts
|
||||
}
|
||||
|
||||
/// Render options for the template thumbnails of File › New: the platform's text, as [`screen_render_options`],
|
||||
/// without the baseline snapping. A thumbnail is a page shrunk to a tile, drawn as it was before pages were
|
||||
/// sharpened.
|
||||
pub(crate) fn thumbnail_render_options() -> wordcraft_render::RenderOptions {
|
||||
let mut opts = wordcraft_render::RenderOptions::default();
|
||||
crate::screen_text::ScreenText::PLATFORM.apply(&mut opts);
|
||||
opts
|
||||
}
|
||||
|
||||
@@ -8,12 +8,12 @@ use std::sync::Arc;
|
||||
|
||||
use craft::behavior::kurbo::Size;
|
||||
use craft::pages::ui::PageSource;
|
||||
use craft::ui::primitives::textures::{LoadedPicture, Revision, ThumbRender, ThumbRequest, ThumbSource};
|
||||
use craft::ui::primitives::textures::{LoadedPicture, MAX_TEXTURE, Revision, ThumbRender, ThumbRequest, ThumbSource};
|
||||
use wordcraft_doc::{Document, Pos};
|
||||
use wordcraft_layout::DocLayout;
|
||||
|
||||
use super::WordApp;
|
||||
use super::pages::{PageKeys, page_render_options, page_shows, view_key};
|
||||
use super::pages::{PageKeys, lcd_for, page_render_options, page_shows, picture_pixels, raster_scale, view_key};
|
||||
|
||||
/// A page dimension (points) safe to lay out: finite, at least 1 pt, at most `cap`.
|
||||
fn dim(v: f32, cap: f32) -> f64 {
|
||||
@@ -30,13 +30,38 @@ pub(super) struct WordPages {
|
||||
options: wordcraft_render::RenderOptions,
|
||||
/// The page a drag took an object off, and the object: rendered without it.
|
||||
hidden: Option<(usize, Pos)>,
|
||||
/// Screen points per document point in the view these pages show in, when it is one whose pages are drawn at
|
||||
/// that scale (the page view); `None` where the view sizes its pages itself (Read Mode's columns). With the
|
||||
/// screen's density it gives the scale at which a picture is the screen's own ([`raster_scale`]).
|
||||
view_scale: Option<f32>,
|
||||
/// Where the page view put each page (page, its place in screen points) the last time the view was at rest;
|
||||
/// empty for a view that sizes its pages itself. A picture is made exactly as many pixels each way as its
|
||||
/// place is ([`picture_pixels`]).
|
||||
placed: Vec<(usize, egui::Rect)>,
|
||||
/// File › Options › General › Screen text smoothing, and what the system says of the screen's text.
|
||||
smoothing: wordcraft_engine::cmd::view::TextSmoothing,
|
||||
screen_text: crate::screen_text::ScreenText,
|
||||
}
|
||||
|
||||
/// The page view asks for pictures whose longest side is a multiple of this many pixels
|
||||
/// (`ThumbRequest::side`).
|
||||
const SIDE_STEP: u32 = 16;
|
||||
|
||||
impl WordPages {
|
||||
/// The source of `layout` for this pass. The page fingerprints move out of the app for the pass; give them back
|
||||
/// with [`WordPages::into_keys`].
|
||||
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>) -> Self {
|
||||
let view = view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p));
|
||||
/// `view_scale` is the view's screen points per document point where its pages are drawn at exactly that scale,
|
||||
/// so that their pictures can be rasterised one pixel per device pixel.
|
||||
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>, view_scale: Option<f32>) -> Self {
|
||||
let view_scale = view_scale.filter(|scale| scale.is_finite() && *scale > 0.0);
|
||||
let placed = if view_scale.is_some() { app.canvas.settled_pages.clone() } else { Vec::new() };
|
||||
let view = {
|
||||
// A picture rasterised for another zoom is not this zoom's, even where the side asked for is the same.
|
||||
let mut h = DefaultHasher::new();
|
||||
(view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p)), view_scale.map(f32::to_bits)).hash(&mut h);
|
||||
h.finish()
|
||||
};
|
||||
let (smoothing, screen_text) = (app.session.prefs.text_smoothing, crate::screen_text::current());
|
||||
let options = page_render_options(app, dim_body);
|
||||
let doc = if let Some((_, preview, _, _)) = &app.canvas.table_preview_layout {
|
||||
Arc::new(preview.clone())
|
||||
@@ -51,7 +76,8 @@ impl WordPages {
|
||||
}
|
||||
}
|
||||
};
|
||||
WordPages { doc, layout: layout.clone(), keys: RefCell::new(std::mem::take(&mut app.canvas.page_keys)), view, options, hidden }
|
||||
let keys = RefCell::new(std::mem::take(&mut app.canvas.page_keys));
|
||||
WordPages { doc, layout: layout.clone(), keys, view, options, hidden, view_scale, placed, smoothing, screen_text }
|
||||
}
|
||||
|
||||
/// The pass's document snapshot, shared with the accessibility describer so the pass holds one copy.
|
||||
@@ -65,16 +91,26 @@ impl WordPages {
|
||||
}
|
||||
}
|
||||
|
||||
impl ThumbSource<usize> for WordPages {
|
||||
fn revision(&self, page: &usize, _request: &ThumbRequest) -> Revision {
|
||||
let mut h = DefaultHasher::new();
|
||||
page_shows(&mut self.keys.borrow_mut(), &self.layout, *page, self.view).hash(&mut h);
|
||||
Revision::new(h.finish())
|
||||
}
|
||||
/// What a request for a page's picture is rasterised as.
|
||||
pub(super) struct RasterPlan {
|
||||
/// The whole page, or only `area` of it.
|
||||
pub(super) whole: bool,
|
||||
/// The part of the page to rasterise, in document points.
|
||||
pub(super) area: wordcraft_geom::Rect,
|
||||
/// Pixels per document point.
|
||||
pub(super) scale: f32,
|
||||
/// The picture's size in pixels where it is made to fill its place on screen exactly; `None` for one made at
|
||||
/// `scale`, a whole pixel up each way.
|
||||
pub(super) pixels: Option<(u32, u32)>,
|
||||
pub(super) options: wordcraft_render::RenderOptions,
|
||||
}
|
||||
|
||||
fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender {
|
||||
let index = *page;
|
||||
let Some(p) = self.layout.pages.get(index) else { return ThumbRender::Blank };
|
||||
impl WordPages {
|
||||
/// What of page `index` a picture for `request` shows and how large it is made: whether it is the whole page,
|
||||
/// the area in document points, the pixels per point, whether that is the screen's own scale, and the picture's
|
||||
/// size in pixels where it is made to fill its place exactly. `None` for a page the layout doesn't have.
|
||||
fn geometry(&self, index: usize, request: &ThumbRequest) -> Option<(bool, wordcraft_geom::Rect, f32, bool, Option<(u32, u32)>)> {
|
||||
let p = self.layout.pages.get(index)?;
|
||||
let (pw, ph) = (dim(p.w, 1e5) as f32, dim(p.h, 1e6) as f32);
|
||||
let whole = request.region.is_none();
|
||||
let (x0, y0, x1, y1) = match request.region {
|
||||
@@ -84,14 +120,51 @@ impl ThumbSource<usize> for WordPages {
|
||||
let area = wordcraft_geom::Rect::new(x0 * pw, y0 * ph, ((x1 - x0) * pw).max(0.01), ((y1 - y0) * ph).max(0.01));
|
||||
let longest = area.w.max(area.h);
|
||||
let cap = wordcraft_render::MAX_SIDE as f32 / longest;
|
||||
let scale = request.side as f32 / longest;
|
||||
// At the screen's own scale where the view's zoom accounts for the side asked for, so no glyph is resampled
|
||||
// on its way to the screen; else at the side asked for.
|
||||
let (scale, own) = raster_scale(request.side, SIDE_STEP, longest, self.view_scale.map(|s| s * request.pixels_per_point));
|
||||
let own = own && scale <= cap;
|
||||
let scale = if scale.is_finite() { scale.clamp(0.01, cap.max(0.01)) } else { 1.0 };
|
||||
let (doc, layout) = (Arc::clone(&self.doc), Arc::clone(&self.layout));
|
||||
// Exactly as many pixels each way as the picture's place on screen has, where that is known and is this
|
||||
// scale's: a pixel more and the page view scales the picture into its place.
|
||||
let place = self.placed.iter().find(|(page, _)| *page == index).map(|(_, rect)| *rect);
|
||||
let pixels = place
|
||||
.filter(|_| own)
|
||||
.and_then(|place| picture_pixels(place, request.region, request.pixels_per_point, (area.w * scale, area.h * scale)))
|
||||
// A place can round to a pixel more than the largest texture, and a larger picture is halved.
|
||||
.filter(|(w, h)| *w.max(h) <= MAX_TEXTURE);
|
||||
Some((whole, area, scale, own, pixels))
|
||||
}
|
||||
|
||||
/// How page `index` is rasterised for `request`; `None` for a page the layout doesn't have.
|
||||
pub(super) fn plan(&self, index: usize, request: &ThumbRequest) -> Option<RasterPlan> {
|
||||
let (whole, area, scale, own, pixels) = self.geometry(index, request)?;
|
||||
let mut options = self.options.clone();
|
||||
options.display.hide_object = self.hidden.as_ref().filter(|(hidden, _)| *hidden == index).map(|(_, pos)| pos.clone());
|
||||
// Subpixel text only on a picture that is the screen's own: scaled, each colour's edge would miss its stripe.
|
||||
options.lcd = lcd_for(self.smoothing, self.screen_text.subpixel, self.screen_text.stripes, request.pixels_per_point).filter(|_| own);
|
||||
Some(RasterPlan { whole, area, scale, pixels, options })
|
||||
}
|
||||
}
|
||||
|
||||
impl ThumbSource<usize> for WordPages {
|
||||
fn revision(&self, page: &usize, request: &ThumbRequest) -> Revision {
|
||||
let mut h = DefaultHasher::new();
|
||||
page_shows(&mut self.keys.borrow_mut(), &self.layout, *page, self.view).hash(&mut h);
|
||||
// A picture made for another place's pixel size is not this place's.
|
||||
self.geometry(*page, request).and_then(|(.., pixels)| pixels).hash(&mut h);
|
||||
Revision::new(h.finish())
|
||||
}
|
||||
|
||||
fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender {
|
||||
let index = *page;
|
||||
let Some(RasterPlan { whole, area, scale, pixels, options }) = self.plan(index, request) else { return ThumbRender::Blank };
|
||||
let (doc, layout) = (Arc::clone(&self.doc), Arc::clone(&self.layout));
|
||||
ThumbRender::Later(Box::new(move |_cancel| {
|
||||
let Some(page) = layout.pages.get(index) else { return Ok(LoadedPicture::Blank) };
|
||||
let img = if whole {
|
||||
let img = if let Some((w, h)) = pixels {
|
||||
wordcraft_render::render_area_to(&doc, page, area, w, h, &options)
|
||||
} else if whole {
|
||||
wordcraft_render::render_page(&doc, page, scale, &options)
|
||||
} else {
|
||||
wordcraft_render::render_area(&doc, page, area, scale, &options)
|
||||
|
||||
@@ -2291,6 +2291,209 @@ fn the_view_key_changes_when_a_drag_takes_an_object_off_the_page() {
|
||||
assert_eq!(hidden, view_key(&app, false, Some(&object)), "the same drag keeps the key: no re-render every frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_pages_follow_the_systems_text_settings() {
|
||||
use crate::screen_text::ScreenText;
|
||||
// Previews and thumbnails are cached without the system's settings in their keys: they are
|
||||
// drawn the platform's fixed way. Thumbnails are not baseline-snapped either.
|
||||
let (screen, thumb) = (screen_render_options(), thumbnail_render_options());
|
||||
for opts in [&screen, &thumb] {
|
||||
assert_eq!((opts.text_darkening, opts.hinting, opts.lcd), (ScreenText::PLATFORM.darkening, ScreenText::PLATFORM.hinting, None));
|
||||
}
|
||||
assert!(screen.baseline_snap && !thumb.baseline_snap);
|
||||
// A page takes the same until the app has asked the system (tests never do).
|
||||
let a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let page = page_render_options(&a, false);
|
||||
assert_eq!((page.text_darkening, page.hinting, page.baseline_snap), (screen.text_darkening, screen.hinting, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subpixel_text_follows_the_choice_the_system_and_the_screen() {
|
||||
use super::pages::lcd_for;
|
||||
use crate::screen_text::SubpixelOrder::{Bgr, Rgb};
|
||||
use wordcraft_engine::cmd::view::TextSmoothing::{Grayscale, Subpixel, System};
|
||||
use wordcraft_render::LcdOrder;
|
||||
// Use system setting: where the system asks for it, in its order, below 2x only.
|
||||
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), 1.0), Some(LcdOrder::Rgb));
|
||||
assert_eq!(lcd_for(System, Some(Bgr), Some(Bgr), 1.5), Some(LcdOrder::Bgr));
|
||||
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), 2.0), None, "a high-density screen");
|
||||
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), f32::NAN), None);
|
||||
assert_eq!(lcd_for(System, None, None, 1.0), None, "the system asks for greyscale, or says nothing");
|
||||
assert_eq!(lcd_for(System, None, Some(Bgr), 1.0), None, "a known stripe order is not a request");
|
||||
// The user's own choice wins on any screen; RGB when the system names no order.
|
||||
assert_eq!(lcd_for(Subpixel, None, None, 2.0), Some(LcdOrder::Rgb));
|
||||
assert_eq!(lcd_for(Subpixel, Some(Bgr), Some(Bgr), 3.0), Some(LcdOrder::Bgr));
|
||||
// A BGR panel whose system has smoothing off (ClearType off on Windows, greyscale on a
|
||||
// Linux desktop) still gets BGR edges, not RGB ones.
|
||||
assert_eq!(lcd_for(Subpixel, None, Some(Bgr), 1.0), Some(LcdOrder::Bgr));
|
||||
let cleartype_off = crate::screen_text::ScreenText::from_windows(Some("0"), Some(2), Some(0));
|
||||
assert_eq!(lcd_for(Subpixel, cleartype_off.subpixel, cleartype_off.stripes, 1.0), Some(LcdOrder::Bgr));
|
||||
assert_eq!(lcd_for(System, cleartype_off.subpixel, cleartype_off.stripes, 1.0), None);
|
||||
for (asked, stripes) in [(None, None), (Some(Rgb), Some(Rgb)), (None, Some(Bgr))] {
|
||||
assert_eq!(lcd_for(Grayscale, asked, stripes, 1.0), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_picture_is_rasterised_at_the_screens_own_scale_where_the_view_accounts_for_it() {
|
||||
use super::pages::raster_scale;
|
||||
// An A4 page (841.89 pt) at 100 % on a 2x screen: 2245.04 device pixels, asked for as 2256 (the next multiple
|
||||
// of 16). At 2256 every glyph would be shrunk by half a percent on its way to the screen.
|
||||
let longest = 841.89_f32;
|
||||
let native = 96.0 / 72.0 * 2.0;
|
||||
assert_eq!(raster_scale(2256, 16, longest, Some(native)), (native, true));
|
||||
assert_eq!(raster_scale(2256, 16, longest, None), (2256.0 / longest, false), "a view with no scale of its own");
|
||||
// US Letter (792 pt) at the same zoom is 2112 pixels, a multiple of 16: the same either way.
|
||||
let (scale, own) = raster_scale(2112, 16, 792.0, Some(native));
|
||||
assert!(own && (scale - 2112.0 / 792.0).abs() < 1e-6);
|
||||
// A side the view's scale doesn't account for: another zoom's request, a side lowered to the largest texture,
|
||||
// a part of the page shown reduced. Rasterised as asked for, and not the screen's own.
|
||||
for side in [2240, 2272, 1024, 16] {
|
||||
assert_eq!(raster_scale(side, 16, longest, Some(native)), (side as f32 / longest, false), "{side}");
|
||||
}
|
||||
// Numbers that aren't: as asked for.
|
||||
for (longest, native, step) in
|
||||
[(longest, f32::NAN, 16), (longest, f32::INFINITY, 16), (longest, -1.0, 16), (longest, 0.0, 16), (longest, native, 0)]
|
||||
{
|
||||
assert!(!raster_scale(2256, step, longest, Some(native)).1, "{longest} {native} {step}");
|
||||
}
|
||||
assert!(!raster_scale(2256, 16, f32::NAN, Some(native)).1 && !raster_scale(2256, 16, 0.0, Some(native)).1);
|
||||
}
|
||||
|
||||
/// A page a fraction of a pixel longer than the largest texture is made no larger than it: a picture one pixel over
|
||||
/// is halved on upload, and the page stays blurry at rest.
|
||||
#[test]
|
||||
fn a_page_picture_never_outgrows_the_largest_texture() {
|
||||
use super::source::WordPages;
|
||||
use craft::ui::primitives::textures::{MAX_TEXTURE, ThumbRequest};
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let layout = a.session.layout();
|
||||
let (w, h) = (layout.pages[0].w, layout.pages[0].h);
|
||||
let longest = w.max(h);
|
||||
for over in [-0.6, -0.1, 0.0, 0.1, 0.3, 0.5] {
|
||||
for y in [0.0, 0.3, 0.49, 0.6] {
|
||||
let scale = (MAX_TEXTURE as f32 + over) / longest;
|
||||
a.canvas.settled_pages = vec![(0, Rect::from_min_size(egui::pos2(10.0, y), egui::vec2(w * scale, h * scale)))];
|
||||
let pages = WordPages::new(&mut a, &layout, false, None, Some(scale));
|
||||
let plan = pages.plan(0, &ThumbRequest::for_cell(longest * scale, 1.0)).unwrap();
|
||||
let side = plan.pixels.map_or((longest * plan.scale).ceil() as u32, |(w, h)| w.max(h));
|
||||
assert!(side <= MAX_TEXTURE, "{over} at {y}: {side}");
|
||||
assert!(side + 2 >= MAX_TEXTURE, "not reduced either: {over} at {y}: {side}");
|
||||
if over < -0.5 {
|
||||
assert!(plan.pixels.is_some(), "a page below the limit keeps its own pixels: {over} at {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_picture_is_made_as_many_pixels_as_its_place_on_screen() {
|
||||
use super::pages::picture_pixels;
|
||||
use egui::{pos2, vec2};
|
||||
// An A4 page at 110 % on a 2x screen, centred in a window: 1746.155 × 2469.544 pixels starting at 642.923.
|
||||
// Its place rounds to 643..2389 across and 356..2826 down.
|
||||
let page = Rect::from_min_size(pos2(321.4615, 178.0), vec2(873.0775, 1234.772));
|
||||
let expected = (1746.155, 2469.544);
|
||||
assert_eq!(picture_pixels(page, None, 2.0, expected), Some((1746, 2470)));
|
||||
// The same page half a pixel further right ends on the next pixel and starts on the same one: 1747 across.
|
||||
assert_eq!(picture_pixels(page.translate(vec2(0.25, 0.0)), None, 2.0, expected), Some((1747, 2470)));
|
||||
// The upper half of it, as the page view asks for a part: the part's own place, rounded the same way.
|
||||
let half = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 0.5));
|
||||
assert_eq!(picture_pixels(page, Some(half), 2.0, (1746.155, 1234.772)), Some((1746, 1235)));
|
||||
// A place left from another zoom, or a part shown reduced, is not this picture's: no size.
|
||||
assert_eq!(picture_pixels(page, None, 2.0, (1587.4, 2245.0)), None);
|
||||
assert_eq!(picture_pixels(page, Some(half), 2.0, (873.0, 617.0)), None);
|
||||
// Numbers that aren't.
|
||||
for (page, ppp, expected) in [
|
||||
(Rect::from_min_size(pos2(f32::NAN, 0.0), vec2(800.0, 1100.0)), 2.0, expected),
|
||||
(Rect::from_min_size(pos2(0.0, 0.0), vec2(f32::INFINITY, 1100.0)), 2.0, expected),
|
||||
(page, f32::NAN, expected),
|
||||
(page, 0.0, expected),
|
||||
(page, 2.0, (f32::NAN, 2469.5)),
|
||||
(Rect::NOTHING, 2.0, expected),
|
||||
] {
|
||||
assert_eq!(picture_pixels(page, None, ppp, expected), None, "{page:?} {ppp} {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_pictures_fill_the_place_the_view_last_rested_at() {
|
||||
use super::source::WordPages;
|
||||
use craft::ui::primitives::textures::{ThumbRequest, ThumbSource};
|
||||
use egui::{pos2, vec2};
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let layout = a.session.layout();
|
||||
let (pw, ph) = (layout.pages[0].w, layout.pages[0].h);
|
||||
let view_scale = 96.0 / 72.0 * 1.1;
|
||||
let request = ThumbRequest::for_cell(pw.max(ph) * view_scale, 2.0);
|
||||
// Before the view has rested anywhere: one scale, a whole pixel up each way.
|
||||
let fresh = WordPages::new(&mut a, &layout, false, None, Some(view_scale));
|
||||
let plan = fresh.plan(0, &request).unwrap();
|
||||
assert_eq!((plan.pixels, plan.scale), (None, view_scale * 2.0));
|
||||
let fresh_revision = fresh.revision(&0, &request);
|
||||
a.canvas.page_keys = fresh.into_keys();
|
||||
// At rest, a third of a pixel into a pixel: the picture is its place's size, and another picture than before.
|
||||
let place = Rect::from_min_size(pos2(321.4615, 178.0), vec2(pw * view_scale, ph * view_scale));
|
||||
a.canvas.settled_pages = vec![(0, place)];
|
||||
let rested = WordPages::new(&mut a, &layout, false, None, Some(view_scale));
|
||||
let plan = rested.plan(0, &request).unwrap();
|
||||
let (w, h) = plan.pixels.expect("a place to fill");
|
||||
assert_eq!(w as f32, (place.max.x * 2.0).round() - (place.min.x * 2.0).round());
|
||||
assert_eq!(h as f32, (place.max.y * 2.0).round() - (place.min.y * 2.0).round());
|
||||
assert_ne!(rested.revision(&0, &request), fresh_revision);
|
||||
assert!(rested.plan(1, &request).is_none_or(|plan| plan.pixels.is_none()), "a page with no place");
|
||||
a.canvas.page_keys = rested.into_keys();
|
||||
// A place from another zoom is not this zoom's; Read Mode's columns use none.
|
||||
let zoomed = WordPages::new(&mut a, &layout, false, None, Some(view_scale * 1.3));
|
||||
assert_eq!(zoomed.plan(0, &ThumbRequest::for_cell(pw.max(ph) * view_scale * 1.3, 2.0)).unwrap().pixels, None);
|
||||
a.canvas.page_keys = zoomed.into_keys();
|
||||
let reading = WordPages::new(&mut a, &layout, false, None, None);
|
||||
assert_eq!(reading.plan(0, &request).unwrap().pixels, None);
|
||||
a.canvas.page_keys = reading.into_keys();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_pictures_take_subpixel_text_only_at_the_screens_own_scale() {
|
||||
use super::source::WordPages;
|
||||
use craft::ui::primitives::textures::{ThumbRequest, ThumbSource};
|
||||
use wordcraft_render::LcdOrder;
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let layout = a.session.layout();
|
||||
let longest = layout.pages[0].w.max(layout.pages[0].h);
|
||||
let view_scale = 96.0 / 72.0 * 1.1;
|
||||
let request = |ppp: f32| ThumbRequest::for_cell(longest * view_scale, ppp);
|
||||
let pages = |a: &mut WordApp, scale: Option<f32>| WordPages::new(a, &layout, false, None, scale);
|
||||
// Greyscale until chosen (tests never ask the system), at the screen's own scale.
|
||||
let grey = pages(&mut a, Some(view_scale));
|
||||
let plan = grey.plan(0, &request(2.0)).unwrap();
|
||||
assert_eq!((plan.scale, plan.options.lcd), (view_scale * 2.0, None));
|
||||
assert!(plan.options.baseline_snap);
|
||||
let grey_revision = grey.revision(&0, &request(2.0));
|
||||
a.canvas.page_keys = grey.into_keys();
|
||||
// The user's choice, a command: subpixel text on the picture that is the screen's own...
|
||||
a.run("view.textSmoothing", json!({"value": "subpixel"})).unwrap();
|
||||
let sub = pages(&mut a, Some(view_scale));
|
||||
assert_eq!(sub.plan(0, &request(2.0)).unwrap().options.lcd, Some(LcdOrder::Rgb));
|
||||
assert_eq!(sub.plan(0, &request(1.0)).unwrap().options.lcd, Some(LcdOrder::Rgb));
|
||||
assert_ne!(sub.revision(&0, &request(2.0)), grey_revision, "a page drawn the other way is another picture");
|
||||
let sub_revision = sub.revision(&0, &request(2.0));
|
||||
// ...and not on one that will be scaled: a request the view's zoom doesn't account for, a part shown reduced.
|
||||
let other = ThumbRequest::for_cell(longest * view_scale * 1.3, 2.0);
|
||||
let plan = sub.plan(0, &other).unwrap();
|
||||
assert_eq!((plan.scale, plan.options.lcd), (other.side as f32 / longest, None));
|
||||
a.canvas.page_keys = sub.into_keys();
|
||||
// Read Mode's columns size their pages themselves: as asked for, greyscale.
|
||||
let reading = pages(&mut a, None);
|
||||
let plan = reading.plan(0, &request(2.0)).unwrap();
|
||||
assert_eq!((plan.scale, plan.options.lcd), (request(2.0).side as f32 / longest, None));
|
||||
a.canvas.page_keys = reading.into_keys();
|
||||
// Another zoom is another picture, even where the side asked for is the same.
|
||||
let nudged = pages(&mut a, Some(view_scale * 1.0005));
|
||||
assert_eq!(ThumbRequest::for_cell(longest * view_scale * 1.0005, 2.0).side, request(2.0).side);
|
||||
assert_ne!(nudged.revision(&0, &request(2.0)), sub_revision);
|
||||
assert!(nudged.plan(99, &request(2.0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_paper_color_changes_raster_and_cache_without_changing_export_paper() {
|
||||
use wordcraft_doc::props::Rgb;
|
||||
@@ -2752,18 +2955,18 @@ fn the_caret_blinks_only_while_the_window_is_active() {
|
||||
fn word_pages_reuses_doc_snapshot_across_unchanged_frames_and_invalidates_on_edit() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("hello")), Default::default());
|
||||
let layout = app.session.layout();
|
||||
let first = super::source::WordPages::new(&mut app, &layout, false, None);
|
||||
let first = super::source::WordPages::new(&mut app, &layout, false, None, None);
|
||||
let doc1 = first.doc();
|
||||
app.canvas.page_keys = first.into_keys();
|
||||
|
||||
let second = super::source::WordPages::new(&mut app, &layout, false, None);
|
||||
let second = super::source::WordPages::new(&mut app, &layout, false, None, None);
|
||||
let doc2 = second.doc();
|
||||
app.canvas.page_keys = second.into_keys();
|
||||
assert!(std::sync::Arc::ptr_eq(&doc1, &doc2), "unchanged frame reuses cached Arc<Document> snapshot");
|
||||
|
||||
app.run("text.insert", json!({"text": " world"})).unwrap();
|
||||
let layout2 = app.session.layout();
|
||||
let third = super::source::WordPages::new(&mut app, &layout2, false, None);
|
||||
let third = super::source::WordPages::new(&mut app, &layout2, false, None, None);
|
||||
let doc3 = third.doc();
|
||||
app.canvas.page_keys = third.into_keys();
|
||||
assert!(!std::sync::Arc::ptr_eq(&doc1, &doc3), "editing document invalidates cached snapshot");
|
||||
@@ -2881,3 +3084,97 @@ fn shift_clicking_a_picture_does_not_scroll_the_view() {
|
||||
assert!(picked.contains(&first) && picked.contains(&second), "both pictures are selected: {picked:?} {:?} at {at:?}", h.state().session.sel);
|
||||
assert_eq!(h.state().canvas.view.offset, before, "the view stayed where it was");
|
||||
}
|
||||
|
||||
/// The pictures drawn in the last pass that are at least 300 texels wide (a page's, not an icon's or the font
|
||||
/// atlas's glyphs): how many device pixels each is drawn across and down, and how many texels it shows.
|
||||
fn drawn_pictures(
|
||||
shapes: &[egui::epaint::ClippedShape],
|
||||
sizes: &std::collections::HashMap<egui::TextureId, [usize; 2]>,
|
||||
ppp: f32,
|
||||
) -> Vec<([f32; 2], [f32; 2])> {
|
||||
fn walk(shape: &egui::Shape, found: &mut Vec<(egui::TextureId, Rect, Rect)>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, found)),
|
||||
egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => {
|
||||
let (mut at, mut uv) = (Rect::NOTHING, Rect::NOTHING);
|
||||
for v in &mesh.vertices {
|
||||
at.extend_with(v.pos);
|
||||
uv.extend_with(v.uv);
|
||||
}
|
||||
found.push((mesh.texture_id, at, uv));
|
||||
}
|
||||
egui::Shape::Rect(rect) => {
|
||||
if let Some(brush) = &rect.brush
|
||||
&& brush.fill_texture_id != egui::TextureId::default()
|
||||
{
|
||||
found.push((brush.fill_texture_id, rect.rect, brush.uv));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
shapes.iter().for_each(|clipped| walk(&clipped.shape, &mut found));
|
||||
found
|
||||
.into_iter()
|
||||
.filter_map(|(id, at, uv)| {
|
||||
let size = sizes.get(&id).filter(|size| size[0] >= 300)?;
|
||||
let texels = [uv.width() * size[0] as f32, uv.height() * size[1] as f32];
|
||||
(texels[0] >= 300.0).then_some(([at.width() * ppp, at.height() * ppp], texels))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The page view scales a picture into its place, so a page's picture has to be exactly as many pixels each way
|
||||
/// as that place: a pixel more (what one scale and rounding up give) squeezes it by a twentieth of a percent and
|
||||
/// the text slides off the pixel grid and back down the page, which reads as blur. Run through the real page view
|
||||
/// and its picture store, at several zooms and screen densities, on the passes a renderer would draw.
|
||||
#[test]
|
||||
fn a_page_at_rest_is_drawn_one_texel_per_device_pixel() {
|
||||
for ppp in [1.0_f32, 2.0] {
|
||||
let ctx = crate::test_harness::context();
|
||||
crate::test_harness::cjk_stand_in(&ctx);
|
||||
ctx.set_pixels_per_point(ppp);
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
app.run("document.setText", json!({"text": "The quick brown fox jumps over the lazy dog."})).unwrap();
|
||||
app.run("layout.size", json!({"name": "A4"})).unwrap();
|
||||
let mut sizes = std::collections::HashMap::new();
|
||||
for (step, zoom) in [100, 110, 137].into_iter().enumerate() {
|
||||
app.run("view.zoom", json!({"value": zoom})).unwrap();
|
||||
// Until the view has come to rest and the worker has made the picture for where it rests.
|
||||
let mut seen = Vec::new();
|
||||
let exact = |pictures: &[([f32; 2], [f32; 2])]| {
|
||||
!pictures.is_empty()
|
||||
&& pictures.iter().all(|(drawn, texels)| (drawn[0] - texels[0]).abs() < 0.01 && (drawn[1] - texels[1]).abs() < 0.01)
|
||||
};
|
||||
for frame in 0..600 {
|
||||
let mut input = egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1500.0, 950.0))),
|
||||
time: Some(step as f64 * 100.0 + frame as f64 * 0.05),
|
||||
max_texture_side: Some(8192),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(viewport) = input.viewports.get_mut(&egui::ViewportId::ROOT) {
|
||||
viewport.native_pixels_per_point = Some(ppp);
|
||||
}
|
||||
craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out));
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
crate::test_harness::logic(ui.ctx(), &mut app);
|
||||
app.ui(ui);
|
||||
});
|
||||
for (id, deltas) in &out.textures_delta.set {
|
||||
for delta in deltas.iter().filter(|delta| delta.pos.is_none()) {
|
||||
sizes.insert(*id, delta.image.size());
|
||||
}
|
||||
}
|
||||
seen = drawn_pictures(&out.shapes, &sizes, ppp);
|
||||
out.textures_delta.clear();
|
||||
if frame > 3 && exact(&seen) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(exact(&seen), "{zoom} % at {ppp}x: (pixels drawn, texels shown) {seen:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,8 +51,11 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
|
||||
.iter()
|
||||
.filter(|c| !crate::dialogs::NOT_IN_SEARCH.contains(&c.id))
|
||||
.map(|c| {
|
||||
let command =
|
||||
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
|
||||
let command = if c.id == "view.paperColor" || c.id == "view.textSmoothing" {
|
||||
CommandRef::with_params("file.options", json!({"pane": "general"}))
|
||||
} else {
|
||||
CommandRef::new(c.id)
|
||||
};
|
||||
let entry = HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string());
|
||||
match crate::app::command_board::location_path(c.location) {
|
||||
Some(path) => entry.with_path(path.into_iter().map(|part| tl!(part).to_string())),
|
||||
|
||||
@@ -68,6 +68,7 @@ pub mod read_aloud;
|
||||
mod restrict_pane;
|
||||
pub mod ribbon;
|
||||
mod save_types;
|
||||
pub mod screen_text;
|
||||
pub mod scroll;
|
||||
pub use scroll::ScrollSpeed;
|
||||
pub mod desktop_theme; // owed by ribbon batch 2 (S-L348)
|
||||
|
||||
@@ -125,6 +125,8 @@ struct Strings {
|
||||
region_id: String,
|
||||
paper: Vec<(String, String)>,
|
||||
paper_id: String,
|
||||
smoothing: Vec<(String, String)>,
|
||||
smoothing_id: String,
|
||||
numerals: Vec<(String, String)>,
|
||||
numeral_id: String,
|
||||
proofing_language: String,
|
||||
@@ -171,6 +173,8 @@ impl Strings {
|
||||
|
||||
let paper = PaperColor::ALL.iter().map(|c| (id_of(c), tl!(c.label()).to_string())).collect();
|
||||
let paper_id = id_of(&app.session.prefs.paper_color);
|
||||
let smoothing = wordcraft_engine::cmd::view::TextSmoothing::ALL.iter().map(|c| (id_of(c), tl!(c.label()).to_string())).collect();
|
||||
let smoothing_id = id_of(&app.session.prefs.text_smoothing);
|
||||
let numerals = [NumeralMode::Arabic, NumeralMode::Hindi, NumeralMode::Context, NumeralMode::System]
|
||||
.iter()
|
||||
.map(|m| (id_of(m), tl!(m.label()).to_string()))
|
||||
@@ -197,6 +201,8 @@ impl Strings {
|
||||
region_id,
|
||||
paper,
|
||||
paper_id,
|
||||
smoothing,
|
||||
smoothing_id,
|
||||
numerals,
|
||||
numeral_id,
|
||||
proofing_language,
|
||||
@@ -246,6 +252,7 @@ impl<'a> OptionsModel<'a> {
|
||||
("general.theme", Choice(ui.theme.code().to_string())),
|
||||
("general.interfaceSize", Choice(size)),
|
||||
("general.paperColor", Choice(id_of(&prefs.paper_color))),
|
||||
("general.textSmoothing", Choice(id_of(&prefs.text_smoothing))),
|
||||
("general.miniToolbar", Bool(ui.mini_toolbar)),
|
||||
("general.darkPage", Bool(view.dark_mode)),
|
||||
("general.showCommunity", Bool(ui.show_discord)),
|
||||
@@ -337,6 +344,9 @@ impl PreferencesModel for OptionsModel<'_> {
|
||||
RowSpec::new("general.paperColor", tl!("Screen paper color:"), RowKind::choice(&s.paper_id, owned(&s.paper))).help(tl!(
|
||||
"Screen only. Document backgrounds, printing and exports keep their colours. Dark page and explicit Read Mode colours take precedence."
|
||||
)),
|
||||
RowSpec::new("general.textSmoothing", tl!("Screen text smoothing:"), RowKind::choice(&s.smoothing_id, owned(&s.smoothing))).help(tl!(
|
||||
"Screen only. Subpixel smoothing makes the edges of page text finer sideways, with faint colour in them, and takes longer to draw. Printing and exports are unchanged."
|
||||
)),
|
||||
b("general.miniToolbar", tl!("Show the mini toolbar when text is selected"), app.ui.mini_toolbar),
|
||||
b("general.darkPage", tl!("Dark page (white text on black)"), app.session.view.dark_mode)
|
||||
.help(tl!("Show documents with their colours inverted, like View › Switch Modes. Saving, printing and PDFs are unchanged.")),
|
||||
@@ -633,6 +643,7 @@ impl PreferencesModel for OptionsModel<'_> {
|
||||
Err(_) => self.run("ui.interfaceSize", json!({"value": "auto"})),
|
||||
},
|
||||
("general.paperColor", Choice(c)) => self.run("view.paperColor", json!({"value": c})),
|
||||
("general.textSmoothing", Choice(c)) => self.run("view.textSmoothing", json!({"value": c})),
|
||||
("general.miniToolbar", Bool(v)) => self.app.ui.mini_toolbar = v,
|
||||
("general.showCommunity", Bool(v)) => self.app.ui.show_discord = v,
|
||||
("general.fontDownloadNotice", Bool(v)) => self.app.ui.font_download_notice = v,
|
||||
|
||||
@@ -301,6 +301,23 @@ fn length_units_follow_the_interface_language() {
|
||||
assert_eq!(unit_suffix(Unit::Millimeters), " mm", "English keeps the English names");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_text_smoothing_options_round_trip_and_work_without_a_document() {
|
||||
use wordcraft_engine::cmd::view::TextSmoothing;
|
||||
let mut a = app();
|
||||
a.start_screen();
|
||||
a.run("view.textSmoothing", json!({"value":"grayscale"})).unwrap();
|
||||
let saved = serde_json::to_vec(&a.prefs()).unwrap();
|
||||
let mut b = app();
|
||||
b.apply_prefs(serde_json::from_slice::<Prefs>(&saved).unwrap());
|
||||
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Grayscale);
|
||||
with_model(&mut b, true, |m| m.set("general.textSmoothing", PrefValue::Choice("subpixel".into())));
|
||||
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Subpixel);
|
||||
// A value the option doesn't have changes nothing.
|
||||
with_model(&mut b, true, |m| m.set("general.textSmoothing", PrefValue::Choice("lcd".into())));
|
||||
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Subpixel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn screen_paper_color_options_round_trip_and_work_without_a_document() {
|
||||
use wordcraft_engine::cmd::view::PaperColor;
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
//! How the desktop draws text, so pages look like the text in the platform's other apps.
|
||||
//!
|
||||
//! Each system keeps the user's choice somewhere else, and says different things:
|
||||
//!
|
||||
//! - macOS: the `AppleFontSmoothing` default, the strength of its font smoothing (0 to 3).
|
||||
//! - Windows: `FontSmoothing`, `FontSmoothingType` and `FontSmoothingOrientation` under
|
||||
//! `HKCU\Control Panel\Desktop`: smoothing on or off, ClearType or greyscale, RGB or BGR stripes.
|
||||
//! - Linux and the BSDs: the desktop's antialiasing, hinting and subpixel order, as GNOME
|
||||
//! (`org.gnome.desktop.interface`) or KDE Plasma (`kdeglobals`) keeps them.
|
||||
//!
|
||||
//! This module turns those values into one [`ScreenText`] and keeps the latest one for the page rasters to read.
|
||||
//! It never asks the system itself, and for now nothing does: the app reads the system through craft-libs'
|
||||
//! `platform::appearance`, which reports theme, contrast and reduced motion and no text settings yet. Until a
|
||||
//! reader there hands an answer to [`set_system`] (and always in tests and headless screenshots)
|
||||
//! [`ScreenText::PLATFORM`] stands, so pages are drawn each platform's fixed way. The constructors below are what
|
||||
//! that reader's values go through.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The order of a screen's colour stripes, left to right.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum SubpixelOrder {
|
||||
Rgb,
|
||||
Bgr,
|
||||
}
|
||||
|
||||
/// How page text is drawn on screen.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ScreenText {
|
||||
/// The strength of macOS-style font smoothing (glyphs thickened sideways): 0 is none, 1 the
|
||||
/// system's default. See `wordcraft_render::RenderOptions::text_darkening`.
|
||||
pub darkening: f32,
|
||||
/// Light hinting, as FreeType's `hintslight` draws text.
|
||||
pub hinting: bool,
|
||||
/// The system asks for subpixel (LCD) antialiasing, in this stripe order; `None` when it asks
|
||||
/// for greyscale antialiasing or says nothing.
|
||||
pub subpixel: Option<SubpixelOrder>,
|
||||
/// The screen's stripe order, where the system names one, whether or not it asks for
|
||||
/// subpixel antialiasing: a user who chooses subpixel text themselves gets it in the order
|
||||
/// of their screen. `None` when the system names no side-by-side order.
|
||||
pub stripes: Option<SubpixelOrder>,
|
||||
}
|
||||
|
||||
impl ScreenText {
|
||||
/// What each platform's apps do when the user has changed nothing, and what pages are drawn
|
||||
/// with until the system has been asked: macOS smooths (thickens) text and never hints it;
|
||||
/// Linux and the BSDs hint lightly; Windows gets neither. All greyscale: a subpixel order is
|
||||
/// only ever taken from the system.
|
||||
pub const PLATFORM: ScreenText = ScreenText {
|
||||
darkening: if cfg!(target_os = "macos") { 1.0 } else { 0.0 },
|
||||
hinting: cfg!(all(unix, not(target_os = "macos"))),
|
||||
subpixel: None,
|
||||
stripes: None,
|
||||
};
|
||||
|
||||
/// macOS, from the `AppleFontSmoothing` default (`None` when it isn't set). 0 turns the
|
||||
/// smoothing off; 1, 2 and 3 are light, medium and strong, and unset is medium. The three
|
||||
/// strengths as half, one and one and a half times our darkening are our own choice: Apple
|
||||
/// publishes no numbers for them. macOS has no hinting and no subpixel antialiasing to ask
|
||||
/// for (it dropped the latter in 10.14).
|
||||
pub fn from_macos(font_smoothing: Option<i64>) -> Self {
|
||||
let darkening = match font_smoothing {
|
||||
Some(level) if level <= 0 => 0.0,
|
||||
Some(1) => 0.5,
|
||||
Some(2) | None => 1.0,
|
||||
Some(_) => 1.5,
|
||||
};
|
||||
ScreenText { darkening, hinting: false, subpixel: None, stripes: None }
|
||||
}
|
||||
|
||||
/// Windows, from the values under `HKCU\Control Panel\Desktop` (`None` for one that isn't
|
||||
/// there): `FontSmoothing` is the text "2" when edges are smoothed and "0" when not,
|
||||
/// `FontSmoothingType` is 2 for ClearType (1 is greyscale), `FontSmoothingOrientation` is 1
|
||||
/// for RGB stripes and 0 for BGR. ClearType gives subpixel edges, RGB unless the system
|
||||
/// says BGR; the stripe order itself is kept even with ClearType off. Text with smoothing off is still drawn antialiased, in greyscale: this
|
||||
/// rasteriser has no aliased text.
|
||||
pub fn from_windows(smoothing: Option<&str>, kind: Option<u32>, orientation: Option<u32>) -> Self {
|
||||
let smoothed = smoothing.map(str::trim) != Some("0");
|
||||
// The orientation is the screen's, and is kept whatever the smoothing is set to.
|
||||
let stripes = match orientation {
|
||||
Some(0) => Some(SubpixelOrder::Bgr),
|
||||
Some(1) => Some(SubpixelOrder::Rgb),
|
||||
_ => None,
|
||||
};
|
||||
let subpixel = (smoothed && kind == Some(2)).then_some(stripes.unwrap_or(SubpixelOrder::Rgb));
|
||||
ScreenText { darkening: 0.0, hinting: false, subpixel, stripes }
|
||||
}
|
||||
|
||||
/// GNOME (and the desktops that keep its settings), from `org.gnome.desktop.interface`:
|
||||
/// `font-antialiasing` is `none`, `grayscale` or `rgba`; `font-hinting` is `none`, `slight`,
|
||||
/// `medium` or `full`; `font-rgba-order` is `rgba`, `rgb`, `bgr`, `vrgb` or `vbgr`. `None`
|
||||
/// when the desktop has none of the three. Any hinting but `none` is our one light hinting.
|
||||
/// Stripes that run across the screen (`vrgb`, `vbgr`) get greyscale edges: only side by
|
||||
/// side stripes are drawn.
|
||||
pub fn from_gnome(antialiasing: Option<&str>, hinting: Option<&str>, rgba_order: Option<&str>) -> Option<Self> {
|
||||
if antialiasing.is_none() && hinting.is_none() && rgba_order.is_none() {
|
||||
return None;
|
||||
}
|
||||
let order = match rgba_order.map(str::trim) {
|
||||
Some("bgr") => Some(SubpixelOrder::Bgr),
|
||||
Some("vrgb" | "vbgr") => None,
|
||||
// `rgba` is the schema's first value and its default; it and no answer mean RGB.
|
||||
_ => Some(SubpixelOrder::Rgb),
|
||||
};
|
||||
let subpixel = if antialiasing.map(str::trim) == Some("rgba") { order } else { None };
|
||||
// The order the desktop names, kept when it asks for greyscale.
|
||||
let stripes = order.filter(|_| rgba_order.is_some());
|
||||
Some(ScreenText { darkening: 0.0, hinting: hinting.map(str::trim) != Some("none"), subpixel, stripes })
|
||||
}
|
||||
|
||||
/// KDE Plasma, from the `[General]` group of `kdeglobals`: `XftAntialias` is `true` or
|
||||
/// `false`; `XftHintStyle` is `hintnone`, `hintslight`, `hintmedium` or `hintfull`;
|
||||
/// `XftSubPixel` is `none`, `rgb`, `bgr`, `vrgb` or `vbgr`. `None` when it has none of the
|
||||
/// three (Plasma writes them only once the user has changed the font settings).
|
||||
pub fn from_kde(antialias: Option<&str>, hint_style: Option<&str>, sub_pixel: Option<&str>) -> Option<Self> {
|
||||
if antialias.is_none() && hint_style.is_none() && sub_pixel.is_none() {
|
||||
return None;
|
||||
}
|
||||
let antialiased = !matches!(antialias.map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("false" | "0"));
|
||||
let order = match sub_pixel.map(str::trim) {
|
||||
Some("rgb") => Some(SubpixelOrder::Rgb),
|
||||
Some("bgr") => Some(SubpixelOrder::Bgr),
|
||||
_ => None,
|
||||
};
|
||||
Some(ScreenText {
|
||||
darkening: 0.0,
|
||||
hinting: hint_style.map(str::trim) != Some("hintnone"),
|
||||
subpixel: order.filter(|_| antialiased),
|
||||
stripes: order,
|
||||
})
|
||||
}
|
||||
|
||||
/// The same settings with numbers a raster can take: a darkening that isn't a number, or is
|
||||
/// negative, is none, and the strongest is twice the default.
|
||||
pub fn sanitized(self) -> Self {
|
||||
let darkening = if self.darkening.is_finite() { self.darkening.clamp(0.0, 2.0) } else { 0.0 };
|
||||
ScreenText { darkening, ..self }
|
||||
}
|
||||
|
||||
/// Put these settings into a page raster's options.
|
||||
pub fn apply(self, opts: &mut wordcraft_render::RenderOptions) {
|
||||
let text = self.sanitized();
|
||||
opts.text_darkening = text.darkening;
|
||||
opts.hinting = text.hinting;
|
||||
}
|
||||
|
||||
/// A value to hash into a page's cache key: a page drawn under other settings is another
|
||||
/// raster.
|
||||
pub fn key(self) -> (u32, bool, Option<SubpixelOrder>, Option<SubpixelOrder>) {
|
||||
let text = self.sanitized();
|
||||
(text.darkening.to_bits(), text.hinting, text.subpixel, text.stripes)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the system said last; `None` until the app has asked, and when the system said nothing.
|
||||
static SYSTEM: Mutex<Option<ScreenText>> = Mutex::new(None);
|
||||
|
||||
/// How page text is drawn now: the system's settings once they are known ([`set_system`]), else
|
||||
/// [`ScreenText::PLATFORM`].
|
||||
pub fn current() -> ScreenText {
|
||||
SYSTEM.lock().unwrap_or_else(std::sync::PoisonError::into_inner).unwrap_or(ScreenText::PLATFORM)
|
||||
}
|
||||
|
||||
/// Record the system's answer (`None`: it has none, so the platform's own way stands). Returns
|
||||
/// whether that changes how text is drawn, so the caller can ask for a repaint.
|
||||
pub fn set_system(answer: Option<ScreenText>) -> bool {
|
||||
let answer = answer.map(ScreenText::sanitized);
|
||||
let before = current();
|
||||
*SYSTEM.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = answer;
|
||||
current() != before
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ScreenText, SubpixelOrder};
|
||||
|
||||
#[test]
|
||||
fn the_platform_default_is_what_was_built_in() {
|
||||
let p = ScreenText::PLATFORM;
|
||||
assert_eq!(p.darkening > 0.0, cfg!(target_os = "macos"));
|
||||
assert_eq!(p.hinting, cfg!(all(unix, not(target_os = "macos"))));
|
||||
assert_eq!((p.subpixel, p.stripes), (None, None), "a stripe order only ever comes from the system");
|
||||
// Tests and headless screenshots never ask the system, so this is what they draw with.
|
||||
assert_eq!(super::current(), p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macos_font_smoothing_sets_the_darkening() {
|
||||
let strength = |level| ScreenText::from_macos(level).darkening;
|
||||
assert_eq!(strength(None), 1.0, "unset is the system's medium");
|
||||
assert_eq!((strength(Some(0)), strength(Some(1)), strength(Some(2)), strength(Some(3))), (0.0, 0.5, 1.0, 1.5));
|
||||
// Values Apple doesn't define: below the range is off, above it the strongest.
|
||||
assert_eq!((strength(Some(-4)), strength(Some(i64::MIN)), strength(Some(9)), strength(Some(i64::MAX))), (0.0, 0.0, 1.5, 1.5));
|
||||
let text = ScreenText::from_macos(None);
|
||||
assert!(!text.hinting && text.subpixel.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_cleartype_gives_subpixel_edges_in_the_screens_order() {
|
||||
let order = |smoothing, kind, orientation| ScreenText::from_windows(smoothing, kind, orientation).subpixel;
|
||||
assert_eq!(order(Some("2"), Some(2), Some(1)), Some(SubpixelOrder::Rgb));
|
||||
assert_eq!(order(Some("2"), Some(2), Some(0)), Some(SubpixelOrder::Bgr));
|
||||
assert_eq!(order(Some("2"), Some(2), None), Some(SubpixelOrder::Rgb), "no orientation: RGB, as nearly every panel is");
|
||||
assert_eq!(order(None, Some(2), Some(1)), Some(SubpixelOrder::Rgb), "no on/off value: on, as Windows starts");
|
||||
// Greyscale smoothing, smoothing off, and a machine that says nothing.
|
||||
assert_eq!(order(Some("2"), Some(1), Some(1)), None);
|
||||
assert_eq!(order(Some("0"), Some(2), Some(1)), None);
|
||||
assert_eq!(order(Some(" 0 "), Some(2), Some(1)), None);
|
||||
assert_eq!(order(None, None, None), None);
|
||||
assert_eq!(order(Some("junk"), Some(u32::MAX), Some(u32::MAX)), None);
|
||||
let text = ScreenText::from_windows(Some("2"), Some(2), Some(1));
|
||||
assert!(!text.hinting && text.darkening == 0.0);
|
||||
// The screen's stripe order survives ClearType being off or greyscale, for a user who
|
||||
// chooses subpixel text themselves; no orientation value is no known order.
|
||||
let stripes = |smoothing, kind, orientation| ScreenText::from_windows(smoothing, kind, orientation).stripes;
|
||||
assert_eq!(stripes(Some("0"), Some(2), Some(0)), Some(SubpixelOrder::Bgr));
|
||||
assert_eq!(stripes(Some("2"), Some(1), Some(0)), Some(SubpixelOrder::Bgr));
|
||||
assert_eq!(stripes(Some("0"), None, Some(1)), Some(SubpixelOrder::Rgb));
|
||||
assert_eq!(stripes(Some("2"), Some(2), None), None);
|
||||
assert_eq!(stripes(Some("2"), Some(2), Some(7)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gnome_settings_set_hinting_and_subpixel_edges() {
|
||||
assert_eq!(ScreenText::from_gnome(None, None, None), None, "a desktop without these settings says nothing");
|
||||
let text = |a, h, o| ScreenText::from_gnome(a, h, o).unwrap();
|
||||
// GNOME's own defaults: greyscale, slight hinting.
|
||||
assert_eq!(
|
||||
text(Some("grayscale"), Some("slight"), Some("rgb")),
|
||||
ScreenText { darkening: 0.0, hinting: true, subpixel: None, stripes: Some(SubpixelOrder::Rgb) }
|
||||
);
|
||||
assert_eq!(text(Some("rgba"), Some("slight"), Some("rgb")).subpixel, Some(SubpixelOrder::Rgb));
|
||||
assert_eq!(text(Some("rgba"), Some("slight"), Some("rgba")).subpixel, Some(SubpixelOrder::Rgb));
|
||||
assert_eq!(text(Some("rgba"), Some("slight"), Some("bgr")).subpixel, Some(SubpixelOrder::Bgr));
|
||||
assert_eq!(text(Some("rgba"), None, None).subpixel, Some(SubpixelOrder::Rgb));
|
||||
// Stripes across the screen, and no antialiasing: greyscale edges.
|
||||
assert_eq!(text(Some("rgba"), Some("slight"), Some("vrgb")).subpixel, None);
|
||||
assert_eq!(text(Some("rgba"), Some("slight"), Some("vbgr")).subpixel, None);
|
||||
assert_eq!(text(Some("none"), Some("slight"), Some("rgb")).subpixel, None);
|
||||
// Hinting: off only when the desktop says none.
|
||||
assert!(!text(Some("grayscale"), Some("none"), None).hinting);
|
||||
for style in ["slight", "medium", "full", "something new"] {
|
||||
assert!(text(None, Some(style), None).hinting, "{style}");
|
||||
}
|
||||
assert!(text(Some("grayscale"), None, None).hinting);
|
||||
// The stripe order is kept when the desktop asks for greyscale or no antialiasing.
|
||||
assert_eq!(text(Some("grayscale"), None, Some("bgr")).stripes, Some(SubpixelOrder::Bgr));
|
||||
assert_eq!(text(Some("none"), None, Some("rgb")).stripes, Some(SubpixelOrder::Rgb));
|
||||
assert_eq!(text(Some("rgba"), None, None).stripes, None, "no order named");
|
||||
assert_eq!(text(Some("grayscale"), None, Some("vbgr")).stripes, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kde_settings_set_hinting_and_subpixel_edges() {
|
||||
assert_eq!(ScreenText::from_kde(None, None, None), None, "Plasma writes nothing until the font settings change");
|
||||
let text = |a, h, s| ScreenText::from_kde(a, h, s).unwrap();
|
||||
assert_eq!(
|
||||
text(Some("true"), Some("hintslight"), Some("rgb")),
|
||||
ScreenText { darkening: 0.0, hinting: true, subpixel: Some(SubpixelOrder::Rgb), stripes: Some(SubpixelOrder::Rgb) }
|
||||
);
|
||||
assert_eq!(text(Some("true"), Some("hintslight"), Some("bgr")).subpixel, Some(SubpixelOrder::Bgr));
|
||||
assert_eq!(text(None, None, Some("rgb")).subpixel, Some(SubpixelOrder::Rgb));
|
||||
for none in ["none", "vrgb", "vbgr", "junk"] {
|
||||
assert_eq!(text(Some("true"), None, Some(none)).subpixel, None, "{none}");
|
||||
}
|
||||
assert_eq!(text(Some("false"), None, Some("rgb")).subpixel, None, "antialiasing off");
|
||||
assert_eq!(text(Some(" False "), None, Some("rgb")).subpixel, None);
|
||||
assert!(!text(None, Some("hintnone"), None).hinting);
|
||||
assert!(text(None, Some("hintfull"), None).hinting && text(Some("true"), None, None).hinting);
|
||||
// The stripe order is kept with antialiasing off.
|
||||
assert_eq!(text(Some("false"), None, Some("bgr")).stripes, Some(SubpixelOrder::Bgr));
|
||||
assert_eq!(text(Some("true"), None, Some("none")).stripes, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_go_into_the_page_options_as_numbers_a_raster_can_take() {
|
||||
let mut opts = wordcraft_render::RenderOptions::default();
|
||||
ScreenText { darkening: 1.5, hinting: true, subpixel: None, stripes: None }.apply(&mut opts);
|
||||
assert_eq!((opts.text_darkening, opts.hinting), (1.5, true));
|
||||
for (given, taken) in [(f32::NAN, 0.0), (f32::INFINITY, 0.0), (-3.0, 0.0), (40.0, 2.0), (0.5, 0.5)] {
|
||||
let text = ScreenText { darkening: given, hinting: false, subpixel: None, stripes: None };
|
||||
text.apply(&mut opts);
|
||||
assert_eq!((opts.text_darkening, opts.hinting), (taken, false), "{given}");
|
||||
assert_eq!(text.key(), ScreenText { darkening: taken, ..text }.key());
|
||||
}
|
||||
// Each setting changes the cache key.
|
||||
let base = ScreenText { darkening: 1.0, hinting: false, subpixel: None, stripes: None };
|
||||
assert_ne!(base.key(), ScreenText { darkening: 0.5, ..base }.key());
|
||||
assert_ne!(base.key(), ScreenText { hinting: true, ..base }.key());
|
||||
assert_ne!(base.key(), ScreenText { subpixel: Some(SubpixelOrder::Rgb), ..base }.key());
|
||||
assert_ne!(base.key(), ScreenText { stripes: Some(SubpixelOrder::Bgr), ..base }.key());
|
||||
assert_ne!(ScreenText { subpixel: Some(SubpixelOrder::Bgr), ..base }.key(), ScreenText { subpixel: Some(SubpixelOrder::Rgb), ..base }.key());
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -58,7 +58,11 @@ Document title opens Rename Document; the account badge opens Options › Genera
|
||||
| Vertical scrollbar track paging | ✅ clicking the vertical scrollbar track above the elevator moves one screen up, and below it moves one screen down, as in Word (#5853, `canvas::tests::clicking_vertical_scrollbar_track_advances_one_screen`); it previously jumped to the clicked position | moves one screen | 90% | — |
|
||||
| Scrollbar drag page tip | ✅ while the vertical scrollbar is dragged, a tip beside the pointer names the page at the top of the window in the status bar's words ("Page 7 of 10"), on one line however long the number (#2551, #3341, `canvas::tests::dragging_the_scrollbar_names_the_page_at_the_top`); its look and wording not yet compared with Word's | not compared | 70% | 0.5 |
|
||||
| Interface text on screen (Linux, BSD) | Drawn by egui with Inter's ttfautohint hints, which match FreeType's light autohinting: measured against headless Firefox (Inter, 18.1 and 15.2 px at 1.45x), the same rows of pixels and weight (ink within 1 %) in the light theme. The dark theme no longer looks semi-bold: egui's dark default thickened light-on-dark text (about 21 % more ink than Firefox); it now adds a light 7 % (plain coverage, Firefox's weight, looked soft on the dark tab row; chosen side by side on a 145 % desktop). Not yet: subpixel (LCD) edges | sharp interface text | 90% | — |
|
||||
| Page text on screen (Linux, BSD) | Lightly hinted as FreeType's `hintslight` draws it (Firefox and other apps there): FreeType's autohinter puts baselines, x-heights and cap heights on whole pixels, nothing moves sideways, so lines break as before. Measured against headless Firefox (Arial, 21.27 px): the same rows of pixels and weight. Not yet: subpixel (LCD) edges; the interface text (egui) is hinted separately. macOS keeps its darkened unhinted text; Windows and exports are unchanged | sharp document text | 90% | 4–8 (subpixel edges) |
|
||||
| Page text on screen (Linux, BSD) | Lightly hinted as FreeType's `hintslight` draws it (Firefox and other apps there): FreeType's autohinter puts baselines, x-heights and cap heights on whole pixels, nothing moves sideways, so lines break as before. Measured against headless Firefox (Arial, 21.27 px): the same rows of pixels and weight. Subpixel (LCD) edges are their own row below; the interface text (egui) is hinted separately. Exports are unchanged | sharp document text | 90% | — |
|
||||
| Page text on screen (macOS, Windows) | Drawn from the fonts' own outlines, unhinted, as macOS draws text. Every baseline sits on a whole device pixel (upright text only; a glyph moves half a pixel at most, never sideways, so lines break as before), so the feet of the letters fill one pixel row; between two rows they were two grey ones, which read as blur beside Preview and OpenOffice on the same screen. On macOS, text is also thickened as the system's font smoothing does it, sideways only (1.21 % of the pixel size on each side, 0.3 px at most, none past 72 px per em): stems gain weight and no grey is added above or below the letters. The outline itself is widened and filled once. The softness was found by comparing 144 dpi screenshots of one paragraph (Times New Roman) in WordCraft, Preview and OpenOffice; the fix is checked on headless rasters, not yet side by side in the running app, and not measured against CoreText's own output. Subpixel (LCD) edges are their own row below. Not yet: Windows text has no ClearType-style hinting | sharp document text | 80% | 4–8 (hinting on Windows) |
|
||||
| Page text and the system's text settings | **Not followed yet.** What each system's values mean is in place (`screen_text.rs`: macOS `AppleFontSmoothing` as a darkening strength; Windows ClearType and stripe orientation; GNOME's and KDE Plasma's antialiasing, hinting and stripe order), and pages are drawn with those settings, and redrawn when they change, once one is recorded. Nothing records one: the app reads the system only through craft-libs' `platform::appearance`, which reports theme, contrast and reduced motion and no text settings. So pages are drawn each platform's fixed way (macOS darkened; Linux and BSD lightly hinted) plus the user's own Screen text smoothing choice. Shared-API gap: craft-libs needs to report the font smoothing strength, antialiasing kind, hinting and stripe order; an earlier version of this work read them in the app itself (macOS only run), which the move of system access to craft-libs rules out. Previews, dragged objects and File › New thumbnails keep the fixed defaults in any case (thumbnails without baseline snapping) | follows system settings | 20% | 4–8 (the craft-libs reader, then the wiring) |
|
||||
| Subpixel (LCD) page text | File › Options › General › Screen text smoothing (`view.textSmoothing`): Use system setting, Grayscale, Subpixel (LCD). A WordCraft extension, saved per user, never in the document. With subpixel smoothing each colour channel of a pixel takes the text's coverage around its own stripe: the page is rasterised three times, its text a third of a pixel to the left, in place and to the right, and red, green and blue are taken from the matching pass (RGB or BGR stripes). That equals text rasterised three times as wide and averaged over three neighbours (the box filter FreeType calls its light LCD filter); there is no sharper filter and no fringe reduction, so edges show more colour than ClearType's or FreeType's default. Everything but text is drawn as without it. "Subpixel (LCD)" draws it on any screen, in the screen's stripe order where the system names one, else RGB. "Use system setting" is greyscale until the system's settings are read (row above); it then draws subpixel text where the system asks for it on screens below 2 device pixels per point. Only on a page picture rasterised at the screen's own scale or size (next row): Read Mode's columns, and a part of a page shown reduced, stay greyscale. Costs up to three rasters per page with text; not timed. Formatting marks, watermarks, previews and thumbnails stay greyscale. Vertical stripe orders are not drawn. **Run on macOS only**, on headless rasters; not yet seen on a 1x LCD or on Windows or Linux | subpixel text | 50% | 6–12 (check on real screens, timing, a 5-tap filter) |
|
||||
| Page pictures at the screen's own size | The shared page view asks for each page's picture by its longest side in pixels, rounded up to a multiple of 16, and draws what it gets as its painter draws every picture: the page's place is rounded to whole pixels and the picture fitted inside it by its own proportions. Only a picture of exactly the rounded place's size is drawn one pixel for one. Rasterised at the side asked for, a page is up to 16 pixels too large (A4 at 100 % on a 2x screen: 2256 pixels for 2245); rasterised at the view's own scale and rounded up, as a first version of this did, it is still a pixel or two too large (2017 × 2852 for a 2016 × 2851 place), squeezed by a twentieth of a percent, and the text slides off the pixel grid and back down the page, which reads as blur. Now: once the view is at rest (two passes running put the pages in the same places), each picture is made exactly as many pixels each way as its place, scaled across and down by whatever that takes (a pixel in two thousand apart). While the view moves, pictures stay as they were; a page that comes into view is first made at the view's scale and again, exactly, when the view rests. Read Mode's columns, and a part of a page shown reduced, are rasterised as asked for, as before. Checked through the real page view and its picture store, headless: one texel per device pixel at 100, 110 and 137 % on 1x and 2x screens. The reporter's blurry screenshot was of the first version; **the fix has not been seen in the running app yet**. The rounding lives in the shared painter, so this follows it from outside: a shared-API gap remains (the page view could say what size it wants, or draw a screen-scale picture at its own size) | sharp document text | 80% | 2–4 (craft-libs page view) |
|
||||
| Web and Draft Layout rendering | Very long pages render only visible full-resolution raster tiles instead of shrinking one huge texture to the GPU size limit; nearby tiles are cached for scrolling | sharp document text | 95% | — |
|
||||
| Reading Mode | Existing Read Mode ribbon button opens a read-only, viewport-column layout with animated horizontal paging, transient width/text/spacing controls, heading navigation (Navigation pane) and resize anchoring; print/export layout unchanged. The arrows, Page Up/Down and Escape work straight after entering it; only whole columns show, centred, at any width, text size or window size; the columns end above the page-turn bar (#1772); Page color: None (white, the document's page color and page picture not shown), Sepia or Inverse (a dark page with light text), as Word's View › Page Color in Read Mode, starting at None and kept between Read Mode entries, documents and runs (`view.readPageColor`); ink, object drag previews and table drag arrows drawn over the pages follow it; Read Mode's View menu: Column Width and Page Color work, Layout is missing ([parity-checklist.md](parity-checklist.md), Read Mode 2/3) | reading-optimized view and navigation | 75% | 1–2 |
|
||||
| Status bar (page x of y, words, language, view buttons, zoom slider) | ✅ (the page is the caret's while the caret is on screen, else the page at the top of the window, so scrolling updates it (#3880); the language is the caret's, by name; a click sets the proofing language, or opens Set Proofing Language… for any other). The count at the right is what it shows in Word: words (default), characters (with spaces) or characters (no spaces), chosen from a right-click menu on it or File › Options › Display (Status bar count, `ui.statusCount`), kept between runs; a selection shows "selected of total" as the Word Count dialog counts them (#2797) | ✅ | 90% | — |
|
||||
@@ -125,6 +129,11 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-21 | minor | Page pictures are made exactly as many pixels each way as their place on screen once the view rests (the row "Page pictures at the screen's own scale" is now "…own size"): the first version, a pixel or two too large, was scaled by the shared painter and looked blurry. Also: stretched hinted text and synthetic bold are darkened correctly |
|
||||
| 2026-11-20 | minor | Ported onto the shared page view and Options (after #7101): page pictures are rasterised at the screen's own scale where the view's zoom accounts for the side asked for, and subpixel text is drawn only there; the Screen text smoothing row is in the shared Options; the app no longer reads the system's text settings itself, so the row "Page text follows the system's text settings" became "Page text and the system's text settings" (not followed yet: craft-libs gap). New row "Page pictures at the screen's own scale" |
|
||||
| 2026-11-19 | minor | Subpixel (LCD) page text: three rasters with the text a third of a pixel apart, one per colour stripe; File › Options › General › Screen text smoothing (`view.textSmoothing`). New row "Subpixel (LCD) page text"; run on macOS only |
|
||||
| 2026-11-19 | minor | Page drawing can take the system's text settings; nothing reads them from the system yet (see the row "Page text and the system's text settings") |
|
||||
| 2026-11-19 | minor | Page text on macOS and Windows: baselines on whole device pixels; macOS stem darkening widens outlines sideways only, in one fill, instead of stroking them all round. New row "Page text on screen (macOS, Windows)" |
|
||||
| 2026-11-25 | trivial | Review › Comments › Delete is a split button: Delete, Delete All Comments in Document and Delete All Resolved Comments. The last deletes each resolved comment with its replies and keeps the open ones, in one undo step (#7818) |
|
||||
| 2026-11-17 | trivial | Format Shape pane adds Line section (No line, Solid line with color, width, dash type, and cap type) and Layout & Properties section (size, rotation, and text box direction and vertical alignment), routes active canvas text-box edits to the member while leaving grouped text boxes disabled, rejects unknown outline `dash`/`cap` values, and applies Line and Layout edits across multi-shape selections (#5896) |
|
||||
| 2026-11-15 | trivial | Paste: a copied table pasted with the caret in a table cell inserts its rows above (caret in the first column, same width) or overwrites the cells from the caret's, adding rows and columns, as Word's Paste does; `edit.pasteNestedTable` (Paste as Nested Table) nests it (#6739). Pasted cells take the destination's cell formatting (Word keeps the source's: not done). Left as before: copies with merged cells, pictures or ragged rows, merged destinations, a one-column destination, Track Changes, PasteAppendTable. Paste into selected cells overwrites from the top-left for plain grids, even when the copied table is wider than the selection (#6742). |
|
||||
|
||||
Reference in New Issue
Block a user