Embed project images in route-D previews and PDFs
This commit is contained in:
1 parent
ae69eba64d
commit
0f8aff7290
8 files changed
+407
-18
No files matched your search
+51
-6
@@ -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, route_d::RasterImage>,
|
||||
) -> (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<String, route_d::RasterImage> {
|
||||
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")
|
||||
|
||||
+121
-8
@@ -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<String, String> {
|
||||
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<String, RasterImage>,
|
||||
) -> Result<String, 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);
|
||||
@@ -171,6 +183,8 @@ struct PageGeometry {
|
||||
environments: Vec<EnvironmentDefinition>,
|
||||
/// `\newif` boolean flags declared in the preamble.
|
||||
conditionals: Vec<ConditionalDefinition>,
|
||||
/// Decoded images keyed by `\includegraphics` path.
|
||||
images: HashMap<String, RasterImage>,
|
||||
}
|
||||
|
||||
/// A `\newtheorem` declaration: display name, shared counter and section scope.
|
||||
@@ -1509,7 +1523,16 @@ pub fn preview_json(source: &str) -> Result<String, String> {
|
||||
|
||||
/// Render the same checkpointed document as a route-D PDF.
|
||||
pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, 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<String, RasterImage>,
|
||||
) -> Result<Vec<u8>, 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<i64>,
|
||||
caption: Option<String>,
|
||||
caption_starred: bool,
|
||||
/// `\includegraphics` path for a figure.
|
||||
image: Option<String>,
|
||||
/// Index into `PageGeometry::tabular` for a captured table body.
|
||||
table: Option<usize>,
|
||||
}
|
||||
@@ -1737,6 +1762,7 @@ where
|
||||
expanded
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
|
||||
paragraphs_with_definitions(source, &[])
|
||||
}
|
||||
@@ -1936,7 +1962,7 @@ fn float_block(raw: &str) -> Option<SourceParagraph> {
|
||||
}
|
||||
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<SourceParagraph> {
|
||||
height,
|
||||
caption,
|
||||
caption_starred,
|
||||
image,
|
||||
table,
|
||||
}),
|
||||
})
|
||||
@@ -2024,8 +2051,8 @@ fn figure_labels(inner: &str) -> Vec<String> {
|
||||
labels
|
||||
}
|
||||
|
||||
/// Read the placeholder dimensions from an `\includegraphics` option list.
|
||||
fn figure_graphic(inner: &str) -> Option<(Option<i64>, Option<i64>)> {
|
||||
/// Read the path and placeholder dimensions from an `\includegraphics`.
|
||||
fn figure_graphic(inner: &str) -> Option<(Option<i64>, Option<i64>, Option<String>)> {
|
||||
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<i64>, Option<i64>)> {
|
||||
}
|
||||
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<i64>, Option<i64>)> {
|
||||
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<String> {
|
||||
let mut paths: Vec<String> = 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}";
|
||||
|
||||
Reference in new issue
Block a user