mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-02 22:30:10 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b741bbac9a | ||
|
|
fd948e2015 | ||
|
|
612e92e6c5 | ||
|
|
5ae937d8e3 | ||
|
|
c07395d712 | ||
|
|
2f16864552 | ||
|
|
1b9b8b1bf3 | ||
|
|
ea5d48b18c | ||
|
|
03b54b043f | ||
|
|
e874c67147 | ||
|
|
8d7ed624ec | ||
|
|
17ae08d4b8 | ||
|
|
8edbfcdeef | ||
|
|
19947b9170 | ||
|
|
eeac0d3322 | ||
|
|
6e783bdc6e | ||
|
|
aea58b38b8 |
@@ -36,9 +36,11 @@ USAGE:
|
||||
page can't be drawn or a picture is missing or undecodable
|
||||
(report on stderr, as for convert --strict)
|
||||
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
|
||||
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
|
||||
[--save OUT …] [--page N] [--scale S] [--print] [--author NAME]
|
||||
run commands headlessly, then save (--author names
|
||||
who tracked changes and comments are by).
|
||||
Repeat --save OUT to write multiple outputs in order,
|
||||
after any outputs from --script.
|
||||
PNG saves use --page (1-based, default 1) and --scale (default 2).
|
||||
--script runs a JSON file (- is stdin) first:
|
||||
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
|
||||
@@ -632,6 +634,13 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
}
|
||||
}
|
||||
validate_options("run", &rest, RUN_OPTIONS)?;
|
||||
let mut cli_outputs = Vec::new();
|
||||
for (i, arg) in rest.iter().enumerate() {
|
||||
if arg == "--save" {
|
||||
let path = rest.get(i + 1).filter(|value| !value.is_empty() && !value.starts_with("--")).ok_or("run: --save requires a path")?;
|
||||
cli_outputs.push(path.clone());
|
||||
}
|
||||
}
|
||||
let page = parse_page_arg("run", &rest)?;
|
||||
let scale = parse_scale_arg("run", &rest)?;
|
||||
let password = password_from(&rest)?;
|
||||
@@ -680,7 +689,7 @@ fn run<S: AsRef<OsStr>>(args: &[S]) -> Result<(), Failure> {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(arg_value(&rest, "--save")).collect();
|
||||
let outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).chain(cli_outputs).collect();
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
|
||||
@@ -564,6 +564,64 @@ fn script_builds_a_document_and_saves_docx_and_pdf_relative_to_the_script() {
|
||||
assert!(json.contains("Hello script") && json.contains("\"bold\":true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_each_cli_output_and_still_accepts_a_single_save() {
|
||||
let dir = script_dir("cli-saves");
|
||||
let input = dir.join("in.docx");
|
||||
let docx = dir.join("out.docx");
|
||||
let pdf = dir.join("out.pdf");
|
||||
run(&args(&["run", "--template", "sample", "--save", &input.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--file", &input.to_string_lossy(), "--save", &docx.to_string_lossy(), "--save", &pdf.to_string_lossy()])).unwrap();
|
||||
assert_eq!(listed_text(&open(&docx, None).unwrap().doc).unwrap(), listed_text(&open(&input, None).unwrap().doc).unwrap());
|
||||
assert!(std::fs::read(pdf).unwrap().starts_with(b"%PDF"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_saves_script_and_cli_outputs() {
|
||||
let dir = script_dir("mixed-saves");
|
||||
let script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.txt","script.docx"]}"#);
|
||||
let first = dir.join("cli.txt");
|
||||
let second = dir.join("cli.docx");
|
||||
run(&args(&["run", "--save", &first.to_string_lossy(), "--script", &script, "--save", &second.to_string_lossy()])).unwrap();
|
||||
for path in [dir.join("script.txt"), dir.join("script.docx"), first, second] {
|
||||
assert!(path.is_file(), "{} was not written", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_a_missing_second_save_path_before_writing() {
|
||||
let dir = script_dir("missing-save");
|
||||
let first = dir.join("first.docx");
|
||||
let first_path = first.to_string_lossy();
|
||||
for tail in [vec!["--save"], vec!["--save", "--print"], vec!["--save", ""]] {
|
||||
let mut argv: Vec<&str> = vec!["run", "--save", &first_path];
|
||||
argv.extend(tail);
|
||||
assert_eq!(run(&args(&argv)), Err("run: --save requires a path".into()));
|
||||
assert!(!first.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_preflights_script_and_cli_outputs_in_order_before_writing() {
|
||||
let dir = script_dir("preflight-saves");
|
||||
let first = dir.join("first.docx");
|
||||
let invalid = dir.join("missing/later.docx");
|
||||
let last = dir.join("missing-too/last.docx");
|
||||
let mut script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["missing-script/script.docx"]}"#);
|
||||
let first_path = first.to_string_lossy();
|
||||
let invalid_path = invalid.to_string_lossy();
|
||||
let last_path = last.to_string_lossy();
|
||||
let argv = |script: &str| args(&["run", "--save", &first_path, "--save", &invalid_path, "--script", script, "--save", &last_path]);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("script.docx"), "{err}");
|
||||
assert!(!first.exists());
|
||||
|
||||
script = write_script(&dir, r#"{"commands":["caret.docEnd"],"save":["script.docx"]}"#);
|
||||
let err = run(&argv(&script)).unwrap_err().to_string();
|
||||
assert!(err.contains("later.docx"), "{err}");
|
||||
assert!(!first.exists() && !dir.join("script.docx").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_with_a_bad_output_writes_no_output() {
|
||||
let dir = script_dir("badout");
|
||||
|
||||
@@ -300,7 +300,11 @@ fn page(s: &mut Session, v: &Value, dir: i32) -> CmdResult {
|
||||
}
|
||||
let Some(c) = l.caret_on(&from, s.page_hint) else { return sel_result(s) };
|
||||
let np = if dir < 0 { c.page.saturating_sub(1) } else { (c.page + 1).min(l.pages.len().saturating_sub(1)) };
|
||||
let to = l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from);
|
||||
let to = if np == c.page {
|
||||
if dir < 0 { s.doc.start_of(from.story) } else { s.doc.end_of(from.story) }
|
||||
} else {
|
||||
l.hit(np, c.x, c.top + 1.0, from.story).unwrap_or(from)
|
||||
};
|
||||
s.page_hint = np;
|
||||
apply(s, to, ext);
|
||||
sel_result(s)
|
||||
|
||||
@@ -80,8 +80,12 @@ impl Session {
|
||||
};
|
||||
let l = Arc::new(wordcraft_layout::layout(&self.doc, &mut self.cache, &opts));
|
||||
let [newest, _] = std::mem::take(&mut self.layout);
|
||||
// Only preserve the alternate layout slot for the current document revision (e.g. Print vs
|
||||
// Web/Draft toggling); a superseded revision can never hit `fits()` again and would keep an
|
||||
// obsolete DocLayout live in memory.
|
||||
let prev = newest.filter(|e| e.0 == rev);
|
||||
self.layout =
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), newest];
|
||||
[Some((rev, width, height, mode, spacing, l.clone(), self.view.proofing, outline, deleted, self.view.numeral, typing, shown)), prev];
|
||||
l
|
||||
}
|
||||
|
||||
@@ -275,3 +279,31 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
|
||||
let mut session = Session::new(Document::new());
|
||||
let first = session.layout();
|
||||
let first_weak = Arc::downgrade(&first);
|
||||
drop(first);
|
||||
|
||||
// Switching view mode at the same revision keeps the prior layout in `layout[1]`.
|
||||
session.view.mode = ViewMode::Draft;
|
||||
let same_rev_other_mode = session.layout();
|
||||
assert!(first_weak.upgrade().is_some(), "same-revision alternate view mode stays cached");
|
||||
|
||||
let draft_weak = Arc::downgrade(&same_rev_other_mode);
|
||||
drop(same_rev_other_mode);
|
||||
|
||||
// Advancing `rev` makes earlier layouts unreachable: building the new layout must drop them.
|
||||
session.run("text.insert", &serde_json::json!({"text": "hello"})).expect("insert");
|
||||
let after_edit = session.layout();
|
||||
assert!(draft_weak.upgrade().is_none(), "superseded revision layout must be dropped");
|
||||
assert!(first_weak.upgrade().is_none(), "older revision layout must not remain live");
|
||||
drop(after_edit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9734,6 +9734,77 @@ fn change_case_keeps_each_runs_formatting_when_lengths_change() {
|
||||
assert_eq!(text(&s), "Q");
|
||||
}
|
||||
|
||||
/// #3479: Change Case follows language-aware mapping for Turkish, Azerbaijani, and Crimean Tatar (i↔İ, ı↔I).
|
||||
#[test]
|
||||
fn change_case_follows_turkic_language_mapping() {
|
||||
// 1. Turkish (tr-TR): all 5 modes
|
||||
// Capitalize Each Word (title)
|
||||
let mut s = s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ışık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Işık");
|
||||
|
||||
// UPPERCASE
|
||||
run(&mut s, "format.changeCase", json!({"mode": "upper"}));
|
||||
assert_eq!(text(&s), "İSTANBUL IŞIK");
|
||||
|
||||
// lowercase
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(text(&s), "istanbul ışık");
|
||||
|
||||
// sentence case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul. ışık.", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "sentence"}));
|
||||
assert_eq!(text(&s), "İstanbul. Işık.");
|
||||
|
||||
// toggle case
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "İstanbul Işık", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "toggle"}));
|
||||
assert_eq!(text(&s), "iSTANBUL ıŞIK");
|
||||
|
||||
// 2. Azerbaijani (az-AZ)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "az-AZ", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 3. Crimean Tatar (crh)
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "crh", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul");
|
||||
|
||||
// 4. English control (en-US): unchanged Unicode default
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "Istanbul");
|
||||
|
||||
// 5. Mixed-language selection: Turkish run followed by English run
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul ", "raw": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
assert_eq!(text(&s), "İstanbul Istanbul");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_case_sentence_ignores_decimal_points() {
|
||||
// #3485: Sentence case should not capitalize after decimal points.
|
||||
@@ -15344,6 +15415,32 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
|
||||
let mut s = s();
|
||||
for i in 0..80 {
|
||||
if i > 0 {
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
}
|
||||
run(&mut s, "text.insert", json!({"text": format!("Paragraph {i}")}));
|
||||
}
|
||||
let pages = s.layout().pages.len();
|
||||
assert!(pages >= 2, "expected a multi-page document, got {pages}");
|
||||
run(&mut s, "caret.docStart", json!({}));
|
||||
let start = s.sel.focus.clone();
|
||||
// Advance page by page until the last page, then one more PageDown must reach the end.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageDown", json!({}));
|
||||
}
|
||||
let end = s.doc.end_of(wordcraft_doc::StoryRef::Body);
|
||||
assert_eq!(s.sel.focus, end, "PageDown on the last page reaches the end of the document");
|
||||
// Step back page by page until page 0, then one more PageUp must reach the start.
|
||||
for _ in 0..pages {
|
||||
run(&mut s, "caret.pageUp", json!({}));
|
||||
}
|
||||
assert_eq!(s.sel.focus, start, "PageUp on the first page reaches the start of the document");
|
||||
}
|
||||
|
||||
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
|
||||
/// (a nested cell's too), a column's, not the whole page's text width.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -3416,13 +3416,22 @@ fn autocorrect_capitalisation_follows_turkic_case_mapping() {
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "İNgilizce ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "İngilizce ", "no combining dot in any language");
|
||||
// #3503: two initial capitals and caps-lock with a stray İ in English.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "Wİrd ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "two initial capitals lowercases İ to i in English");
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
typ(&mut s, "wİRD ");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "Wird ", "caps-lock slip fixes wİRD to Wird in English");
|
||||
}
|
||||
|
||||
/// #3479: Format > Change Case follows the same Turkic case mapping as AutoCorrect, using
|
||||
/// each run's own language; other languages keep the Unicode default.
|
||||
#[test]
|
||||
fn change_case_follows_turkic_case_mapping() {
|
||||
for tag in ["tr-TR", "az-AZ"] {
|
||||
for tag in ["tr-TR", "az-AZ", "crh"] {
|
||||
for (mode, input, want) in [
|
||||
("upper", "istanbul", "İSTANBUL"),
|
||||
("lower", "IŞIK", "ışık"),
|
||||
|
||||
@@ -521,12 +521,18 @@ fn fill_headers_footers(
|
||||
None
|
||||
}
|
||||
|
||||
/// Evict paragraph layouts that weren't used this pass if the cache grew large.
|
||||
/// Evict paragraph layouts that weren't used this pass if the cache accumulated too many stale entries.
|
||||
fn evict_unused(cache: &mut LayoutCache) {
|
||||
if cache.paras.len() + cache.measures.len() > 4 * cache.used.len().max(1024) {
|
||||
if cache.paras.len() + cache.measures.len() > cache.used.len() + cache.used.len().clamp(512, 1024) {
|
||||
let used = std::mem::take(&mut cache.used);
|
||||
cache.paras.retain(|k, _| used.contains(k));
|
||||
cache.measures.retain(|k, _| used.contains(k));
|
||||
if cache.paras.capacity() > cache.paras.len().max(512) * 4 {
|
||||
cache.paras.shrink_to(cache.paras.len() * 2);
|
||||
}
|
||||
if cache.measures.capacity() > cache.measures.len().max(256) * 4 {
|
||||
cache.measures.shrink_to(cache.measures.len() * 2);
|
||||
}
|
||||
cache.used = used;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18287,3 +18287,19 @@ fn many_list_definitions_keep_the_list_numbering_in_order() {
|
||||
assert_eq!(labels.first().copied(), Some("1."));
|
||||
assert_eq!(labels.last().copied(), Some("512."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evict_unused_caps_stale_entries_across_repeated_edits() {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::from_text(&"line\n".repeat(599));
|
||||
let mut c = LayoutCache::new();
|
||||
layout(&d, &mut c, &LayoutOptions::default());
|
||||
let base = c.len();
|
||||
for pass in 0..80 {
|
||||
for para_idx in 0..25 {
|
||||
d.insert_text(&Pos::body(para_idx, 0), if pass % 2 == 0 { "a" } else { "b" }, &Default::default()).unwrap();
|
||||
}
|
||||
layout(&d, &mut c, &LayoutOptions::default());
|
||||
assert!(c.len() <= base + 1025, "stale cache entries must be bounded (got {}, base {base})", c.len());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,16 +6,74 @@
|
||||
//! Renders now [`take`](ContextPool::take) the kept context, reset to their size, and
|
||||
//! [`give_back`](ContextPool::give_back) it when done.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
use vello_cpu::{RenderContext, RenderSettings};
|
||||
|
||||
/// A render context kept between renders.
|
||||
const MAX_SPARES: usize = 2;
|
||||
/// Pixel area above a 100%-zoom page even at 2x HiDPI (~2000x2000). Contexts expanded past this
|
||||
/// (e.g. 200% zoom) are dropped once renders return to normal size so large buffers aren't pinned.
|
||||
const OVERSIZED_PIXELS: u64 = 4_000_000;
|
||||
const OVERSIZED_SHRINK_STREAK: u32 = 4;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
primary: Option<RenderContext>,
|
||||
primary_out: bool,
|
||||
primary_peak_pixels: u64,
|
||||
primary_small_streak: u32,
|
||||
spares: Vec<(RenderContext, u64)>,
|
||||
/// How many contexts (both primary and single-threaded spares) were built.
|
||||
built: usize,
|
||||
}
|
||||
|
||||
/// Checked-out context from [`ContextPool`]. Dropping without [`ContextPool::give_back`] (e.g.
|
||||
/// on panic) discards the half-drawn context while still releasing the primary checkout slot.
|
||||
pub(crate) struct PooledContext<'a> {
|
||||
pool: &'a ContextPool,
|
||||
ctx: Option<RenderContext>,
|
||||
is_primary: bool,
|
||||
pixels: u64,
|
||||
}
|
||||
|
||||
impl Deref for PooledContext<'_> {
|
||||
type Target = RenderContext;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
#[allow(clippy::expect_used)]
|
||||
self.ctx.as_ref().expect("PooledContext accessed after give_back")
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for PooledContext<'_> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
#[allow(clippy::expect_used)]
|
||||
self.ctx.as_mut().expect("PooledContext accessed after give_back")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PooledContext<'_> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(ctx) = self.ctx.take() {
|
||||
if self.is_primary {
|
||||
let mut state = self.pool.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
state.primary_out = false;
|
||||
state.primary_peak_pixels = 0;
|
||||
state.primary_small_streak = 0;
|
||||
}
|
||||
drop(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render contexts kept between renders.
|
||||
///
|
||||
/// Keeps one multi-threaded primary context plus a bounded set of single-threaded spares for
|
||||
/// concurrent background page renders, avoiding spawning/tearing down extra rayon thread pools and
|
||||
/// retaining zoom-expanded buffers indefinitely.
|
||||
pub(crate) struct ContextPool {
|
||||
slot: Mutex<Option<RenderContext>>,
|
||||
/// How many contexts (so thread pools) were built: one, unless renders overlap.
|
||||
built: AtomicUsize,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
/// The context page, area and icon renders share.
|
||||
@@ -23,39 +81,96 @@ pub(crate) static CONTEXTS: ContextPool = ContextPool::new();
|
||||
|
||||
impl ContextPool {
|
||||
pub(crate) const fn new() -> Self {
|
||||
ContextPool { slot: Mutex::new(None), built: AtomicUsize::new(0) }
|
||||
}
|
||||
|
||||
/// A context reset to `w`×`h`: the kept one, or a new one with [`crate::default_threads`]
|
||||
/// workers while another render has it (another thread, or a render inside a render).
|
||||
pub(crate) fn take(&self, w: u16, h: u16) -> RenderContext {
|
||||
let kept = self.slot.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
match kept {
|
||||
Some(mut ctx) => {
|
||||
ctx.reset_and_resize(w, h);
|
||||
ctx
|
||||
}
|
||||
None => {
|
||||
self.built.fetch_add(1, Ordering::Relaxed);
|
||||
RenderContext::new_with(w, h, RenderSettings { num_threads: crate::default_threads(), ..Default::default() })
|
||||
}
|
||||
ContextPool {
|
||||
state: Mutex::new(State {
|
||||
primary: None,
|
||||
primary_out: false,
|
||||
primary_peak_pixels: 0,
|
||||
primary_small_streak: 0,
|
||||
spares: Vec::new(),
|
||||
built: 0,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `ctx` for the next [`take`](Self::take), unless one is kept already (then `ctx` and
|
||||
/// its threads go). A render that panics never gets here, so a half-drawn context is dropped
|
||||
/// rather than reused.
|
||||
pub(crate) fn give_back(&self, ctx: RenderContext) {
|
||||
let mut slot = self.slot.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if slot.is_none() {
|
||||
*slot = Some(ctx);
|
||||
/// A context reset to `w`×`h`: the kept multi-threaded primary context, a kept single-threaded
|
||||
/// spare when renders overlap, or a newly built context when none is idle.
|
||||
pub(crate) fn take(&self, w: u16, h: u16) -> PooledContext<'_> {
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
let multi_threads = crate::default_threads();
|
||||
enum Checkout {
|
||||
PrimaryExisting(RenderContext),
|
||||
PrimaryNew,
|
||||
SpareExisting(RenderContext, u64),
|
||||
SpareNew,
|
||||
}
|
||||
let action = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if multi_threads > 0 && !state.primary_out {
|
||||
state.primary_out = true;
|
||||
state.primary_peak_pixels = state.primary_peak_pixels.max(pixels);
|
||||
state.primary_small_streak = if pixels <= OVERSIZED_PIXELS { state.primary_small_streak.saturating_add(1) } else { 0 };
|
||||
match state.primary.take() {
|
||||
Some(ctx) => Checkout::PrimaryExisting(ctx),
|
||||
None => {
|
||||
state.built += 1;
|
||||
Checkout::PrimaryNew
|
||||
}
|
||||
}
|
||||
} else if let Some((ctx, peak)) = state.spares.pop() {
|
||||
Checkout::SpareExisting(ctx, peak)
|
||||
} else {
|
||||
state.built += 1;
|
||||
Checkout::SpareNew
|
||||
}
|
||||
};
|
||||
let (mut ctx, is_primary, tracked_pixels, reset) = match action {
|
||||
Checkout::PrimaryExisting(ctx) => (ctx, true, pixels, true),
|
||||
Checkout::PrimaryNew => {
|
||||
(RenderContext::new_with(w, h, RenderSettings { num_threads: multi_threads, ..Default::default() }), true, pixels, false)
|
||||
}
|
||||
Checkout::SpareExisting(ctx, peak) => (ctx, false, peak.max(pixels), true),
|
||||
Checkout::SpareNew => (RenderContext::new_with(w, h, RenderSettings { num_threads: 0, ..Default::default() }), false, pixels, false),
|
||||
};
|
||||
if reset {
|
||||
ctx.reset_and_resize(w, h);
|
||||
}
|
||||
PooledContext { pool: self, ctx: Some(ctx), is_primary, pixels: tracked_pixels }
|
||||
}
|
||||
|
||||
/// Keep `ctx` for the next [`take`](Self::take), dropping oversized contexts once renders return
|
||||
/// to normal size or when the spare pool is full. A render that panics never gets here, so a
|
||||
/// half-drawn context is dropped rather than reused.
|
||||
pub(crate) fn give_back(&self, mut guard: PooledContext<'_>) {
|
||||
let Some(ctx) = guard.ctx.take() else { return };
|
||||
let drop_it = {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if guard.is_primary {
|
||||
state.primary_out = false;
|
||||
if state.primary.is_some() {
|
||||
Some(ctx)
|
||||
} else if state.primary_peak_pixels > OVERSIZED_PIXELS && state.primary_small_streak >= OVERSIZED_SHRINK_STREAK {
|
||||
state.primary_peak_pixels = 0;
|
||||
state.primary_small_streak = 0;
|
||||
Some(ctx)
|
||||
} else {
|
||||
state.primary = Some(ctx);
|
||||
None
|
||||
}
|
||||
} else if guard.pixels <= OVERSIZED_PIXELS && state.spares.len() < MAX_SPARES {
|
||||
state.spares.push((ctx, guard.pixels));
|
||||
None
|
||||
} else {
|
||||
Some(ctx)
|
||||
}
|
||||
};
|
||||
drop(drop_it);
|
||||
}
|
||||
|
||||
/// How many contexts this pool has built.
|
||||
#[cfg(test)]
|
||||
fn built(&self) -> usize {
|
||||
self.built.load(Ordering::Relaxed)
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).built
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,4 +385,55 @@ mod tests {
|
||||
// down here; that it built any shows page renders go through it.
|
||||
assert!(CONTEXTS.built() >= 1, "page and icon renders take the shared context");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_spares_are_reused_without_spawning_more_contexts() {
|
||||
let pool = ContextPool::new();
|
||||
for _ in 0..4 {
|
||||
let a = pool.take(240, 160);
|
||||
let b = pool.take(240, 160);
|
||||
pool.give_back(a);
|
||||
pool.give_back(b);
|
||||
}
|
||||
assert_eq!(pool.built(), 2, "primary + spare should be reused across overlapping rounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_contexts_are_dropped_after_returning_to_small_renders() {
|
||||
let pool = ContextPool::new();
|
||||
let big_p = pool.take(2500, 2500);
|
||||
let big_s = pool.take(2500, 2500);
|
||||
pool.give_back(big_p);
|
||||
pool.give_back(big_s);
|
||||
assert_eq!(pool.built(), 2);
|
||||
|
||||
for _ in 0..OVERSIZED_SHRINK_STREAK {
|
||||
pooled(&pool, 400, 400);
|
||||
}
|
||||
// Oversized primary dropped at streak == OVERSIZED_SHRINK_STREAK; next take rebuilds a fresh one.
|
||||
pooled(&pool, 400, 400);
|
||||
assert_eq!(pool.built(), 3, "oversized primary should be replaced once back at normal sizes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spare_pool_caps_retained_contexts_at_max_spares() {
|
||||
let pool = ContextPool::new();
|
||||
let retained = MAX_SPARES + usize::from(crate::default_threads() > 0);
|
||||
let total = retained + 1;
|
||||
let held: Vec<_> = (0..total).map(|_| pool.take(240, 160)).collect();
|
||||
assert_eq!(pool.built(), total);
|
||||
for ctx in held {
|
||||
pool.give_back(ctx);
|
||||
}
|
||||
|
||||
// Primary (when default_threads() > 0) + MAX_SPARES spares are retained; checking that many out builds nothing new.
|
||||
let reused: Vec<_> = (0..retained).map(|_| pool.take(240, 160)).collect();
|
||||
assert_eq!(pool.built(), total, "retained contexts should be reused");
|
||||
let extra = pool.take(240, 160);
|
||||
assert_eq!(pool.built(), total + 1, "excess spare beyond MAX_SPARES should have been dropped");
|
||||
pool.give_back(extra);
|
||||
for ctx in reused {
|
||||
pool.give_back(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -887,8 +887,9 @@ impl WordApp {
|
||||
let Some(path) = p.get("path").and_then(Value::as_str) else {
|
||||
return Some(Err("`path` must name a document on the recent list".into()));
|
||||
};
|
||||
let resolved = crate::prefs::expand_recent_path(path);
|
||||
let before = self.ui.recent.len();
|
||||
self.ui.recent.retain(|r| r != path);
|
||||
self.ui.recent.retain(|r| r != path && r != &resolved);
|
||||
if self.ui.recent.len() == before {
|
||||
return Some(Err(format!("`{path}` is not on the recent list")));
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ impl WordApp {
|
||||
ui.keyboard = Shortcuts(self.session.keymap().clone());
|
||||
ui.ribbon = self.session.ribbon.clone();
|
||||
ui.ink_pens = self.session.view.draw.pens.clone();
|
||||
ui.recent = ui.recent.iter().map(|p| crate::prefs::contract_recent_path(p)).collect();
|
||||
ui
|
||||
}
|
||||
|
||||
@@ -35,6 +36,8 @@ impl WordApp {
|
||||
self.ui.tab = DEFAULT_TAB.into();
|
||||
let recent_fonts = recent_fonts_from(self.ui.font_picker.recent.iter().map(String::as_str));
|
||||
self.ui.font_picker.recent = recent_fonts;
|
||||
let mut seen_recent = std::collections::HashSet::with_capacity(self.ui.recent.len());
|
||||
self.ui.recent = self.ui.recent.iter().map(|p| crate::prefs::expand_recent_path(p)).filter(|p| seen_recent.insert(p.clone())).collect();
|
||||
// Settings from before the theme setting: their dark-mode switch picks Dark or Light.
|
||||
if let Some(dark) = self.ui.legacy_dark.take() {
|
||||
self.ui.theme = if dark { theme::Appearance::Dark } else { theme::Appearance::Light };
|
||||
|
||||
@@ -143,6 +143,8 @@ pub struct CanvasState {
|
||||
pub(crate) turning: Option<crate::objects::Turning>,
|
||||
/// Page content fingerprints of the current layout, for the page revision.
|
||||
pub(crate) page_keys: PageKeys,
|
||||
/// Cached `(body.y, body.bottom)` pairs for `PageView::bodies`, keyed by the `DocLayout` instance.
|
||||
pub(crate) page_bodies: Option<(std::sync::Weak<DocLayout>, std::rc::Rc<Vec<(f64, f64)>>)>,
|
||||
/// The caret colour last worked out and the key of the place it was worked out for, so a blink doesn't rebuild the
|
||||
/// page's draw list every frame (`cursor::caret_color_at`).
|
||||
pub(crate) caret_bg: Option<(u64, Color32)>,
|
||||
@@ -262,6 +264,19 @@ pub struct CanvasState {
|
||||
type TablePreviewKey = ((String, serde_json::Value, u64, u64, wordcraft_engine::Selection), Arc<DocLayout>);
|
||||
|
||||
impl CanvasState {
|
||||
/// Returns cached `(body.y, body.bottom)` pairs for `layout`, rebuilding only when the layout changes.
|
||||
pub(crate) fn cached_page_bodies(&mut self, layout: &Arc<DocLayout>) -> std::rc::Rc<Vec<(f64, f64)>> {
|
||||
if let Some((weak, bodies)) = &self.page_bodies
|
||||
&& weak.upgrade().is_some_and(|prev| Arc::ptr_eq(&prev, layout))
|
||||
{
|
||||
return std::rc::Rc::clone(bodies);
|
||||
}
|
||||
let bodies: std::rc::Rc<Vec<(f64, f64)>> =
|
||||
std::rc::Rc::new(layout.pages.iter().map(|p| (f64::from(p.body.y), f64::from(p.body.bottom()))).collect());
|
||||
self.page_bodies = Some((Arc::downgrade(layout), std::rc::Rc::clone(&bodies)));
|
||||
bodies
|
||||
}
|
||||
|
||||
/// Another document is shown in the window: everything about the page that was shown (drags,
|
||||
/// menus, the input method's composition, a scroll in progress…) starts afresh. What belongs
|
||||
/// to the window or the user stays: the colours last applied, the ruler's tab kind and the
|
||||
@@ -405,6 +420,7 @@ impl Default for CanvasState {
|
||||
frame_held: false,
|
||||
turning: None,
|
||||
page_keys: PageKeys::default(),
|
||||
page_bodies: None,
|
||||
caret_bg: None,
|
||||
markup_facts: Cell::new(None),
|
||||
scroll_to_caret: true,
|
||||
@@ -798,7 +814,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
let hidden = crate::objects::dragged_off_page(app.canvas.object_gesture.as_ref());
|
||||
let selected = selection_page_rects(app, layout);
|
||||
let areas = mark_areas(app, layout, &selected);
|
||||
let bodies: Vec<(f64, f64)> = layout.pages.iter().map(|p| (f64::from(p.body.y), f64::from(p.body.bottom()))).collect();
|
||||
let bodies = app.canvas.cached_page_bodies(layout);
|
||||
let show_rulers = app.session.view.ruler
|
||||
&& app.session.view.mode == wordcraft_layout::ViewMode::Print
|
||||
&& crate::chrome::Screen::of(&app.session.view) == crate::chrome::Screen::Normal;
|
||||
|
||||
@@ -36,6 +36,23 @@ fn the_page_shows_the_table_the_grid_previews() {
|
||||
assert_eq!(cells(&shown_layout(&mut app)), 0, "no request: the document's own page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_page_bodies_reuses_buffer_for_same_layout_and_rebuilds_on_change() {
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns")), crate::Services::default());
|
||||
let layout_a = app.session.layout();
|
||||
let first = app.canvas.cached_page_bodies(&layout_a);
|
||||
let second = app.canvas.cached_page_bodies(&layout_a);
|
||||
assert!(std::rc::Rc::ptr_eq(&first, &second), "same DocLayout reuses cached bodies Rc");
|
||||
assert_eq!(first.len(), layout_a.pages.len());
|
||||
|
||||
app.run("insert.header", json!({"text": "Header marker."})).unwrap();
|
||||
let layout_b = app.session.layout();
|
||||
assert!(!Arc::ptr_eq(&layout_a, &layout_b));
|
||||
let third = app.canvas.cached_page_bodies(&layout_b);
|
||||
assert!(!std::rc::Rc::ptr_eq(&first, &third), "new DocLayout rebuilds cached bodies");
|
||||
assert_eq!(third.len(), layout_b.pages.len());
|
||||
}
|
||||
|
||||
/// #3931 review: the preview's pages are drawn from the copy they were laid out from. The
|
||||
/// table moves "Kites" down a block, so the document's own block there is not its paragraph.
|
||||
#[test]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! formatting controls. The framework's selection task bar places it (above the selection, flipped
|
||||
//! and clamped inside the document area); this module decides when it shows and what it holds.
|
||||
|
||||
use craft::behavior::{EditEvent, Preview};
|
||||
use craft::behavior::{EditEvent, EditPolicy, Preview};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::pages::ui::PageBody;
|
||||
use craft::ui::buttons::{Button, ControlPlace, GroupLevel, ToggleButton};
|
||||
@@ -198,13 +198,14 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
|
||||
.map(|s| Entry::new(number_text(f64::from(*s)), number_text(f64::from(*s))))
|
||||
.collect();
|
||||
let mut text = size.clone();
|
||||
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text), &sizes).show(ui);
|
||||
// `text` is rebuilt from the selection on every pass: the box keeps what is typed until Enter.
|
||||
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text).policy(EditPolicy::OnCommit), &sizes).show(ui);
|
||||
follow_list(app, preview, &combo.preview, |v| {
|
||||
v.trim().parse::<f64>().ok().map(|x| ("format.size".to_string(), json!({"size": x})))
|
||||
});
|
||||
// Only a pick or Enter applies the size: typing alone is an edit of the box's draft.
|
||||
let committed =
|
||||
combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. } | EditEvent::Commit { .. }));
|
||||
// Only a pick or Enter applies the size: typing alone is an edit of the box's draft, and leaving the box
|
||||
// without either drops it.
|
||||
let committed = combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. }));
|
||||
if committed
|
||||
&& text != size
|
||||
&& let Ok(x) = text.trim().parse::<f64>()
|
||||
|
||||
@@ -980,3 +980,25 @@ fn automatic_and_no_color_preview_on_hover() {
|
||||
assert_eq!(h.state().canvas.command_previewed, None, "{button} {item_label}: Escape clears the preview");
|
||||
}
|
||||
}
|
||||
|
||||
/// A size typed into the bar's size box applies when Enter is pressed. The box's
|
||||
/// text was rebuilt from the selection on every pass, so what was typed was gone by then.
|
||||
#[test]
|
||||
fn a_size_typed_into_the_bar_size_box_applies_on_enter() {
|
||||
let mut h = bar_over("brown fox");
|
||||
for typed in ["20", "16.5"] {
|
||||
h.state_mut().run("select.text", json!({"text": "brown fox"})).unwrap();
|
||||
steps(&mut h);
|
||||
let selection = h.state().session.sel.clone();
|
||||
let before = format_state(&mut h).get("size").and_then(Value::as_f64);
|
||||
let at = size_box(&h).center();
|
||||
click_at(&mut h, at);
|
||||
press_key(&mut h, egui::Key::A, egui::Modifiers { ctrl: true, command: true, ..Default::default() });
|
||||
h.event(egui::Event::Text(typed.into()));
|
||||
steps(&mut h);
|
||||
assert_eq!(format_state(&mut h).get("size").and_then(Value::as_f64), before, "typing {typed} alone changes nothing");
|
||||
press_key(&mut h, egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(format_state(&mut h).get("size").and_then(Value::as_f64), typed.parse::<f64>().ok(), "Enter applies the typed size {typed}");
|
||||
assert_eq!(h.state().session.sel, selection, "the selection stays");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,7 +347,9 @@ impl PreferencesModel for OptionsModel<'_> {
|
||||
tl!("Tell me when a document's missing fonts can be downloaded"),
|
||||
app.ui.font_download_notice,
|
||||
),
|
||||
custom("general.defaultApp", tl!("Make WordCraft the default for Word documents…")).visible(can_default),
|
||||
RowSpec::new("general.defaultApp", "", RowKind::CustomRows)
|
||||
.keywords(tl!("Make WordCraft the default for Word documents…"))
|
||||
.visible(can_default),
|
||||
],
|
||||
),
|
||||
GroupSpec::new(
|
||||
|
||||
@@ -461,3 +461,105 @@ pub fn import_legacy_window(bytes: &[u8], store: &mut craft::window::restore::St
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Returns the user's home directory from `HOME` or `USERPROFILE`, if set and non-empty.
|
||||
fn home_dir() -> Option<std::path::PathBuf> {
|
||||
std::env::var_os("HOME")
|
||||
.filter(|h| !h.is_empty())
|
||||
.or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
|
||||
.map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
fn strip_tilde_prefix(path: &str) -> Option<&str> {
|
||||
if cfg!(windows) { path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\")) } else { path.strip_prefix("~/") }
|
||||
}
|
||||
|
||||
fn split_tilde_rest(rest: &str) -> impl Iterator<Item = &str> {
|
||||
let is_sep = |c: char| c == '/' || (cfg!(windows) && c == '\\');
|
||||
rest.split(is_sep).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
fn strip_home_prefix<'a>(path: &'a std::path::Path, home: &std::path::Path) -> Option<Vec<std::path::Component<'a>>> {
|
||||
if cfg!(not(windows)) {
|
||||
return path.strip_prefix(home).ok().map(|rel| rel.components().collect());
|
||||
}
|
||||
let mut path_comps = path.components();
|
||||
for h in home.components() {
|
||||
let p = path_comps.next()?;
|
||||
let matches = match (h, p) {
|
||||
(std::path::Component::Prefix(a), std::path::Component::Prefix(b)) => {
|
||||
a.as_os_str().to_string_lossy().eq_ignore_ascii_case(&b.as_os_str().to_string_lossy())
|
||||
}
|
||||
(std::path::Component::RootDir, std::path::Component::RootDir) | (std::path::Component::CurDir, std::path::Component::CurDir) => true,
|
||||
(std::path::Component::ParentDir, std::path::Component::ParentDir) => true,
|
||||
(std::path::Component::Normal(a), std::path::Component::Normal(b)) => {
|
||||
a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if !matches {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(path_comps.collect())
|
||||
}
|
||||
|
||||
/// Contracts a path inside `home` to `~/...` with `/` separators for cross-OS profile sync (#8189).
|
||||
/// Paths outside `home`, containing `..`, or (on Unix) literal backslashes are returned unchanged.
|
||||
pub(crate) fn contract_recent_path_with(path: &str, home: Option<&std::path::Path>) -> String {
|
||||
if let Some(rest) = strip_tilde_prefix(path) {
|
||||
let parts: Vec<_> = split_tilde_rest(rest).collect();
|
||||
return if parts.is_empty() { path.to_string() } else { format!("~/{}", parts.join("/")) };
|
||||
}
|
||||
let Some(home) = home else {
|
||||
return path.to_string();
|
||||
};
|
||||
let Some(rel) = strip_home_prefix(std::path::Path::new(path), home) else {
|
||||
return path.to_string();
|
||||
};
|
||||
let mut parts = Vec::new();
|
||||
for c in rel {
|
||||
match c {
|
||||
std::path::Component::Normal(s) => {
|
||||
let s = s.to_string_lossy();
|
||||
if s.contains('\\') {
|
||||
return path.to_string();
|
||||
}
|
||||
parts.push(s);
|
||||
}
|
||||
std::path::Component::CurDir => {}
|
||||
std::path::Component::ParentDir | std::path::Component::RootDir | std::path::Component::Prefix(_) => {
|
||||
return path.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
if parts.is_empty() { path.to_string() } else { format!("~/{}", parts.join("/")) }
|
||||
}
|
||||
|
||||
/// Expands a `~/...` recent-file path against `home`; other paths (or entries whose components
|
||||
/// would replace `home`, such as `..` or a Windows drive prefix) are returned unchanged (#8189).
|
||||
pub(crate) fn expand_recent_path_with(path: &str, home: Option<&std::path::Path>) -> String {
|
||||
let Some(rest) = strip_tilde_prefix(path) else {
|
||||
return path.to_string();
|
||||
};
|
||||
let Some(home) = home else {
|
||||
return path.to_string();
|
||||
};
|
||||
let mut out = home.to_path_buf();
|
||||
for part in split_tilde_rest(rest) {
|
||||
let mut comps = std::path::Path::new(part).components();
|
||||
if !matches!((comps.next(), comps.next()), (Some(std::path::Component::Normal(_)), None)) {
|
||||
return path.to_string();
|
||||
}
|
||||
out.push(part);
|
||||
}
|
||||
out.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
pub(crate) fn contract_recent_path(path: &str) -> String {
|
||||
contract_recent_path_with(path, home_dir().as_deref())
|
||||
}
|
||||
|
||||
pub(crate) fn expand_recent_path(path: &str) -> String {
|
||||
expand_recent_path_with(path, home_dir().as_deref())
|
||||
}
|
||||
|
||||
@@ -219,3 +219,55 @@ fn recent_list_edits_are_final_and_persist() {
|
||||
assert!(c.ui.recent.is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #8189: recent paths inside the user's home directory are stored as `~/...` and resolved on load.
|
||||
#[test]
|
||||
fn recent_paths_inside_home_contract_and_expand() {
|
||||
use std::path::Path;
|
||||
|
||||
let home = Path::new("/home/alice");
|
||||
let inside = home.join("Docs").join("test.docx");
|
||||
let contracted = super::contract_recent_path_with(&inside.to_string_lossy(), Some(home));
|
||||
assert_eq!(contracted, "~/Docs/test.docx");
|
||||
assert_eq!(super::expand_recent_path_with(&contracted, Some(home)), inside.to_string_lossy());
|
||||
|
||||
// Paths outside home, with `..`, and the home directory itself stay unchanged.
|
||||
assert_eq!(super::contract_recent_path_with("/tmp/outside.docx", Some(home)), "/tmp/outside.docx");
|
||||
assert_eq!(super::contract_recent_path_with("/home/alice/../etc/passwd", Some(home)), "/home/alice/../etc/passwd");
|
||||
assert_eq!(super::contract_recent_path_with(&home.to_string_lossy(), Some(home)), home.to_string_lossy());
|
||||
if cfg!(not(windows)) {
|
||||
let literal_backslash = "/home/alice/Docs/a\\b.docx";
|
||||
assert_eq!(super::contract_recent_path_with(literal_backslash, Some(home)), literal_backslash);
|
||||
assert_eq!(super::expand_recent_path_with("~/Docs/a\\b.docx", Some(home)), literal_backslash);
|
||||
// Case-sensitive on Unix.
|
||||
assert_eq!(super::contract_recent_path_with("/home/Alice/Docs/test.docx", Some(home)), "/home/Alice/Docs/test.docx");
|
||||
} else {
|
||||
let win_home = Path::new(r"C:\Users\Alice");
|
||||
assert_eq!(super::contract_recent_path_with(r"c:\users\alice\Docs\test.docx", Some(win_home)), "~/Docs/test.docx");
|
||||
assert_eq!(super::expand_recent_path_with("~/Docs/C:notes.docx", Some(win_home)), "~/Docs/C:notes.docx");
|
||||
}
|
||||
assert_eq!(super::expand_recent_path_with("~/Docs/../outside.docx", Some(home)), "~/Docs/../outside.docx");
|
||||
assert_eq!(super::expand_recent_path_with("/tmp/outside.docx", Some(home)), "/tmp/outside.docx");
|
||||
assert_eq!(super::expand_recent_path_with("~/Docs/test.docx", None), "~/Docs/test.docx");
|
||||
|
||||
// Round-trip through WordApp::prefs / apply_prefs using the process home directory.
|
||||
let real_home = std::env::var_os("HOME")
|
||||
.filter(|h| !h.is_empty())
|
||||
.or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
|
||||
.map(std::path::PathBuf::from);
|
||||
if let Some(real_home) = real_home {
|
||||
let doc = real_home.join("WordCraftSyncTest").join("notes.docx");
|
||||
let doc_str = doc.to_string_lossy().into_owned();
|
||||
let mut a = app();
|
||||
a.ui.recent = vec![doc_str.clone(), "/tmp/outside.docx".into()];
|
||||
let saved = a.prefs();
|
||||
assert_eq!(saved.recent, vec!["~/WordCraftSyncTest/notes.docx".to_string(), "/tmp/outside.docx".to_string()]);
|
||||
|
||||
let mut loaded = saved;
|
||||
loaded.recent.push(doc_str.clone());
|
||||
a.apply_prefs(loaded);
|
||||
assert_eq!(a.ui.recent, vec![doc_str, "/tmp/outside.docx".to_string()]);
|
||||
assert!(a.run("ui.recentRemove", json!({"path": "~/WordCraftSyncTest/notes.docx"})).is_ok());
|
||||
assert_eq!(a.ui.recent, vec!["/tmp/outside.docx".to_string()]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2237,11 +2237,8 @@ fn the_default_app_button_shows_only_with_the_hosts_hook() {
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("Show the community button in the title bar").is_some(), "hook {hook}: the Options page rendered");
|
||||
// The row carries the label too (macOS shows it, with Finder's steps instead of a button): ask for the button.
|
||||
let button = h.query_all_by_role_and_label(egui::accesskit::Role::Button, LABEL).next().is_some();
|
||||
assert_eq!(button, hook, "hook {hook}: the button");
|
||||
assert_eq!(h.query_all_by_label_contains(LABEL).count(), hook as usize, "hook {hook}: one caption on the button");
|
||||
if hook {
|
||||
// The button itself, not the row that carries its label.
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, LABEL).click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(calls.get(), 1, "the button ran the hook");
|
||||
|
||||
+3
-2
@@ -73,8 +73,9 @@ PDF in one run without a window:
|
||||
`file` (a document to open) and `template` are optional, and `--file` / `--template` on the command
|
||||
line win. A command is `{"command": id, "params": {…}}` or just the id. `save` is a path or a list;
|
||||
each output's format follows its extension. Relative `file` and `save` paths resolve against the
|
||||
script's folder (the working folder for stdin). `--cmd` flags run after the script's commands and
|
||||
`--save` after its outputs. The run starts with one open document. `file.new` and `file.open`
|
||||
script's folder (the working folder for stdin). `--cmd` flags run after the script's commands.
|
||||
Repeat `--save OUT` to write additional outputs in command-line order, after the script's outputs.
|
||||
Each `--save` requires a path. The run starts with one open document. `file.new` and `file.open`
|
||||
open another one and make it active; later commands and the saves work on the active document.
|
||||
`view.switchWindows` lists the open documents (with `--print` their ids show), and
|
||||
`view.switchWindows={"id": n}` makes one active. A failing command stops the run with `command N (id): …` and exit
|
||||
|
||||
Reference in New Issue
Block a user