mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-21 20:39:42 +00:00
IME: the composition is drawn in the text's font and size, and CJK in it no longer shows boxes
The IME composition is drawn in the typing style's face, size and baseline, with size capped from the font atlas. CJK in the composition no longer shows boxes. Installing fonts in one window no longer drops another window's faces. This does not change the IME popup position. See the pull request for the discussion.
This commit is contained in:
@@ -7,7 +7,7 @@ use wordcraft_doc::props::TextDirection;
|
||||
use wordcraft_doc::{Document, Path, Pos, StoryRef};
|
||||
use wordcraft_geom::{Point, Rect};
|
||||
|
||||
use crate::para::{PARA_MARK_WIDTH, ParaLayout};
|
||||
use crate::para::{PARA_MARK_WIDTH, ParaLayout, StyleRun};
|
||||
use crate::{DocLayout, Page, Placed};
|
||||
|
||||
/// Caret geometry on a page: a bar from (`x`, `top`) to (`x + width`, `top + height`). It is
|
||||
@@ -727,6 +727,30 @@ impl DocLayout {
|
||||
None
|
||||
}
|
||||
|
||||
/// The style run text typed at `pos` would take (the character's before it, or at the start
|
||||
/// of a paragraph the first character's) and the baseline it sits on, on the page: `pos`'s
|
||||
/// line's, raised or lowered by the run's shift (superscript, `w:position`). An input method's
|
||||
/// composition is drawn with them, as Word draws it in the text's own font and size. `None` in
|
||||
/// turned text, whose lines aren't horizontal.
|
||||
pub fn typing_style(&self, pos: &Pos, page_hint: usize) -> Option<(StyleRun, f32)> {
|
||||
for (_, it) in self.pieces(pos.story, &pos.path, page_hint) {
|
||||
let Placed::Lines { para, l0, l1, y, turn, .. } = it else { continue };
|
||||
let li = para.line_of(pos.off);
|
||||
if li < *l0 || li >= *l1 {
|
||||
continue;
|
||||
}
|
||||
if *turn != TextDirection::Horizontal {
|
||||
return None;
|
||||
}
|
||||
let first = para.lines.get(*l0)?;
|
||||
let line = para.lines.get(li)?;
|
||||
let at = |off: usize| para.clusters.iter().find(|c| c.start <= off && off < c.end).and_then(|c| para.styles.get(c.style as usize));
|
||||
let run = pos.off.checked_sub(1).and_then(at).or_else(|| at(pos.off)).or_else(|| para.styles.first())?;
|
||||
return Some((run.clone(), y + line.baseline - first.top - run.shift));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The position one line up (`dir < 0`) or down from `pos`, keeping `goal_x` (page x).
|
||||
pub fn vertical(&self, pos: &Pos, goal_x: Option<f32>, dir: i32, page_hint: usize) -> Option<(Pos, f32)> {
|
||||
let c = self.caret_on(pos, page_hint)?;
|
||||
|
||||
@@ -150,6 +150,7 @@ impl<'a> Builder<'a> {
|
||||
};
|
||||
let st = StyleRun {
|
||||
face,
|
||||
requested_face: r.face,
|
||||
size,
|
||||
synth_bold,
|
||||
synth_italic,
|
||||
|
||||
@@ -67,6 +67,9 @@ pub(super) fn undrawable_bullet(text: &str, lvl: &Level, rc: &ResolvedChar) -> b
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StyleRun {
|
||||
pub face: FaceRef,
|
||||
/// The face the run's font resolves to, which `face` replaces where it lacks a character (a
|
||||
/// fallback face, the East Asian font for CJK): the face new text typed in the run asks for.
|
||||
pub requested_face: FaceRef,
|
||||
pub size: f32,
|
||||
pub synth_bold: bool,
|
||||
pub synth_italic: bool,
|
||||
|
||||
@@ -10765,6 +10765,41 @@ fn east_asian_text_takes_the_asian_font_and_latin_text_the_latin_font() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text typed after a raised or lowered character sits where that character does: an input
|
||||
/// method's composition there is drawn on the line's baseline shifted as the run is (positive up),
|
||||
/// as the committed text is drawn, not on the line's own baseline.
|
||||
#[test]
|
||||
fn typing_style_takes_the_runs_baseline_shift() {
|
||||
use wordcraft_doc::props::VertAlign;
|
||||
let mut d = Document::from_text("x2");
|
||||
d.format_range(&Pos::body(0, 1), &Pos::body(0, 2), &|c| c.vert_align = Some(VertAlign::Superscript)).unwrap();
|
||||
let l = lay(&d);
|
||||
let (plain, line) = l.typing_style(&Pos::body(0, 1), 0).expect("after the x");
|
||||
let (raised, base) = l.typing_style(&Pos::body(0, 2), 0).expect("after the superscript 2");
|
||||
assert_eq!(plain.shift, 0.0);
|
||||
assert!(raised.shift > 0.0, "a superscript is raised: {}", raised.shift);
|
||||
assert!((line - raised.shift - base).abs() < 0.01, "line {line}, shift {}, baseline {base}", raised.shift);
|
||||
}
|
||||
|
||||
/// Text typed after a character the run's font lacks asks for the run's own font, not the fallback
|
||||
/// face that drew that character: an input method's composition after a Chinese character in a
|
||||
/// Latin font draws its letters as the committed letters are drawn.
|
||||
#[test]
|
||||
fn typing_style_asks_for_the_runs_font_after_a_fallback_character() {
|
||||
let text = "A\u{4f60}";
|
||||
let l = lay(&Document::from_text(text));
|
||||
let para = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
|
||||
let face_at = |off: usize| para.clusters.iter().find(|c| c.start == off).map(|c| para.styles[c.style as usize].face.id());
|
||||
let (latin, han) = (face_at(0), face_at(1));
|
||||
if latin == han {
|
||||
eprintln!("skipped: the body font has the character, or no installed font does");
|
||||
return;
|
||||
}
|
||||
let (run, _) = l.typing_style(&Pos::body(0, text.len()), 0).expect("after the Chinese character");
|
||||
assert_eq!(Some(run.face.id()), han, "the character before the caret is drawn in a fallback face");
|
||||
assert_eq!(Some(run.requested_face.id()), latin, "text typed there asks for the run's own font");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_east_asian_font_is_drawn_in_its_font_table_alternate() {
|
||||
crate::test_fonts();
|
||||
|
||||
@@ -165,29 +165,12 @@ impl WordApp {
|
||||
|| system_cjk != self.fonts_system_cjk
|
||||
|| system_arabic != self.fonts_system_arabic
|
||||
{
|
||||
// Every window's borrowed faces: the fonts are the app's.
|
||||
let mut faces = self.canvas.ime_faces.clone();
|
||||
for w in self.other_windows() {
|
||||
for face in &w.canvas.ime_faces {
|
||||
if !faces.iter().any(|f| f.id() == face.id()) {
|
||||
faces.push(face.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
theme::install_fonts_language_arabic(
|
||||
ctx,
|
||||
lang.prefers_hans(),
|
||||
lang.prefers_korean(),
|
||||
lang.prefers_hant(),
|
||||
system_cjk,
|
||||
system_arabic,
|
||||
&faces,
|
||||
);
|
||||
self.fonts_hans = lang.prefers_hans();
|
||||
self.fonts_korean = lang.prefers_korean();
|
||||
self.fonts_hant = lang.prefers_hant();
|
||||
self.fonts_system_cjk = system_cjk;
|
||||
self.fonts_system_arabic = system_arabic;
|
||||
self.apply_ui_fonts(ctx);
|
||||
// Mod with -, = and 0 are Word shortcuts (optional hyphen, subscript, paragraph spacing);
|
||||
// egui's keyboard zoom would also scale the whole window on them. Zoom is View › Zoom.
|
||||
// egui quits on Command-Q, which is Ctrl+Q off the Mac: Word's Reset Paragraph
|
||||
@@ -202,4 +185,33 @@ impl WordApp {
|
||||
self.styled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the interface fonts [`Self::install_ui_fonts`] chose, with every window's borrowed
|
||||
/// faces and each window's composition face. The fonts are the app's, one set for every
|
||||
/// window: fonts made from one window's faces would draw another window's caption or
|
||||
/// comments as boxes, and its composition in the wrong face.
|
||||
pub(crate) fn apply_ui_fonts(&self, ctx: &egui::Context) {
|
||||
let mut fonts = theme::font_definitions_language_arabic(
|
||||
self.fonts_hans,
|
||||
self.fonts_korean,
|
||||
self.fonts_hant,
|
||||
self.fonts_system_cjk,
|
||||
self.fonts_system_arabic,
|
||||
);
|
||||
// Every window's borrowed faces: the fonts are the app's.
|
||||
let mut faces = self.canvas.ime_faces.clone();
|
||||
for w in self.other_windows() {
|
||||
for face in &w.canvas.ime_faces {
|
||||
if !faces.iter().any(|f| f.id() == face.id()) {
|
||||
faces.push(face.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
theme::add_fallback_faces(&mut fonts, &faces);
|
||||
theme::set_composition_face(&mut fonts, self.windows.shown(), self.canvas.ime_face);
|
||||
for (window, w) in self.other_windows_by_key() {
|
||||
theme::set_composition_face(&mut fonts, window, w.canvas.ime_face);
|
||||
}
|
||||
ctx.set_fonts(fonts);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,6 +188,9 @@ pub struct CanvasState {
|
||||
/// Document faces added to the interface fonts so the input method's composition (#565) and a
|
||||
/// file name in the window caption can be drawn.
|
||||
pub(crate) ime_faces: Vec<std::sync::Arc<wordcraft_fonts::FontFace>>,
|
||||
/// The document face this window's composition is drawn in, as the fonts were last installed
|
||||
/// (its [`crate::theme::composition_family`]).
|
||||
pub(crate) ime_face: Option<wordcraft_fonts::FaceRef>,
|
||||
pub want_focus: bool,
|
||||
pub context_issue: Option<serde_json::Value>,
|
||||
pub context_synonyms: Option<serde_json::Value>,
|
||||
@@ -430,6 +433,7 @@ impl Default for CanvasState {
|
||||
ime_preedit: String::new(),
|
||||
ime_preedit_range: None,
|
||||
ime_faces: Vec::new(),
|
||||
ime_face: None,
|
||||
want_focus: true,
|
||||
context_issue: None,
|
||||
context_synonyms: None,
|
||||
@@ -1879,33 +1883,9 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
let mut preedit_color = None;
|
||||
let mut ime_dx = 0.0;
|
||||
if focused && !app.canvas.ime_preedit.is_empty() {
|
||||
// The composition is interface text, but it may be in a script the interface fonts lack
|
||||
// (Bangla, Thai ...): borrow the document fonts' fallback faces, or it draws as boxes (#565).
|
||||
let new = crate::theme::faces_for_preedit(
|
||||
&app.canvas.ime_preedit,
|
||||
&app.canvas.ime_faces,
|
||||
|c| (c as u32) < 0x250,
|
||||
|c| wordcraft_fonts::FontDb::global().fallback_for(c, u32::MAX),
|
||||
);
|
||||
if !new.is_empty() {
|
||||
app.canvas.ime_faces.extend(new);
|
||||
crate::theme::install_fonts_language_extra(
|
||||
ui.ctx(),
|
||||
app.fonts_hans,
|
||||
app.fonts_korean,
|
||||
app.fonts_hant,
|
||||
app.fonts_system_cjk,
|
||||
&app.canvas.ime_faces,
|
||||
);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
let color = caret_color(app);
|
||||
let g = painter.layout_no_wrap(app.canvas.ime_preedit.clone(), regular(c.height * scale * 0.8), Color32::PLACEHOLDER);
|
||||
let at = preedit_cursor_chars(&app.canvas.ime_preedit, app.canvas.ime_preedit_range.as_ref());
|
||||
ime_dx = g.pos_from_cursor(egui::text::CCursor::new(at)).min.x;
|
||||
let r = Rect::from_min_size(pos2(x, y1 - g.size().y), g.size());
|
||||
painter.galley(r.min, g, color);
|
||||
painter.line_segment([pos2(r.min.x, r.max.y), pos2(r.max.x, r.max.y)], Stroke::new(1.0, color));
|
||||
let at = CompositionAt { pr: *pr, scale, x, y1, height: c.height, turned: c.width > 0.0, color, max_tex, ppp };
|
||||
ime_dx = paint_composition(app, ui.ctx(), &painter, &layout, &at);
|
||||
preedit_color = Some(color);
|
||||
}
|
||||
let x = x + ime_dx;
|
||||
@@ -1965,5 +1945,77 @@ pub fn show(app: &mut WordApp, ui: &mut Ui) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Where [`paint_composition`] draws an input method's composition: from the caret at `x` on the
|
||||
/// page drawn at `pr` (`scale` screen points to the point), whose bottom is at `y1` and whose
|
||||
/// height is `height` points, across the page in turned text. `max_tex` and `ppp` are the
|
||||
/// texture side and pixels per point the composition's glyphs must fit.
|
||||
struct CompositionAt {
|
||||
pr: Rect,
|
||||
scale: f32,
|
||||
x: f32,
|
||||
y1: f32,
|
||||
height: f32,
|
||||
turned: bool,
|
||||
color: Color32,
|
||||
max_tex: f32,
|
||||
ppp: f32,
|
||||
}
|
||||
|
||||
/// Draw the input method's composition and return how far into it the input method's cursor
|
||||
/// lies, in screen points.
|
||||
fn paint_composition(app: &mut WordApp, ctx: &egui::Context, painter: &egui::Painter, layout: &DocLayout, at: &CompositionAt) -> f32 {
|
||||
// The composition is interface text, but it may be in a script the interface fonts lack
|
||||
// (Bangla, Thai ...): borrow the document fonts' fallback faces, or it draws as boxes (#565).
|
||||
// CJK uses the CJK UI font, as the window caption does: the faces a document falls back
|
||||
// to for it are mostly too large to borrow (Microsoft YaHei on Windows is 19 MB), and a
|
||||
// build without craft-fonts has no CJK interface face of its own.
|
||||
if !app.want_system_cjk && app.canvas.ime_preedit.chars().any(wordcraft_fonts::is_cjk) {
|
||||
app.want_system_cjk = true;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
let new = crate::theme::faces_for_preedit(&app.canvas.ime_preedit, &app.canvas.ime_faces, crate::theme::caption_char_covered, |c| {
|
||||
wordcraft_fonts::FontDb::global().fallback_for(c, u32::MAX)
|
||||
});
|
||||
// Word draws the composition in the font and size of the text it goes into: take the
|
||||
// face, size and baseline the layout gives text typed here (not in turned text). The
|
||||
// face is the one the run's font asks for, not a fallback face that drew the
|
||||
// character before the caret (a Chinese character in a Latin font).
|
||||
let typing = if at.turned { None } else { layout.typing_style(&app.session.sel.focus, app.session.page_hint) };
|
||||
let face = typing.as_ref().map(|(run, _)| run.requested_face);
|
||||
if !new.is_empty() || face != app.canvas.ime_face {
|
||||
app.canvas.ime_faces.extend(new);
|
||||
app.canvas.ime_face = face;
|
||||
// With every other window's faces too: the fonts are the app's.
|
||||
app.apply_ui_fonts(ctx);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
// New fonts apply from the next frame; until the window's composition family is bound (or
|
||||
// without a style run) the composition is drawn as before, in the interface font.
|
||||
let family = crate::theme::composition_family(app.windows.shown());
|
||||
let bound = ctx.fonts(|f| f.definitions().families.contains_key(&family));
|
||||
// egui draws each glyph into its font atlas and panics on one wider than the atlas
|
||||
// (1,638-point text at 500% is about 11,000 points): keep the composition's glyphs
|
||||
// within a quarter of the atlas side, and at most 1,024 pixels, as each glyph stays
|
||||
// in the atlas. Larger text gets a smaller composition.
|
||||
let most = (at.max_tex / 4.0).min(1024.0) / at.ppp;
|
||||
let size = |s: f32| s.min(most).max(1.0);
|
||||
let (font, base) = match &typing {
|
||||
Some((run, base)) if bound && run.size.is_finite() && run.size > 0.0 => {
|
||||
(egui::FontId::new(size(run.size * at.scale), family), Some(at.pr.min.y + base * at.scale))
|
||||
}
|
||||
_ => (regular(size(at.height * at.scale * 0.8)), None),
|
||||
};
|
||||
let g = painter.layout_no_wrap(app.canvas.ime_preedit.clone(), font, Color32::PLACEHOLDER);
|
||||
let cursor = preedit_cursor_chars(&app.canvas.ime_preedit, app.canvas.ime_preedit_range.as_ref());
|
||||
let dx = g.pos_from_cursor(egui::text::CCursor::new(cursor)).min.x;
|
||||
// The galley's first baseline sits on the line's baseline, as typed text would.
|
||||
let baseline = g.rows.first().and_then(|r| r.glyphs.first().map(|gl| r.pos.y + gl.pos.y)).unwrap_or(g.size().y);
|
||||
let top = base.map_or(at.y1 - g.size().y, |b| b - baseline);
|
||||
let r = Rect::from_min_size(pos2(at.x, top), g.size());
|
||||
painter.galley(r.min, g, at.color);
|
||||
painter.line_segment([pos2(r.min.x, r.max.y), pos2(r.max.x, r.max.y)], Stroke::new(1.0, at.color));
|
||||
dx
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -4331,6 +4331,132 @@ fn hiding_white_space_stacks_page_bands_and_keeps_hit_testing() {
|
||||
let _ = collapse_white_space(&[], &[], 1.0, 1.0);
|
||||
}
|
||||
|
||||
/// A Japanese, Chinese or Korean composition is drawn with the CJK UI font, as the window
|
||||
/// caption is. It borrowed a document face instead, but only one of 16 MB or less, and on
|
||||
/// Windows Japanese falls back to Microsoft YaHei (19 MB): without craft-fonts' CJK faces
|
||||
/// built in, the composition was a box until it was committed.
|
||||
#[test]
|
||||
fn a_cjk_composition_uses_the_cjk_ui_font() {
|
||||
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
// The frame the composition arrives in draws it before the CJK UI font is installed.
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_size(egui::vec2(1440.0, 900.0))
|
||||
.with_step_dt(1.0 / 60.0)
|
||||
.with_context_setup(kana_test_glyphs)
|
||||
.build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
for _ in 0..8 {
|
||||
h.step();
|
||||
}
|
||||
assert!(h.state().canvas.focused, "the canvas takes focus when the window opens");
|
||||
assert!(!h.state().want_system_cjk, "nothing CJK on screen yet");
|
||||
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほん".into(), active_range_chars: None }));
|
||||
for _ in 0..3 {
|
||||
h.step();
|
||||
}
|
||||
assert_eq!(h.state().canvas.ime_preedit, "にほん");
|
||||
assert!(h.state().want_system_cjk, "kana ask for the CJK UI font");
|
||||
assert!(h.state().fonts_system_cjk, "and the interface fonts are installed with it");
|
||||
assert!(!h.state().canvas.ime_faces.iter().any(|f| f.covers('に')), "no document face is borrowed for it");
|
||||
}
|
||||
|
||||
/// The composition is drawn in the font and size of the text it goes into, as Word draws it.
|
||||
/// It was drawn in the interface font at 0.8 of the line's height, which made Latin letters look
|
||||
/// larger and heavier than the same letters once committed.
|
||||
#[test]
|
||||
fn the_composition_takes_the_documents_font_and_size() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
app.run("document.setText", json!({"text": "Hello"})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
app.run("format.size", json!({"size": 20})).unwrap();
|
||||
app.run("caret.docEnd", json!({})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
for _ in 0..8 {
|
||||
h.step();
|
||||
}
|
||||
let layout = h.state_mut().session.layout();
|
||||
let (run, base) = layout.typing_style(&h.state().session.sel.focus, 0).expect("the run text typed here takes");
|
||||
assert_eq!(run.size, 20.0, "the size of the text before the caret");
|
||||
let caret = layout.caret(&h.state().session.sel.focus).expect("a caret");
|
||||
assert!(base > caret.top && base < caret.top + caret.height, "the baseline lies within the caret: {base} in {caret:?}");
|
||||
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "tottori".into(), active_range_chars: None }));
|
||||
for _ in 0..3 {
|
||||
h.step();
|
||||
}
|
||||
assert!(h.state().canvas.ime_face == Some(run.requested_face), "the composition takes that face");
|
||||
let family = crate::theme::composition_family(h.state().windows.shown());
|
||||
let first = h.ctx.fonts(|f| f.definitions().families.get(&family).and_then(|v| v.first().cloned()));
|
||||
assert!(first.as_deref().is_some_and(|n| n.starts_with("composition ") && n.contains(run.requested_face.family.as_str())), "{first:?}");
|
||||
// As drawn: at the text's size on screen, its first baseline on the line's. The caret's IME
|
||||
// rectangle gives the caret's top and the page's scale on screen.
|
||||
let ime = h.output().platform_output.ime.as_ref().map(|i| i.rect).expect("the caret's IME rectangle");
|
||||
let scale = ime.height() / caret.height;
|
||||
let drawn = h
|
||||
.output()
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|c| match &c.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == "tottori" => Some(t.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the composition is drawn");
|
||||
let size = drawn.galley.job.sections.first().map(|s| s.format.font_id.size);
|
||||
assert!(size.is_some_and(|s| (s - 20.0 * scale).abs() < 0.01), "{size:?} at scale {scale}");
|
||||
let row = drawn.galley.rows.first().expect("a row");
|
||||
let baseline = drawn.pos.y + row.pos.y + row.glyphs.first().expect("a glyph").pos.y;
|
||||
let want = ime.min.y + (base - caret.top) * scale;
|
||||
assert!((baseline - want).abs() < 0.5, "drawn baseline {baseline}, the line's {want}");
|
||||
// A composition isn't text until it is committed.
|
||||
assert_eq!(h.state().session.doc.plain_text(StoryRef::Body), "Hello");
|
||||
}
|
||||
|
||||
/// The composition's size never panics egui, which draws each glyph into its font atlas and
|
||||
/// panics on one wider than the atlas. In 1,638-point text at 500% the text's size is about
|
||||
/// 11,000 points, so the composition is drawn smaller.
|
||||
#[test]
|
||||
fn a_composition_at_the_largest_size_and_zoom_is_drawn_smaller() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
app.run("document.setText", json!({"text": "W"})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
app.run("format.size", json!({"size": 1638})).unwrap();
|
||||
app.run("caret.docEnd", json!({})).unwrap();
|
||||
app.run("view.zoom", json!({"value": 500})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
for _ in 0..8 {
|
||||
h.step();
|
||||
}
|
||||
h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "WWW".into(), active_range_chars: None }));
|
||||
for _ in 0..3 {
|
||||
h.step();
|
||||
}
|
||||
let size = h.output().shapes.iter().find_map(|c| match &c.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == "WWW" => t.galley.job.sections.first().map(|s| s.format.font_id.size),
|
||||
_ => None,
|
||||
});
|
||||
let most = h.ctx.input(|i| i.max_texture_side) as f32 / 4.0 / h.ctx.pixels_per_point();
|
||||
assert!(size.is_some_and(|s| s > 1.0 && s <= most), "{size:?}, at most {most}");
|
||||
}
|
||||
|
||||
/// #1169: Space and Enter count as `Response::clicked` on the focused canvas, and
|
||||
/// `request_focus` always interrupts IME. On X11 that recreates the XIM context and
|
||||
/// fcitx drops every later key. Those keys still type, and they must not set
|
||||
@@ -4381,11 +4507,14 @@ fn space_and_enter_on_the_canvas_do_not_interrupt_ime() {
|
||||
/// Kittest's `MissingGlyphPolicy::Panic` is right: a missing glyph is a bug. But the interface
|
||||
/// fonts need not carry Japanese (craft-fonts is optional, and a CI Linux runner has no
|
||||
/// Japanese system font), and these IME tests compose Japanese through the interface font
|
||||
/// chain. Draw a stand-in for exactly those characters; every other missing glyph still panics.
|
||||
/// chain, or a window's composition family (the document's face, then that chain). Draw a
|
||||
/// stand-in for exactly those characters; every other missing glyph still panics.
|
||||
fn kana_test_glyphs(ctx: &egui::Context) {
|
||||
ctx.add_glyph_rasterizer(egui::GlyphRasterizer::new("wordcraft::canvas::tests::kana", |req| {
|
||||
let kana =
|
||||
*req.family == egui::FontFamily::Proportional && !req.cluster.is_empty() && req.cluster.chars().all(|c| matches!(c, 'に' | 'ほ' | 'ん'));
|
||||
let composition = matches!(req.family, egui::FontFamily::Name(n) if n.starts_with("composition "));
|
||||
let kana = (*req.family == egui::FontFamily::Proportional || composition)
|
||||
&& !req.cluster.is_empty()
|
||||
&& req.cluster.chars().all(|c| matches!(c, 'に' | 'ほ' | 'ん'));
|
||||
kana.then(|| egui::RasterizedGlyph {
|
||||
bitmap: egui::GlyphBitmap {
|
||||
image: egui::ColorImage::new([1, 1], vec![egui::Color32::WHITE]),
|
||||
|
||||
@@ -545,6 +545,29 @@ pub fn install_fonts_language_arabic(
|
||||
ctx.set_fonts(fonts);
|
||||
}
|
||||
|
||||
/// The font family window `window`'s input method composition is drawn in: the document's face
|
||||
/// at the caret, then the interface fonts for what it lacks. The fonts are the app's, one set for
|
||||
/// every window, so each window has a family of its own, bound to its own document's face.
|
||||
pub fn composition_family(window: u64) -> FontFamily {
|
||||
FontFamily::Name(format!("composition {window}").into())
|
||||
}
|
||||
|
||||
/// Bind window `window`'s [`composition_family`] to `face` followed by the interface fonts, so a
|
||||
/// composition looks like the text around it, as in Word. A face larger than the composition
|
||||
/// borrows (see [`faces_for_preedit`]) is left out: the interface fonts draw the composition then.
|
||||
pub fn set_composition_face(fonts: &mut FontDefinitions, window: u64, face: Option<wordcraft_fonts::FaceRef>) {
|
||||
let mut family = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
if let Some(f) = face.filter(|f| f.data().len() <= 16 << 20) {
|
||||
let f = f.get();
|
||||
let name = format!("composition {} {} {}", f.family, f.style, f.id());
|
||||
let mut data = FontData::from_static(f.data());
|
||||
data.index = f.index();
|
||||
fonts.font_data.insert(name.clone(), Arc::new(data));
|
||||
family.insert(0, name);
|
||||
}
|
||||
fonts.families.insert(composition_family(window), family);
|
||||
}
|
||||
|
||||
/// Add `faces` after every other font of the interface families.
|
||||
pub fn add_fallback_faces(fonts: &mut FontDefinitions, faces: &[Arc<wordcraft_fonts::FontFace>]) {
|
||||
for f in faces {
|
||||
|
||||
@@ -867,6 +867,12 @@ impl WordApp {
|
||||
pub(crate) fn other_windows(&self) -> impl Iterator<Item = &WindowUi> {
|
||||
self.windows.open.iter().filter_map(|w| w.ui.as_deref())
|
||||
}
|
||||
|
||||
/// [`WordApp::other_windows`] with each window's key, for each window's composition face
|
||||
/// ([`crate::theme::composition_family`]).
|
||||
pub(crate) fn other_windows_by_key(&self) -> impl Iterator<Item = (u64, &WindowUi)> {
|
||||
self.windows.open.iter().filter_map(|w| w.ui.as_deref().map(|ui| (w.key, ui)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -364,6 +364,64 @@ fn a_composition_stays_in_its_window() {
|
||||
assert_eq!(text(&a), "B", "a commit in the other window doesn't land here");
|
||||
}
|
||||
|
||||
/// The fonts are the app's, one set for every window. A composition in one window installs them
|
||||
/// with the faces another window borrowed for its interface text, and each window's composition
|
||||
/// keeps its own document's face, whichever window installed the fonts last. With both windows
|
||||
/// composing, neither installs them again.
|
||||
#[test]
|
||||
fn a_composition_keeps_every_windows_fonts() {
|
||||
let ctx = backend();
|
||||
let font = |a: &mut WordApp, name: &str| {
|
||||
a.run("select.all", json!({})).unwrap();
|
||||
a.run("format.font", json!({"name": name})).unwrap();
|
||||
a.run("caret.docEnd", json!({})).unwrap();
|
||||
};
|
||||
let mut a = app("Serif");
|
||||
font(&mut a, "Source Serif 4");
|
||||
let first = a.windows.shown();
|
||||
frames(&ctx, &mut a, 2);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
a.run("text.insert", json!({"text": "Mono"})).unwrap();
|
||||
font(&mut a, "JetBrains Mono");
|
||||
let (second, b) = (a.windows.shown(), a.active_viewport());
|
||||
assert_ne!(first, second);
|
||||
// The second window borrows a face for its interface text, as for a file name in a script
|
||||
// the interface fonts lack.
|
||||
let borrowed = wordcraft_fonts::FontDb::global().fallback_for('A', u32::MAX).expect("a face for Latin");
|
||||
let borrowed_name = format!("fallback {} {} {}", borrowed.family, borrowed.style, borrowed.id());
|
||||
a.canvas.ime_faces.push(borrowed);
|
||||
a.styled = false;
|
||||
let compose = |id: ViewportId| {
|
||||
EVENTS.with(|e| {
|
||||
e.borrow_mut().entry(id).or_default().push(egui::Event::Ime(egui::ImeEvent::Preedit { text: "tottori".into(), active_range_chars: None }))
|
||||
})
|
||||
};
|
||||
let face_of = |window: u64| {
|
||||
ctx.fonts(|f| f.definitions().families.get(&crate::theme::composition_family(window)).and_then(|v| v.first().cloned())).unwrap_or_default()
|
||||
};
|
||||
let has_borrowed = || ctx.fonts(|f| f.definitions().families.get(&egui::FontFamily::Proportional).is_some_and(|v| v.contains(&borrowed_name)));
|
||||
|
||||
focus(ViewportId::ROOT);
|
||||
frames(&ctx, &mut a, 8);
|
||||
assert!(a.active_viewport() == ViewportId::ROOT && a.canvas.focused);
|
||||
compose(ViewportId::ROOT);
|
||||
frames(&ctx, &mut a, 3);
|
||||
assert!(face_of(first).contains("Source Serif"), "{}", face_of(first));
|
||||
assert!(has_borrowed(), "the first window's composition keeps the face the second borrowed");
|
||||
|
||||
focus(b);
|
||||
frames(&ctx, &mut a, 8);
|
||||
assert!(a.active_viewport() == b && a.canvas.focused);
|
||||
compose(b);
|
||||
frames(&ctx, &mut a, 3);
|
||||
assert!(face_of(second).contains("JetBrains Mono"), "{}", face_of(second));
|
||||
assert!(face_of(first).contains("Source Serif"), "the first window's composition keeps its face: {}", face_of(first));
|
||||
assert!(has_borrowed());
|
||||
UPLOADS.with(|u| *u.borrow_mut() = 0);
|
||||
frames(&ctx, &mut a, 4);
|
||||
assert_eq!(UPLOADS.with(|u| *u.borrow()), 0, "the fonts are not installed again");
|
||||
}
|
||||
|
||||
/// Control-channel typing goes to the active window when it has a viewport of its own (the
|
||||
/// root's raw-input hook doesn't see that window's input), once.
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user