diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b2d7a939..3d8f93f3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1111,6 +1111,8 @@ pub struct NoteCraftApp { /// History > Hide Authors: who changed a page is not shown under its title. What the page /// keeps is not touched (issue #292). hide_authors: bool, + /// Printouts being made off the window's thread, with the format of the page each is for. + printouts: Vec<(crate::printout::Job, PageFormat)>, open: HashSet, selected: Option, /// The pages visited, for Back and Forward. @@ -1383,6 +1385,7 @@ impl NoteCraftApp { saver, author_name, hide_authors, + printouts: Vec::new(), nav: NavHistory::default(), qat, last_ink_change: None, @@ -2252,6 +2255,11 @@ impl NoteCraftApp { self.open = self.collect_branches().into_iter().collect(); } + /// How many printouts are still being made. + pub fn printouts_pending(&self) -> usize { + self.printouts.len() + } + /// Whether the page being edited has unsaved changes. pub fn is_dirty(&self) -> bool { self.editor @@ -3312,52 +3320,96 @@ impl NoteCraftApp { } } + /// Starts making a printout of `file` for the page in `dir`, off the window's thread: the + /// page goes on being written in while it is made ([`crate::printout::Job`]), and it goes in + /// once it is ready ([`Self::poll_printouts`]). fn insert_printout(&mut self, dir: &Path, file: &Path, format: PageFormat) { - let rendered = match printout::render(file) { - Ok(rendered) => rendered, + let job = crate::printout::Job::start(dir, file); + self.say(crate::i18n::format_message_id("ui.making_a_printout_of_name", &[("name", &job.name)])); + self.printouts.push((job, format)); + } + + /// Takes in the printouts that are ready, and says how far along the others are. + fn poll_printouts(&mut self, ctx: &Context) { + let mut i = 0; + while i < self.printouts.len() { + match self.printouts[i].0.poll() { + None => { + let (done, total) = self.printouts[i].0.pages; + if total > 0 { + let name = self.printouts[i].0.name.clone(); + self.say(crate::i18n::format_message_id( + "ui.making_a_printout_of_name_page_done_of_total", + &[("name", &name), ("done", &done.to_string()), ("total", &total.to_string())], + )); + } + i += 1; + } + Some(made) => { + let (job, format) = self.printouts.remove(i); + self.finish_printout(&job, format, made); + } + } + } + if !self.printouts.is_empty() { + ctx.request_repaint_after(Duration::from_millis(100)); + } + } + + /// Puts a printout that is ready into its page: the open one where the writer is, as + /// [`Self::insert_printout_blocks`] does, or, when another page was opened meanwhile, into + /// that page's file, in a box of its own below what is there. + fn finish_printout(&mut self, job: &crate::printout::Job, format: PageFormat, made: Result) { + let made = match made { + Ok(made) => made, Err(error) => { self.complain(&error); return; } }; - let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let Some(Output::Text(link)) = self.run("page.attach", ¶ms(&[("path", &path_str(dir)), ("source", &path_str(file))])) else { - self.complain(&crate::i18n::format_message_id("ui.could_not_attach_name_before_rendering_its_pages", &[("name", &name)])); - return; - }; - let Some(base) = link.strip_prefix("assets/").and_then(|link| Path::new(link).file_name()).map(|name| name.to_string_lossy().into_owned()) - else { - self.complain(crate::tl_id!("ui.the_attachment_returned_an_invalid_page_link")); - return; - }; - let assets = dir.join("assets"); - let mut generated = Vec::with_capacity(rendered.pages().len()); - for (index, page) in rendered.pages().iter().enumerate() { - let target = assets.join(format!("{base}.printout-{:03}.png", index + 1)); - if let Err(error) = std::fs::copy(page, &target) { - for path in &generated { - let _ = std::fs::remove_file(path); - } - self.complain(&crate::i18n::format_message_id( - "ui.could_not_store_printout_page_page_error", - &[("page", &(index + 1).to_string()), ("error", &error.to_string())], - )); - return; - } - generated.push(target); + let mut text = snippets::attachment(format, &made.link, &job.name); + for (index, image) in made.images.iter().enumerate() { + text.push_str(&snippets::printout_page(format, image, index + 1)); } - let mut text = snippets::attachment(format, &link, &name); - for (index, _) in generated.iter().enumerate() { - let image = format!("assets/{base}.printout-{:03}.png", index + 1); - text.push_str(&snippets::printout_page(format, &image, index + 1)); + if self.editor.as_ref().is_some_and(|ed| ed.dir == job.dir) { + self.insert_printout_blocks(&text); + if let Some(ed) = self.editor.as_mut() { + ed.attachments = notecraft_store::assets::list(&ed.dir); + } + } else if !self.add_to_page_file(&job.dir, &text) { + return; } - self.insert_printout_blocks(&text); self.say(crate::i18n::format_message_id( "ui.inserted_name_and_count_printout_pages", - &[("name", &name), ("count", &generated.len().to_string())], + &[("name", &job.name), ("count", &made.images.len().to_string())], )); } + /// Adds `text` to the page in `dir`, which is not the one open, in a box of its own below its + /// boxes, and writes it. Says why when it cannot, and returns whether it did. + fn add_to_page_file(&mut self, dir: &Path, text: &str) -> bool { + let page = match notecraft_store::page::load_page(dir) { + Ok(page) => page, + Err(e) => { + self.complain(&e.to_string()); + return false; + } + }; + let (mut blocks, arranged) = notecraft_formats::boxes::read(page.format, &page.body); + let (added, _) = notecraft_formats::boxes::read(page.format, text); + let body = match arranged { + Some(boxes) if !boxes.is_empty() => { + let width = boxes.first().map_or(360.0, |c| c.width); + let below = boxes.iter().map(|c| c.y + 60.0).fold(0.0, f32::max); + let boxes = notecraft_model::container::append(&boxes, blocks.len(), added.len(), width, below, 12.0); + blocks.extend(added); + notecraft_formats::boxes::write(page.format, &blocks, Some(&boxes)) + } + _ => format!("{}\n{text}", page.body.trim_end()), + }; + self.run("page.save", ¶ms(&[("path", &path_str(dir)), ("body", &body)])).is_some() + } + // ---------- tree ---------- fn collect_branches(&self) -> Vec { @@ -11908,6 +11960,7 @@ impl NoteCraftApp { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); } } + self.poll_printouts(ctx); self.take_saves(false); if self.saver.busy() { ctx.request_repaint_after(std::time::Duration::from_millis(50)); @@ -12640,7 +12693,7 @@ mod alert_tests { |h: &egui_kittest::Harness<'_, NoteCraftApp>| h.state().editor.as_ref().map(|e| (e.blocks.clone(), e.boxes.clone())).expect("editor"); let before = shape(&h); let dir = page.clone(); - h.state_mut().add_file(&dir, &pdf, FileChoice::Printout); + add_printout(&mut h, &dir, &pdf); // Long enough for the autosave to write the page and the window to settle. for _ in 0..60 { h.step(); @@ -12684,6 +12737,79 @@ mod alert_tests { (t, page, pdf, h) } + /// Asks for a printout of `pdf` in `page` and waits for it: it is made in the background. + fn add_printout(h: &mut egui_kittest::Harness<'_, NoteCraftApp>, page: &Path, pdf: &Path) { + h.state_mut().add_file(page, pdf, FileChoice::Printout); + for _ in 0..500 { + h.step(); + if h.state().printouts_pending() == 0 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(h.state().printouts_pending(), 0, "the printout was made"); + for _ in 0..3 { + h.step(); + } + } + + /// A printout is made off the window's thread: asking for one returns at once, the window + /// carries on drawing, and the pages go in once they are ready. Making one froze the page + /// for seconds (rendering, then copying every page into the page's folder). + #[test] + fn a_printout_is_made_in_the_background_and_goes_in_when_ready() { + let (_t, page, pdf, mut h) = printout_harness(true, "printout-background"); + let before = h.state().editor.as_ref().map(|e| e.blocks.len()).expect("editor"); + h.state_mut().add_file(&page, &pdf, FileChoice::Printout); + assert_eq!(h.state().printouts_pending(), 1, "the printout is being made"); + assert_eq!(h.state().editor.as_ref().map(|e| e.blocks.len()), Some(before), "and the page is not waiting for it"); + h.step(); + for _ in 0..500 { + h.step(); + if h.state().printouts_pending() == 0 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let ed = h.state().editor.as_ref().expect("editor"); + assert!(ed.blocks.len() > before, "the printout went in once it was ready"); + assert!( + ed.blocks.iter().any(|b| matches!(b, notecraft_formats::Block::Image { src, .. } if src.contains(".printout-001.png"))), + "its page is a picture in the page" + ); + } + + /// A printout asked for on one page goes into that page, even when another page was opened + /// while it was being made. + #[test] + fn a_printout_goes_into_its_own_page_when_another_was_opened_meanwhile() { + let (_t, page, pdf, mut h) = printout_harness(true, "printout-other-page"); + let other = { + let parent = page.parent().expect("section").to_path_buf(); + std::fs::read_dir(&parent) + .expect("section") + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.is_dir() && *p != page) + .expect("another page") + }; + h.state_mut().add_file(&page, &pdf, FileChoice::Printout); + h.state_mut().open_path(&other.to_string_lossy()); + for _ in 0..500 { + h.step(); + if h.state().printouts_pending() == 0 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(h.state().editor.as_ref().map(|e| e.dir.clone()), Some(other.clone()), "the other page is the one open"); + let file = notecraft_store::tree::page_file(&page).expect("the first page's file").1; + let text = std::fs::read_to_string(file).expect("read"); + assert!(text.contains(".printout-001.png"), "the printout is in the page it was asked for:\n{text}"); + let other_file = notecraft_store::tree::page_file(&other).expect("the other page's file").1; + assert!(!std::fs::read_to_string(other_file).expect("read").contains(".printout-001.png"), "and not in the other one"); + } + /// The window opens where it was left: the same page, even in a notebook kept outside the /// notebooks folder (the one in a synced folder, say), at the same zoom and scrolled to the /// same place. A page outside the notebooks folder was never remembered at all, so the window @@ -12787,7 +12913,7 @@ mod alert_tests { #[test] fn drawing_a_page_of_printouts_does_not_ask_the_disk_every_frame() { let (_t, page, pdf, mut h) = printout_harness(true, "printout-quiet-frames"); - h.state_mut().add_file(&page, &pdf, FileChoice::Printout); + add_printout(&mut h, &page, &pdf); for _ in 0..5 { h.step(); } @@ -12808,10 +12934,7 @@ mod alert_tests { let (_t, page, pdf, mut h) = printout_harness(html, "printout-below"); h.state_mut().editor.as_mut().expect("editor").caret = None; for _ in 0..2 { - h.state_mut().add_file(&page, &pdf, FileChoice::Printout); - for _ in 0..5 { - h.step(); - } + add_printout(&mut h, &page, &pdf); } let all = h.state().editor.as_ref().map(|e| e.boxes.clone()).expect("editor"); // The sample page's words, then one box for each printout, each one further down. @@ -12858,10 +12981,7 @@ mod alert_tests { } let boxes_with_blank = h.state().editor.as_ref().map(|e| e.boxes.len()).expect("editor"); h.state_mut().editor.as_mut().expect("editor").caret = None; - h.state_mut().add_file(&page, &pdf, FileChoice::Printout); - for _ in 0..5 { - h.step(); - } + add_printout(&mut h, &page, &pdf); let ed = h.state().editor.as_ref().expect("editor"); assert!(!ed.boxes.iter().any(|c| c.y == 2000.0), "html={html}: the blank box went: {:?}", ed.boxes); assert_eq!(ed.boxes.len(), boxes_with_blank, "html={html}: one box for the printout, none for the blank line: {:?}", ed.boxes); @@ -12942,10 +13062,7 @@ mod alert_tests { } let before = h.state().editor.as_ref().map(|e| e.boxes.clone()).expect("editor"); let blocks_before = h.state().editor.as_ref().map(|e| e.blocks.clone()).expect("editor"); - h.state_mut().add_file(&page, &pdf, FileChoice::Printout); - for _ in 0..5 { - h.step(); - } + add_printout(&mut h, &page, &pdf); let ed = h.state().editor.as_ref().expect("editor"); assert_eq!(ed.boxes.len(), before.len(), "html={html}: no new box was made: {:?}", ed.boxes); let moved = &ed.boxes[index]; diff --git a/crates/ui-egui/src/printout.rs b/crates/ui-egui/src/printout.rs index 693dcebb..2ac90759 100644 --- a/crates/ui-egui/src/printout.rs +++ b/crates/ui-egui/src/printout.rs @@ -40,13 +40,16 @@ pub(crate) fn supports(source: &Path) -> bool { extension == "pdf" || OFFICE_EXTENSIONS.contains(&extension.as_str()) } -pub(crate) fn render(source: &Path) -> Result { +/// Renders `source` (a PDF, or an Office document by way of a PDF) to one picture a page, in a +/// workspace of its own that goes with the result, telling `progress` how many pages of how many +/// are done as they finish. +pub(crate) fn render_with(source: &Path, progress: &(dyn Fn(usize, usize) + Sync)) -> Result { if !supports(source) { return Err("Printout is supported for PDF and Office documents only".into()); } let workspace = temporary_workspace()?; fs::create_dir_all(&workspace).map_err(|e| format!("cannot create printout workspace: {e}"))?; - let result = render_in_workspace(source, &workspace); + let result = render_in_workspace(source, &workspace, progress); match result { Ok(pages) => Ok(Rendered { workspace, pages }), Err(error) => { @@ -56,35 +59,63 @@ pub(crate) fn render(source: &Path) -> Result { } } -fn render_in_workspace(source: &Path, workspace: &Path) -> Result, String> { +fn render_in_workspace(source: &Path, workspace: &Path, progress: &(dyn Fn(usize, usize) + Sync)) -> Result, String> { let pdf = if source.extension().and_then(OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) { source.to_path_buf() } else { office_to_pdf(source, workspace)? }; - let pages = render_pdf(&pdf, workspace)?; + let pages = render_pdf_with(&pdf, workspace, progress)?; if pages.is_empty() { return Err("the renderer produced no printout pages".into()); } Ok(pages) } +#[cfg(test)] fn render_pdf(pdf_path: &Path, workspace: &Path) -> Result, String> { - let data = fs::read(pdf_path).map_err(|e| format!("cannot read PDF for rendering: {e}"))?; - let pdf = Pdf::new(Arc::new(data)).map_err(|e| format!("cannot parse PDF for rendering: {e:?}"))?; + render_pdf_with(pdf_path, workspace, &|_, _| {}) +} + +/// Renders every page of a PDF to a PNG in `workspace`, in the document's order. The pages are +/// rendered side by side, one thread to a core, each with its own reading of the document: one +/// after another, a fifteen-page printout took about two seconds. +fn render_pdf_with(pdf_path: &Path, workspace: &Path, progress: &(dyn Fn(usize, usize) + Sync)) -> Result, String> { + let data = Arc::new(fs::read(pdf_path).map_err(|e| format!("cannot read PDF for rendering: {e}"))?); + let count = Pdf::new(data.clone()).map_err(|e| format!("cannot parse PDF for rendering: {e:?}"))?.pages().len(); let pages_dir = workspace.join("pages"); fs::create_dir_all(&pages_dir).map_err(|e| format!("cannot create printout pages folder: {e}"))?; - let interpreter = InterpreterSettings::default(); - let settings = RenderSettings { x_scale: 2.0, y_scale: 2.0, bg_color: WHITE, ..Default::default() }; - let mut pages = Vec::with_capacity(pdf.pages().len()); - for (index, page) in pdf.pages().iter().enumerate() { - let pixmap = render_pdf_page(page, &interpreter, &settings); - let path = pages_dir.join(format!("page-{:03}.png", index + 1)); - let png = pixmap.into_png().map_err(|e| format!("cannot encode PDF page {} as PNG: {e}", index + 1))?; - fs::write(&path, png).map_err(|e| format!("cannot write rendered PDF page {}: {e}", index + 1))?; - pages.push(path); + let threads = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get).clamp(1, 8).min(count.max(1)); + let done = std::sync::atomic::AtomicUsize::new(0); + let results: Vec, String>> = std::thread::scope(|scope| { + let workers: Vec<_> = (0..threads) + .map(|worker| { + let (data, pages_dir, done) = (data.clone(), &pages_dir, &done); + scope.spawn(move || -> Result, String> { + let pdf = Pdf::new(data).map_err(|e| format!("cannot parse PDF for rendering: {e:?}"))?; + let interpreter = InterpreterSettings::default(); + let settings = RenderSettings { x_scale: 2.0, y_scale: 2.0, bg_color: WHITE, ..Default::default() }; + let mut mine = Vec::new(); + for (index, page) in pdf.pages().iter().enumerate().skip(worker).step_by(threads) { + let pixmap = render_pdf_page(page, &interpreter, &settings); + let path = pages_dir.join(format!("page-{:03}.png", index + 1)); + let png = pixmap.into_png().map_err(|e| format!("cannot encode PDF page {} as PNG: {e}", index + 1))?; + fs::write(&path, png).map_err(|e| format!("cannot write rendered PDF page {}: {e}", index + 1))?; + mine.push((index, path)); + progress(done.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1, count); + } + Ok(mine) + }) + }) + .collect(); + workers.into_iter().map(|w| w.join().unwrap_or_else(|_| Err("a page could not be rendered".to_string()))).collect() + }); + let mut pages: Vec<(usize, PathBuf)> = Vec::with_capacity(count); + for result in results { + pages.extend(result?); } - Ok(pages) + pages.sort_by_key(|(index, _)| *index); + Ok(pages.into_iter().map(|(_, path)| path).collect()) } fn office_to_pdf(source: &Path, workspace: &Path) -> Result { @@ -127,6 +158,98 @@ fn office_renderers() -> Vec { } } +/// A printout being made off the window's thread: rendered, its document attached to the page, +/// and its pages copied into the page's folder. On a synced folder the copying alone took over a +/// second for fifteen pages, and the whole of it froze the page until it was done. +pub(crate) struct Job { + /// The page it is for, and the name of the document. + pub dir: PathBuf, + pub name: String, + /// How many pages are rendered, of how many, as last heard. + pub pages: (usize, usize), + news: std::sync::mpsc::Receiver, +} + +/// What a printout job is done with: the document's link in the page's folder and the links of +/// its pages, in order. +pub(crate) struct Made { + pub link: String, + pub images: Vec, +} + +enum News { + Pages(usize, usize), + Done(Result), +} + +impl Job { + /// Starts making a printout of `file` for the page in `dir`. + pub(crate) fn start(dir: &Path, file: &Path) -> Job { + let (tell, news) = std::sync::mpsc::channel(); + let (page, source) = (dir.to_path_buf(), file.to_path_buf()); + let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let job_name = name.clone(); + let spawned = std::thread::Builder::new().name("notecraft-printout".into()).spawn({ + let tell = tell.clone(); + move || { + let progress = std::sync::Mutex::new(tell.clone()); + let made = make(&page, &source, &job_name, &|done, total| { + if let Ok(tell) = progress.lock() { + let _ = tell.send(News::Pages(done, total)); + } + }); + let _ = tell.send(News::Done(made)); + } + }); + if let Err(e) = spawned { + let _ = tell.send(News::Done(Err(format!("cannot start making the printout: {e}")))); + } + Job { dir: dir.to_path_buf(), name, pages: (0, 0), news } + } + + /// What has happened since this was last asked: `Some` once the job is done. + pub(crate) fn poll(&mut self) -> Option> { + loop { + match self.news.try_recv() { + Ok(News::Pages(done, total)) => self.pages = (done, total), + Ok(News::Done(made)) => return Some(made), + Err(std::sync::mpsc::TryRecvError::Empty) => return None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => return Some(Err("the printout stopped before it was done".into())), + } + } + } +} + +/// Renders `source`, attaches it to the page in `dir`, and copies its pages into the page's +/// folder, taking them back out again if any could not be stored. +fn make(dir: &Path, source: &Path, name: &str, progress: &(dyn Fn(usize, usize) + Sync)) -> Result { + let rendered = render_with(source, progress)?; + let link = notecraft_store::assets::attach_file(dir, source) + .map_err(|_| crate::i18n::format_message_id("ui.could_not_attach_name_before_rendering_its_pages", &[("name", name)]))?; + let base = link + .strip_prefix("assets/") + .and_then(|link| Path::new(link).file_name()) + .map(|name| name.to_string_lossy().into_owned()) + .ok_or_else(|| crate::tl_id!("ui.the_attachment_returned_an_invalid_page_link").to_string())?; + let assets = dir.join("assets"); + let mut stored: Vec = Vec::with_capacity(rendered.pages().len()); + for (index, page) in rendered.pages().iter().enumerate() { + let target = assets.join(format!("{base}.printout-{:03}.png", index + 1)); + if let Err(error) = fs::copy(page, &target) { + for path in &stored { + let _ = fs::remove_file(path); + } + return Err(crate::i18n::format_message_id( + "ui.could_not_store_printout_page_page_error", + &[("page", &(index + 1).to_string()), ("error", &error.to_string())], + )); + } + stored.push(target); + } + let images = (1..=stored.len()).map(|n| format!("assets/{base}.printout-{n:03}.png")).collect(); + Ok(Made { link, images }) +} + fn temporary_workspace() -> Result { let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| format!("clock error: {e}"))?.as_nanos(); Ok(std::env::temp_dir().join(format!("notecraft-printout-{}-{stamp}", std::process::id()))) @@ -162,6 +285,58 @@ mod tests { fs::remove_dir_all(workspace).expect("remove temporary workspace"); } + /// The pages of a printout are rendered side by side, one thread to a core, and still come + /// out in the document's order. + #[test] + fn many_pages_render_side_by_side_in_order() { + let workspace = temporary_workspace().expect("temporary workspace"); + fs::create_dir_all(&workspace).expect("create temporary workspace"); + let pdf_path = workspace.join("colours.pdf"); + let colours = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 1.0, 0.0), (0.0, 1.0, 1.0), (1.0, 0.0, 1.0), (0.0, 0.0, 0.0)]; + fs::write(&pdf_path, pdf_of_colours(&colours)).expect("write sample PDF"); + let seen = std::sync::atomic::AtomicUsize::new(0); + let pages = super::render_pdf_with(&pdf_path, &workspace, &|done, total| { + assert_eq!(total, colours.len()); + seen.fetch_max(done, std::sync::atomic::Ordering::SeqCst); + }) + .expect("render"); + assert_eq!(pages.len(), colours.len()); + assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), colours.len(), "progress reached the last page"); + for (page, (r, g, b)) in pages.iter().zip(colours) { + let img = image::open(page).expect("a PNG").to_rgb8(); + let px = img.get_pixel(img.width() / 2, img.height() / 2).0; + let want = [(r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8]; + assert_eq!(px, want, "{page:?} is the page of that colour"); + } + fs::remove_dir_all(workspace).expect("remove temporary workspace"); + } + + /// A PDF of one page per colour, each filled with it. + fn pdf_of_colours(colours: &[(f32, f32, f32)]) -> Vec { + let n = colours.len(); + let mut objects = vec!["<< /Type /Catalog /Pages 2 0 R >>".to_owned()]; + let kids: Vec = (0..n).map(|i| format!("{} 0 R", 3 + 2 * i)).collect(); + objects.push(format!("<< /Type /Pages /Kids [{}] /Count {n} >>", kids.join(" "))); + for (i, (r, g, b)) in colours.iter().enumerate() { + let content = format!("{r} {g} {b} rg 0 0 200 200 re f"); + objects.push(format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents {} 0 R >>", 4 + 2 * i)); + objects.push(format!("<< /Length {} >>\nstream\n{}\nendstream", content.len(), content)); + } + let mut pdf = b"%PDF-1.4\n".to_vec(); + let mut offsets = vec![0usize]; + for (index, object) in objects.iter().enumerate() { + offsets.push(pdf.len()); + write!(pdf, "{} 0 obj\n{}\nendobj\n", index + 1, object).expect("write PDF object"); + } + let xref_offset = pdf.len(); + write!(pdf, "xref\n0 {}\n0000000000 65535 f \n", offsets.len()).expect("write PDF xref"); + for offset in offsets.iter().skip(1) { + writeln!(pdf, "{offset:010} 00000 n ").expect("write PDF xref entry"); + } + write!(pdf, "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n", offsets.len()).expect("write PDF trailer"); + pdf + } + fn minimal_pdf() -> Vec { let content = "BT /F1 12 Tf 72 720 Td (Hello) Tj ET"; let objects = [ diff --git a/i18n/ar-XB.tsv b/i18n/ar-XB.tsv index 1ea9a670..a50077d6 100644 --- a/i18n/ar-XB.tsv +++ b/i18n/ar-XB.tsv @@ -412,6 +412,8 @@ @id ui.make_subpage [[RLI]]$$$Make Subpage@@@[[PDI]] @id ui.make_the_page_larger [[RLI]]$$$Make the page larger@@@[[PDI]] @id ui.make_the_page_smaller [[RLI]]$$$Make the page smaller@@@[[PDI]] +@id ui.making_a_printout_of_name [[RLI]]$$$Making a printout of {name}…@@@[[PDI]] +@id ui.making_a_printout_of_name_page_done_of_total [[RLI]]$$$Making a printout of {name}: page {done} of {total}@@@[[PDI]] @id ui.many_thanks_to_its_authors_and_contributors [[RLI]]$$$— many thanks to its authors and contributors.@@@[[PDI]] @id ui.markdown [[RLI]]$$$Markdown@@@[[PDI]] @id ui.match_case [[RLI]]$$$Match case@@@[[PDI]] diff --git a/i18n/en-XA.tsv b/i18n/en-XA.tsv index d491d6bd..dc248ee0 100644 --- a/i18n/en-XA.tsv +++ b/i18n/en-XA.tsv @@ -412,6 +412,8 @@ @id ui.make_subpage $$$Make Subpage@@@ @id ui.make_the_page_larger $$$Make the page larger@@@ @id ui.make_the_page_smaller $$$Make the page smaller@@@ +@id ui.making_a_printout_of_name $$$Making a printout of {name}…@@@ +@id ui.making_a_printout_of_name_page_done_of_total $$$Making a printout of {name}: page {done} of {total}@@@ @id ui.many_thanks_to_its_authors_and_contributors $$$— many thanks to its authors and contributors.@@@ @id ui.markdown $$$Markdown@@@ @id ui.match_case $$$Match case@@@ diff --git a/i18n/en.tsv b/i18n/en.tsv index 2a2dc377..0a2b4e22 100644 --- a/i18n/en.tsv +++ b/i18n/en.tsv @@ -412,6 +412,8 @@ @id ui.make_subpage Make Subpage @id ui.make_the_page_larger Make the page larger @id ui.make_the_page_smaller Make the page smaller +@id ui.making_a_printout_of_name Making a printout of {name}… +@id ui.making_a_printout_of_name_page_done_of_total Making a printout of {name}: page {done} of {total} @id ui.many_thanks_to_its_authors_and_contributors — many thanks to its authors and contributors. @id ui.markdown Markdown @id ui.match_case Match case