From 0f8aff7290aa0ecb7e0ae5e8bd8b45b4c9983c8f Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 23:29:15 +0800 Subject: [PATCH] Embed project images in route-D previews and PDFs --- README.md | 2 +- crates/texrra-tex-core/src/lib.rs | 101 +++++++++++++++++++++ crates/texrra-tex-core/src/render.rs | 27 ++++++ docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 4 +- src/main.rs | 57 ++++++++++-- src/route_d.rs | 129 +++++++++++++++++++++++++-- tests/server.rs | 103 +++++++++++++++++++++ 8 files changed, 407 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 0aef739..e143f17 100644 --- a/README.md +++ b/README.md @@ -467,7 +467,7 @@ from the font's MATH assembly parts. `\\left...\\right` target sizing follows the assignable TeX parameters `\\delimiterfactor` (default 901) and `\\delimitershortfall` (default 5pt), including local and global assignments. -Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{}{}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt); a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay at the base size); starred headings stay unnumbered and an optional `[short]` title is dropped. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection`, `\listoffigures`/`\listoftables` reproduce the numbered captions, `verbatim` keeps monospaced source lines, `\href` keeps its link text and paints a PDF `/Link` URI annotation over the label, and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; a project's own `.sty`/`.cls` files are inlined for `\usepackage{name}`/`\documentclass{name}` with local `\RequirePackage` dependencies inlined recursively, local base classes named by `\LoadClass`/`\LoadClassWithOptions` inlined the same way, and package/class boilerplate dropped; local class and package files run their `\DeclareOption` code for the options named on `\documentclass[...]` / `\usepackage[...]` (with `\ExecuteOptions` defaults), and unknown paths stay as literal text. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit. `itemize`/`enumerate`/`description` environments nest arbitrarily: bullet labels cycle `•`/`–`/`*`, sub-enumerations use `(a)`, roman and upper-letter labels, description items keep their `[term]` as `term — `, an optional `\item[label]` replaces the generated marker, and each depth adds 12pt of indentation. +Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{}{}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt); a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay at the base size); starred headings stay unnumbered and an optional `[short]` title is dropped. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection`, `\listoffigures`/`\listoftables` reproduce the numbered captions, `verbatim` keeps monospaced source lines, `\href` keeps its link text and paints a PDF `/Link` URI annotation over the label, and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing files keep the rule placeholder). `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; a project's own `.sty`/`.cls` files are inlined for `\usepackage{name}`/`\documentclass{name}` with local `\RequirePackage` dependencies inlined recursively, local base classes named by `\LoadClass`/`\LoadClassWithOptions` inlined the same way, and package/class boilerplate dropped; local class and package files run their `\DeclareOption` code for the options named on `\documentclass[...]` / `\usepackage[...]` (with `\ExecuteOptions` defaults), and unknown paths stay as literal text. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit; PDF exports cache the last eight results and the cache key also covers decoded image bytes, so replacing an image re-renders both. `itemize`/`enumerate`/`description` environments nest arbitrarily: bullet labels cycle `•`/`–`/`*`, sub-enumerations use `(a)`, roman and upper-letter labels, description items keep their `[term]` as `term — `, an optional `\item[label]` replaces the generated marker, and each depth adds 12pt of indentation. Inline `$...$` and `\(...\)` math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal). `\newcommand`/`\renewcommand` definitions are captured from the preamble and expanded textually, including numbered arguments; TeX's `\def` parameter texts and `\let` aliases are executed the same way, and `\newenvironment` definitions wrap their bodies with the declared begin/end material. `\newif` flags select between `\if...\else...\fi` branches, with assignments honoured in the preamble or the body, so class conditionals like `\ifdraft` work. diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index dc9c6a0..b73337e 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -124,6 +124,12 @@ pub enum VerticalItem { height: i64, depth: i64, }, + /// A raster image painted into the vertical list. + Image { + width: i64, + height: i64, + image: crate::render::RasterImage, + }, } impl Halign { @@ -1824,6 +1830,10 @@ fn document_nodes( height: *height, depth: *depth, }, + VerticalItem::Image { height, .. } => VerticalNode::Box { + height: *height, + depth: 0, + }, VerticalItem::Paragraph(paragraph) => VerticalNode::Box { height: paragraph.height, depth: if paragraph.height > paragraph.depth { @@ -1883,6 +1893,7 @@ fn item_height(item: &VerticalItem) -> i64 { VerticalItem::Halign(halign) => halign.height, VerticalItem::Paragraph(paragraph) => paragraph.height, VerticalItem::Math { height, depth, .. } => height + depth, + VerticalItem::Image { height, .. } => *height, VerticalItem::Mark(_) | VerticalItem::Penalty(_) => 0, } } @@ -2629,6 +2640,31 @@ impl Engine { } current.items.push(item.clone()); } + VerticalItem::Image { height, .. } => { + if top_float_exceeds_page_fraction( + ¤t, + document.page_goal, + document.top_fraction_percent, + ) { + pages.push(std::mem::replace(&mut current, Page::empty())); + used = document.top_skip; + insertion_height = 0; + } + if current.items.is_empty() && !page_has_top_float_material(¤t) { + used = document.top_skip.max(*height); + } else if used + *height + > document.page_goal + - insertion_height + - bottom_float_area(¤t, document.text_float_sep) + { + pages.push(std::mem::replace(&mut current, Page::empty())); + used = document.top_skip.max(*height); + insertion_height = 0; + } else { + used += *height; + } + current.items.push(item.clone()); + } VerticalItem::Box(vertical_box) => { if top_float_exceeds_page_fraction( ¤t, @@ -3685,6 +3721,7 @@ impl Engine { VerticalItem::Halign(halign) => halign.height, VerticalItem::Paragraph(paragraph) => paragraph.height, VerticalItem::Math { height, depth, .. } => height + depth, + VerticalItem::Image { height, .. } => *height, }) .sum(); // A paragraph is rebuilt line by line, so it may fill the remaining @@ -3790,6 +3827,31 @@ impl Engine { } current.items.push(item.clone()); } + VerticalItem::Image { height, .. } => { + if top_float_exceeds_page_fraction( + ¤t, + next.page_goal, + next.top_fraction_percent, + ) { + pages.push(std::mem::replace(&mut current, Page::empty())); + used = next.top_skip; + insertion_height = 0; + } + if current.items.is_empty() && !page_has_top_float_material(¤t) { + used = next.top_skip.max(*height); + } else if used + *height + > next.page_goal + - insertion_height + - bottom_float_area(¤t, next.text_float_sep) + { + pages.push(std::mem::replace(&mut current, Page::empty())); + used = next.top_skip.max(*height); + insertion_height = 0; + } else { + used += *height; + } + current.items.push(item.clone()); + } VerticalItem::Box(vertical_box) => { if top_float_exceeds_page_fraction( ¤t, @@ -8800,6 +8862,45 @@ b & 2 \\ assert_eq!(hashes, fresh_hashes); } + #[test] + fn image_items_paint_rasters() { + let image = crate::render::RasterImage { + width: 2, + height: 2, + rgb: vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0], + }; + let document = Document::new( + 1000, + vec![Unit::vertical( + 1, + vec![VerticalItem::Image { + width: 50, + height: 40, + image, + }], + )], + ); + let layout = Engine::layout_paged(&document).expect("images are page-buildable"); + let display = layout.pages()[0].display_list(); + assert_eq!(display.images.len(), 1); + assert!(display.items.iter().any(|item| matches!( + item, + crate::render::DisplayItem::Image { + width, + height, + .. + } if *width == 50 && *height == 40 + ))); + let pdf = crate::pdf::display_lists_to_pdf_with_cm_type1( + &[display], + 1000, + 1000, + crate::pdf::PageOrigin::default(), + ); + let text = String::from_utf8_lossy(&pdf); + assert!(text.contains("/Subtype /Image")); + } + #[test] fn paged_layout_places_top_floats() { let document = Document::new( diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 36e4491..4b2eb86 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -79,6 +79,14 @@ pub enum DisplayItem { Special(String), } +/// A raster image carried by a vertical item, with its pixel data. +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct RasterImage { + pub width: u32, + pub height: u32, + pub rgb: Vec, +} + /// A raw RGB image that can be painted as a PDF XObject. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PdfImage { @@ -471,6 +479,25 @@ impl Page { VerticalItem::Box(box_) => { y += box_.height; } + VerticalItem::Image { + width, + height, + image, + } => { + let index = list.add_image(PdfImage { + width: (*width).max(0) as u32, + height: (*height).max(0) as u32, + rgb: image.rgb.clone(), + }); + list.push(DisplayItem::Image { + x: 0, + y, + width: *width, + height: *height, + index, + }); + y += *height; + } VerticalItem::Rule { width, height } => { list.push(DisplayItem::Rule { x: 0, diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 9c4adeb..0cbce2e 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and -PDF opt-in with `?engine=route-d`). 699 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 702 workspace tests are green and no oracle fixture is ignored. Status after G1 (P0-P2): the paragraph model reproduces TeX's passes, diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index e683e37..333046c 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -133,7 +133,7 @@ and justification. | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), though `\valign`, nested tables and full tabular parity remain open | | M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`, with `cmmi10`, `cmsy10` and `cmex10` glyphs embedded as Type1 outlines), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an approximation of TeX's `\split` behaviour; `align`/`align*` displays share column widths and number each row, while `gather`/`gather*` centre every row); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation, with `1mu` = `1/18em` (a thin space is 3mu = 1.67pt at 10pt); `\mid` is a relation while `\colon` is punctuation; `\mskip`, `\mkern`, `\mspace`, `\hskip`, `\kern` and `\hspace` scan TeX dimensions (`mu`, `pt`, `em`, ...) and contribute their natural width, accepting `plus`/`minus` parts even though math boxes are not glue lists; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it; math italic letters are embedded as Computer Modern Type1 outlines (`cmmi10`), and math alphabets map `\\mathbf`/`\\mathit`/`\\mathsf`/`\\mathtt` onto the bold, math-italic, sans and mono faces with their TFMs and `\\mathcal` onto the cmsy10 calligraphic capitals; `\mathfrak` maps onto the bundled eufm10 Fraktur letters (embedded as Type1 outlines); infix fractions `\over`, `\atop`, `\choose`, `\brace`, `\brack` and their `withdelims` forms build fractions from the current row, with the bar only for the `\over` forms; `\middle` delimiters are sized with their enclosing `\left`/`\right` group and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size | | M5 | NFSS/TFM metrics, CM/Latin Modern | **partial**: paragraph-level NFSS declarations and inline run composition over the built-in Roman/Bold/Italic/BoldItalic/Mono/MonoItalic/Sans/SansBold/SansItalic/SmallCaps/Slanted/BoldSlanted faces (CM has no sans bold-italic, so `cmss/bx/it` substitutes `cmss/bx/n`; `\scshape` selects cmcsc10 and a bold small caps request falls back to cmbx10; `\slshape` uses the slanted cmsl10 rather than the italic cmti10 and `\ttfamily\itshape` reaches cmitt10), per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, `cmsy10` math symbols and `cmex10` big operators, with Liberation subsets used only as a fallback for characters outside the Type1 encodings; paragraph base sizes from `\fontsize` and the article size commands scale glyph metrics and the default interline glue while the measure and authored skips stay absolute, and a size command in the middle of a paragraph splits a sized run that is shaped and painted at its own type size; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open | -| M6 | class/package execution (`article`, `sn-jnl`) | **partial**: `\documentclass[...]` options are read and the article `10pt`/`11pt`/`12pt` base size sets the default paragraph font size and `\baselineskip` (13.6pt/14.5pt); the `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom` options (and `\geometry{...}`) adjust the measure and page height; `\title`/`\author`/`\date` are captured, `\today` expands to the UTC calendar date in the title block and the body, and `\maketitle` expands into the centered article title block at the class sizes (with today's date when `\date` is absent and no date for `\date{}`); numbered `\section`/`\subsection`/`\subsubsection`/`\paragraph`/`\subparagraph` headings advance five-level article counters and paint at `\Large`/`\large`/`\normalsize` (the two deepest levels stay bold at the base size), starred headings stay unnumbered, and an optional `[short]` title is dropped; the `abstract` environment expands into a centered bold heading and a 9pt body, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or on its own line after it) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\appendix` restarts sectioning with letters (`A`, `A.1`), and `\tableofcontents` lists the numbered headings through `\subsubsection` with 12pt per-level indentation while `\listoffigures`/`\listoftables` reproduce the numbered figure/table captions; `verbatim` environments keep each source line as a monospaced 9pt paragraph indented by 12pt (leading whitespace is normalised), `\href{url}{text}` keeps its text, and `\url{...}` becomes typewriter text; `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics[width=...,height=...]` reserves a rule placeholder; a `table` environment becomes a float that carries its captured `tabular` body and a numbered `Table n:` caption whose text sits above the tabular as in LaTeX, while `\caption*` stays unnumbered for either float kind; `theorem`/`lemma`/`corollary`/`proposition`/`definition`/`example`/`remark`/`proof` environments get a bold numbered heading (optionally with `[title]`), italic statements for the theorem group, an unnumbered proof, and `\label`/`\ref` targets; `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` define custom environments with shared counters and section-scoped numbers; `itemize`/`enumerate`/`description` lists nest with depth-aware bullets (`•`, `–`, `*`), lettered/roman sub-labels and 12pt-per-level indentation, and an optional `\item[label]` overrides the generated marker; `\def\name#1{...}` parameter texts and `\let\alias=\other` aliases are executed as textual definitions; `\newenvironment{name}[n]{begin}{end}` definitions expand their begin/end codes around the environment body, with numbered arguments available in both; `\newif\ifname` flags default to false and `\nametrue`/`\namefalse` assignments, whether in the preamble or the body, select between `\ifname ... \else ... \fi` branches; project previews and PDF exports expand `\input{...}`/`\include{...}` from the project's files (the `.tex` suffix may be omitted) while unknown files stay literal text, and inline a project's own `.sty` files for `\usepackage{name}` and `.cls` files for `\documentclass` (rewritten to `article` with the original options kept), recursively inlining local `\RequirePackage` dependencies (up to eight levels, cycles skipped), dropping package/class boilerplate (`\ProvidesPackage`/`\ProvidesClass`, `\NeedsTeXFormat`, `\RequirePackage`) and inlining local base classes requested with `\LoadClass`/`\LoadClassWithOptions` (unknown bases keep LaTeX's article fallback); local class and package files execute their `\DeclareOption`/`\ExecuteOptions`/`\ProcessOptions` subset, so options named on `\documentclass[...]` or `\usepackage[...]` run their declaration code and `\ExecuteOptions` supplies defaults; a full class layout implementation and arbitrary package code remain open | +| M6 | class/package execution (`article`, `sn-jnl`) | **partial**: `\documentclass[...]` options are read and the article `10pt`/`11pt`/`12pt` base size sets the default paragraph font size and `\baselineskip` (13.6pt/14.5pt); the `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom` options (and `\geometry{...}`) adjust the measure and page height; `\title`/`\author`/`\date` are captured, `\today` expands to the UTC calendar date in the title block and the body, and `\maketitle` expands into the centered article title block at the class sizes (with today's date when `\date` is absent and no date for `\date{}`); numbered `\section`/`\subsection`/`\subsubsection`/`\paragraph`/`\subparagraph` headings advance five-level article counters and paint at `\Large`/`\large`/`\normalsize` (the two deepest levels stay bold at the base size), starred headings stay unnumbered, and an optional `[short]` title is dropped; the `abstract` environment expands into a centered bold heading and a 9pt body, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or on its own line after it) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\appendix` restarts sectioning with letters (`A`, `A.1`), and `\tableofcontents` lists the numbered headings through `\subsubsection` with 12pt per-level indentation while `\listoffigures`/`\listoftables` reproduce the numbered figure/table captions; `verbatim` environments keep each source line as a monospaced 9pt paragraph indented by 12pt (leading whitespace is normalised), `\href{url}{text}` keeps its text, and `\url{...}` becomes typewriter text; `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics[width=...,height=...]` embeds the referenced project image (PNG/JPEG/BMP are decoded into a PDF XObject, with a rule placeholder when the file is missing); a `table` environment becomes a float that carries its captured `tabular` body and a numbered `Table n:` caption whose text sits above the tabular as in LaTeX, while `\caption*` stays unnumbered for either float kind; `theorem`/`lemma`/`corollary`/`proposition`/`definition`/`example`/`remark`/`proof` environments get a bold numbered heading (optionally with `[title]`), italic statements for the theorem group, an unnumbered proof, and `\label`/`\ref` targets; `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` define custom environments with shared counters and section-scoped numbers; `itemize`/`enumerate`/`description` lists nest with depth-aware bullets (`•`, `–`, `*`), lettered/roman sub-labels and 12pt-per-level indentation, and an optional `\item[label]` overrides the generated marker; `\def\name#1{...}` parameter texts and `\let\alias=\other` aliases are executed as textual definitions; `\newenvironment{name}[n]{begin}{end}` definitions expand their begin/end codes around the environment body, with numbered arguments available in both; `\newif\ifname` flags default to false and `\nametrue`/`\namefalse` assignments, whether in the preamble or the body, select between `\ifname ... \else ... \fi` branches; project previews and PDF exports expand `\input{...}`/`\include{...}` from the project's files (the `.tex` suffix may be omitted) while unknown files stay literal text, and inline a project's own `.sty` files for `\usepackage{name}` and `.cls` files for `\documentclass` (rewritten to `article` with the original options kept), recursively inlining local `\RequirePackage` dependencies (up to eight levels, cycles skipped), dropping package/class boilerplate (`\ProvidesPackage`/`\ProvidesClass`, `\NeedsTeXFormat`, `\RequirePackage`) and inlining local base classes requested with `\LoadClass`/`\LoadClassWithOptions` (unknown bases keep LaTeX's article fallback); local class and package files execute their `\DeclareOption`/`\ExecuteOptions`/`\ProcessOptions` subset, so options named on `\documentclass[...]` or `\usepackage[...]` run their declaration code and `\ExecuteOptions` supplies defaults; a full class layout implementation and arbitrary package code remain open | | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | ## Current limits @@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 405 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 699 tests (406 route-D unit, 128 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 46 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 407 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 702 tests (407 route-D unit, 129 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 47 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo diff --git a/src/main.rs b/src/main.rs index 6fe7ada..24d6613 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,5 @@ use std::{ - collections::hash_map::DefaultHasher, + collections::{HashMap, hash_map::DefaultHasher}, env, fmt::Write as _, fs, @@ -809,9 +809,22 @@ fn store_route_d_pdf(key: (String, u64), pdf: &[u8]) { } } -fn route_d_cache_key(id: &str, source: &str) -> (String, u64) { +fn route_d_cache_key( + id: &str, + source: &str, + images: &HashMap, +) -> (String, u64) { let mut hasher = DefaultHasher::new(); source.hash(&mut hasher); + let mut names: Vec<&String> = images.keys().collect(); + names.sort(); + for name in names { + name.hash(&mut hasher); + let image = &images[name]; + image.width.hash(&mut hasher); + image.height.hash(&mut hasher); + image.rgb.hash(&mut hasher); + } (id.to_string(), hasher.finish()) } @@ -878,6 +891,36 @@ fn expand_project_source(source: &str, store: &projects::ProjectStore, id: &str) expand_project_inputs(&expanded, store, id) } +/// Decode every `\includegraphics` file a project source references. +fn load_project_images( + source: &str, + store: &projects::ProjectStore, + id: &str, +) -> HashMap { + let mut images = HashMap::new(); + for path in route_d::image_paths(source) { + let Ok(bytes) = store + .read_file(id, &path) + .or_else(|_| store.read_file(id, &format!("{path}.png"))) + else { + continue; + }; + let Ok(decoded) = image::load_from_memory(&bytes) else { + continue; + }; + let rgb = decoded.to_rgb8(); + images.insert( + path, + route_d::RasterImage { + width: rgb.width(), + height: rgb.height(), + rgb: rgb.into_raw(), + }, + ); + } + images +} + fn expand_project_inputs(source: &str, store: &projects::ProjectStore, id: &str) -> String { let read = |path: &str| { let bytes = store @@ -981,11 +1024,12 @@ fn handle_project_request( }; if uses_route_d(url) { let expanded = expand_project_source(&source, &store, id); - let key = route_d_cache_key(id, &expanded); + let images = load_project_images(&expanded, &store, id); + let key = route_d_cache_key(id, &expanded, &images); if let Some(json) = route_d_cached_preview(&key) { return respond_json(request, 200, &preview_without_changes(&json)); } - return match route_d::project_preview_json(id, &expanded) { + return match route_d::project_preview_json_with_images(id, &expanded, &images) { Ok(json) => { store_route_d_preview(key, json.clone()); respond_json(request, 200, &json) @@ -1010,11 +1054,12 @@ fn handle_project_request( }; if uses_route_d(url) { let expanded = expand_project_source(&source, &store, id); - let key = route_d_cache_key(id, &expanded); + let images = load_project_images(&expanded, &store, id); + let key = route_d_cache_key(id, &expanded, &images); if let Some(pdf) = route_d_cached_pdf(&key) { return respond_pdf_with_cache(request, pdf, "hit"); } - return match route_d::pdf_bytes(&expanded) { + return match route_d::pdf_bytes_with_images(&expanded, &images) { Ok(pdf) => { store_route_d_pdf(key, &pdf); respond_pdf_with_cache(request, pdf, "miss") diff --git a/src/route_d.rs b/src/route_d.rs index 1d00782..8ddab7f 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -12,6 +12,7 @@ use std::sync::{Mutex, OnceLock}; use texrra_tex_core::cmr10::Cmr10Metrics; use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines}; use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1}; +pub use texrra_tex_core::render::RasterImage; use texrra_tex_core::{ Document, Engine, FloatPlacement, InsertionClass, ParagraphFont, ParagraphStyle, Unit, VerticalItem, @@ -45,8 +46,19 @@ fn latex_body(source: &str) -> &str { /// paragraph list is unchanged and applies each changed paragraph through /// `Engine::edit`, starting from the earliest changed paragraph. Structural /// edits fall back to a full layout. The v1 project preview remains the default. +#[allow(dead_code)] // Kept as the no-image entry point for callers and tests. pub fn project_preview_json(project_id: &str, source: &str) -> Result { - let (body, geometry) = geometry_and_body(source); + project_preview_json_with_images(project_id, source, &HashMap::new()) +} + +/// Project preview with project images decoded into raster data. +pub fn project_preview_json_with_images( + project_id: &str, + source: &str, + images: &HashMap, +) -> Result { + let (body, mut geometry) = geometry_and_body(source); + geometry.images = images.clone(); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); @@ -171,6 +183,8 @@ struct PageGeometry { environments: Vec, /// `\newif` boolean flags declared in the preamble. conditionals: Vec, + /// Decoded images keyed by `\includegraphics` path. + images: HashMap, } /// A `\newtheorem` declaration: display name, shared counter and section scope. @@ -1509,7 +1523,16 @@ pub fn preview_json(source: &str) -> Result { /// Render the same checkpointed document as a route-D PDF. pub fn pdf_bytes(source: &str) -> Result, String> { - let (body, geometry) = geometry_and_body(source); + pdf_bytes_with_images(source, &HashMap::new()) +} + +/// Render a route-D PDF with decoded project images. +pub fn pdf_bytes_with_images( + source: &str, + images: &HashMap, +) -> Result, String> { + let (body, mut geometry) = geometry_and_body(source); + geometry.images = images.clone(); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); @@ -1642,6 +1665,8 @@ struct FloatSpec { height: Option, caption: Option, caption_starred: bool, + /// `\includegraphics` path for a figure. + image: Option, /// Index into `PageGeometry::tabular` for a captured table body. table: Option, } @@ -1737,6 +1762,7 @@ where expanded } +#[cfg_attr(not(test), allow(dead_code))] fn paragraphs(source: &str) -> Result, String> { paragraphs_with_definitions(source, &[]) } @@ -1936,7 +1962,7 @@ fn float_block(raw: &str) -> Option { } caption = Some(text); } - let (width, height) = figure_graphic(inner).unwrap_or((None, None)); + let (width, height, image) = figure_graphic(inner).unwrap_or((None, None, None)); let table = embedded_table(inner); Some(SourceParagraph { text: String::new(), @@ -1967,6 +1993,7 @@ fn float_block(raw: &str) -> Option { height, caption, caption_starred, + image, table, }), }) @@ -2024,8 +2051,8 @@ fn figure_labels(inner: &str) -> Vec { labels } -/// Read the placeholder dimensions from an `\includegraphics` option list. -fn figure_graphic(inner: &str) -> Option<(Option, Option)> { +/// Read the path and placeholder dimensions from an `\includegraphics`. +fn figure_graphic(inner: &str) -> Option<(Option, Option, Option)> { let index = inner.find("\\includegraphics")?; let after = inner[index + "\\includegraphics".len()..].trim_start(); let (options, after) = match after.strip_prefix('[') { @@ -2035,7 +2062,7 @@ fn figure_graphic(inner: &str) -> Option<(Option, Option)> { } None => ("", after), }; - let (_, _) = braced_group(after)?; + let (path, _) = braced_group(after)?; let mut width = None; let mut height = None; for part in options.split(',') { @@ -2046,7 +2073,33 @@ fn figure_graphic(inner: &str) -> Option<(Option, Option)> { height = parse_dimension(value.trim()); } } - Some((width, height)) + let path = path.trim(); + Some((width, height, (!path.is_empty()).then(|| path.to_string()))) +} + +/// Every distinct `\includegraphics` path in a source file. +pub fn image_paths(source: &str) -> Vec { + let mut paths: Vec = Vec::new(); + let mut rest = source; + while let Some(index) = rest.find("\\includegraphics") { + let after = rest[index + "\\includegraphics".len()..].trim_start(); + let after = match after.strip_prefix('[') { + Some(options) => match options.find(']') { + Some(end) => options[end + 1..].trim_start(), + None => break, + }, + None => after, + }; + let Some((path, consumed)) = braced_group(after) else { + break; + }; + let path = path.trim(); + if !path.is_empty() && !paths.iter().any(|existing| existing == path) { + paths.push(path.to_string()); + } + rest = &after[consumed..]; + } + paths } const THEOREM_ENVIRONMENTS: [&str; 8] = [ @@ -2746,6 +2799,7 @@ fn font_size_command(rest: &str) -> Option<(i64, &str)> { Some((size, after)) } +#[cfg_attr(not(test), allow(dead_code))] fn nfss_font(raw: &str, base: ParagraphFont) -> Option<(ParagraphFont, String)> { nfss_font_with_size(raw, base).map(|(font, _, body)| (font, body)) } @@ -4215,7 +4269,26 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do content.extend(caption.items.clone()); } } - if spec.height.is_some() || spec.width.is_some() { + let mut placed_image = false; + if let Some(path) = &spec.image { + if let Some(image) = geometry.images.get(path) { + let image_width = spec.width.unwrap_or(width).min(width); + let image_height = spec.height.unwrap_or_else(|| { + if image.width > 0 { + (image_width * image.height as i64 / image.width as i64).max(1) + } else { + image_width / 2 + } + }); + content.push(VerticalItem::Image { + width: image_width, + height: image_height, + image: image.clone(), + }); + placed_image = true; + } + } + if !placed_image && (spec.height.is_some() || spec.width.is_some()) { let rule_width = spec.width.unwrap_or(width).min(width); let rule_height = spec.height.unwrap_or(rule_width / 2); content.push(VerticalItem::Rule { @@ -4743,6 +4816,46 @@ mod source_tests { assert_eq!(document.units[0].source, "See 1."); } + #[test] + fn figure_graphics_place_decoded_images() { + let blocks = paragraphs( + "\\begin{figure}[t]\n\\includegraphics[width=120pt]{plot.png}\n\\caption{Plot}\n\\end{figure}", + ) + .expect("paragraphs"); + let mut geometry = PageGeometry::default(); + geometry.images.insert( + "plot.png".to_string(), + RasterImage { + width: 200, + height: 100, + rgb: vec![7; 200 * 100 * 3], + }, + ); + let document = build_document(&blocks, &geometry); + let image = document + .units + .iter() + .flat_map(|unit| &unit.items) + .find_map(|item| match item { + VerticalItem::Float(float) => { + float.content.iter().find_map(|content| match content { + VerticalItem::Image { + width, + height, + image, + } => Some((*width, *height, image.clone())), + _ => None, + }) + } + _ => None, + }) + .expect("decoded image in the float"); + assert_eq!(image.0, 120 * SCALE); + assert_eq!(image.1, 60 * SCALE); + assert_eq!(image.2.width, 200); + assert_eq!(image.2.rgb.len(), 200 * 100 * 3); + } + #[test] fn figure_graphics_reserve_a_placeholder() { let source = "\\begin{figure}[b]\n\\includegraphics[width=200pt]{plot.pdf}\\caption{Plot}\n\\end{figure}"; diff --git a/tests/server.rs b/tests/server.rs index fc9b43c..bce7eea 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -1630,3 +1630,106 @@ fn route_d_preview_reports_declared_paper_size() { &text[..200.min(text.len())] ); } + +/// A tiny 2x2 24-bit BMP for image embedding tests. +fn two_by_two_bmp() -> Vec { + let pixel_bytes: u32 = 16; + let file_size: u32 = 54 + pixel_bytes; + let mut bytes = Vec::new(); + bytes.extend_from_slice(b"BM"); + bytes.extend_from_slice(&file_size.to_le_bytes()); + bytes.extend_from_slice(&[0, 0, 0, 0]); + bytes.extend_from_slice(&54u32.to_le_bytes()); + bytes.extend_from_slice(&40u32.to_le_bytes()); + bytes.extend_from_slice(&2i32.to_le_bytes()); + bytes.extend_from_slice(&2i32.to_le_bytes()); + bytes.extend_from_slice(&1u16.to_le_bytes()); + bytes.extend_from_slice(&24u16.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&pixel_bytes.to_le_bytes()); + bytes.extend_from_slice(&2835i32.to_le_bytes()); + bytes.extend_from_slice(&2835i32.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + for row in [[0u8, 0, 255, 0, 255, 0], [255, 0, 0, 255, 255, 255]] { + bytes.extend_from_slice(&row); + bytes.extend_from_slice(&[0, 0]); + } + bytes +} + +#[test] +fn project_preview_and_pdf_embed_images() { + let server = TestServer::start("route-d-image"); + let image = two_by_two_bmp(); + let put = server.request( + "PUT", + "/api/projects/hello/file?path=pixel.bmp", + &image, + "image/bmp", + ); + assert_eq!(put.status, 200, "{}", put.text()); + let main = "\\documentclass{article}\n\\begin{document}\n\\begin{figure}[t]\n\\includegraphics[width=120pt]{pixel.bmp}\n\\caption{Pixel}\n\\end{figure}\n\\end{document}\n"; + let put = server.request( + "PUT", + "/api/projects/hello/file?path=hello.tex", + main.as_bytes(), + "text/plain; charset=utf-8", + ); + assert_eq!(put.status, 200, "{}", put.text()); + + let preview = server.request( + "POST", + "/api/projects/hello/preview?engine=route-d", + &[], + "application/json", + ); + assert_eq!(preview.status, 200, "{}", preview.text()); + let svg = preview.text(); + assert!(svg.contains(r##"fill=\"#cccccc\""##), "preview: {svg}"); + assert!(svg.contains(">P"), "preview: {svg}"); + + let pdf = server.request( + "POST", + "/api/projects/hello/pdf?engine=route-d", + &[], + "application/pdf", + ); + assert_eq!(pdf.status, 200); + assert!( + pdf.body + .windows("/Subtype /Image".len()) + .any(|window| window == b"/Subtype /Image"), + "pdf should embed the raster image" + ); + + let mut changed = two_by_two_bmp(); + changed[54] ^= 0xff; + let put = server.request( + "PUT", + "/api/projects/hello/file?path=pixel.bmp", + &changed, + "image/bmp", + ); + assert_eq!(put.status, 200, "{}", put.text()); + let preview = server.request( + "POST", + "/api/projects/hello/preview?engine=route-d", + &[], + "application/json", + ); + assert_eq!(preview.status, 200, "{}", preview.text()); + assert!( + preview.text().contains("\"recomputedPages\":1"), + "editing the image should invalidate the preview cache: {}", + preview.text() + ); + let pdf = server.request( + "POST", + "/api/projects/hello/pdf?engine=route-d", + &[], + "application/pdf", + ); + assert_eq!(pdf.status, 200); + assert_eq!(pdf.header("x-texrra-cache"), Some("miss")); +}