Retain XeTeX image lookup paths in native formats

This commit is contained in:
gloamxun committed 2026-11-28 01:06:12 +08:00
1 parent 6a118d3b60
commit c2e1e64a60
10 files changed
+208 -54

No files matched your search

@@ -10,7 +10,7 @@ pub(super) struct RegisteredImage {
image: Arc<PdfImageUse>,
attributes: Option<Vec<Token>>,
saved: Option<FormatPdfImage>,
pending_xdv: Option<FormatImageKind>,
pending_xdv: Option<(FormatImageKind, std::path::PathBuf)>,
}
impl Executor {
@@ -31,7 +31,9 @@ impl Executor {
attributes: (!matches!(saved.kind, FormatImageKind::XdvShippedSpecial))
.then(|| saved.attributes.clone()),
saved: None,
pending_xdv: (!saved.kind.reads_at_load()).then_some(saved.kind),
pending_xdv: (!saved.kind.reads_at_load()).then(|| {
(saved.kind, saved.xdv_file.as_deref().unwrap_or_else(|| saved.path()).into())
}),
}
}).collect();
self.format_image_warnings = warnings;
@@ -371,7 +373,7 @@ impl Executor {
return self.fail("XeTeX image is illegal in math mode");
}
let (name, from) = self.xdv_image_filename(token, files)?;
let (image, source_origin, page, format_kind) = if pdf {
let (page, format_kind) = if pdf {
let page = if self.keyword("page", files)? {
self.integer(files)?
} else {
@@ -390,17 +392,27 @@ impl Executor {
break;
}
}
(page, FormatImageKind::XdvPdf { page_box: box_type })
} else {
(0, FormatImageKind::XdvRaster)
};
let (resource, format_path) = if self.state.is_initex() {
let (resource, path) = files
.resource_with_lookup_path(ResourceKind::PdfImage, &name, &from)
.map_err(|message| self.error(message, token.span))?;
(resource, Some(path))
} else {
let resource = files
.resource(ResourceKind::PdfImage, &name, &from)
.map_err(|message| self.error(message, token.span))?;
let (image, source_origin) = PdfImage::read_xdv(resource, page, box_type)
(resource, None)
};
let (image, source_origin) = if let FormatImageKind::XdvPdf { page_box } = format_kind {
let (image, origin) = PdfImage::read_xdv(resource, page, page_box)
.map_err(|message| self.error(message, token.span))?;
(Arc::new(image), source_origin, page, FormatImageKind::XdvPdf { page_box: box_type })
(Arc::new(image), origin)
} else {
(
self.xdv_raster_source(&name, &from, token.span, files)?,
[0.0; 2], 0, FormatImageKind::XdvRaster,
)
(self.decode_xdv_raster(resource, token.span)?, [0.0; 2])
};
let mut placement = XdvImagePlacement::new(&image, source_origin);
loop {
@@ -432,7 +444,11 @@ impl Executor {
let image = PdfImageUse::new_xdv(self.pdf_images.len() + 1, image, placement, page)
.map_err(|message| self.error(message, token.span))?;
let image = Arc::new(image);
let saved = self.state.is_initex().then(|| FormatPdfImage::capture(&image, &[], format_kind));
let saved = format_path.map(|path| {
let mut saved = FormatPdfImage::capture(&image, &[], format_kind);
saved.xdv_file = Some(path);
saved
});
self.pdf_images.push(RegisteredImage {
image: image.clone(),
attributes: Some(Vec::new()),
@@ -442,16 +458,11 @@ impl Executor {
self.defer_image(image, token)
}
fn xdv_raster_source(
fn decode_xdv_raster(
&self,
name: &str,
from: &str,
resource: crate::resources::LoadedResource,
span: Span,
files: &mut impl SourceProvider,
) -> Result<Arc<PdfImage>, Error> {
let resource = files
.resource(ResourceKind::PdfImage, name, from)
.map_err(|message| self.error(message, span))?;
// A layout measurement and later shipout share the decoded pixels
// only if the resource provider returns the same version.
if let Some(registered) = self.pdf_images.iter().rev().find(|registered| {
@@ -491,7 +502,10 @@ impl Executor {
name: special.file.clone(),
from: from.clone(),
});
let resource = self.xdv_raster_source(&special.file, &from, span, files)?;
let resource = files
.resource(ResourceKind::PdfImage, &special.file, &from)
.map_err(|message| self.error(message, span))?;
let resource = self.decode_xdv_raster(resource, span)?;
let image = special.place(self.pdf_images.len() + 1, resource)
.map_err(|error| self.error(error, span))?;
let image = Arc::new(image);
@@ -515,8 +529,8 @@ impl Executor {
pub(super) fn declare_pdf_image(
&mut self, id: usize, files: &mut impl SourceProvider,
) -> Result<(), Error> {
if let Some(kind) = self.pdf_images[id - 1].pending_xdv {
self.open_format_xdv_image(id, kind, files)?;
if self.pdf_images[id - 1].pending_xdv.is_some() {
self.open_format_xdv_image(id, files)?;
}
let registered = &mut self.pdf_images[id - 1];
let Some(tokens) = registered.attributes.take() else {
@@ -595,20 +609,21 @@ impl Executor {
fn open_format_xdv_image(
&mut self,
id: usize,
kind: FormatImageKind,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let saved = &self.pdf_images[id - 1].image;
let path = saved.image.version.path.to_string_lossy();
let registered = &self.pdf_images[id - 1];
let (kind, path) = registered.pending_xdv.as_ref().expect("pending XDV image");
let path = path.to_str().ok_or_else(|| self.error("XDV image path is not UTF-8", self.current))?;
let saved = &registered.image;
let from = self.source_name(self.current);
self.reads.insert(Dependency::FileLookup {
name: path.to_string(),
from: from.clone(),
});
let resource = files.resource(ResourceKind::PdfImage, &path, &from)
let resource = files.resource(ResourceKind::PdfImage, path, &from)
.map_err(|message| self.error(message, self.current))?;
let page = saved.xdv.as_ref().expect("registered XDV placement").page_request;
let actual = match kind {
let actual = match *kind {
FormatImageKind::XdvPdf { page_box } => {
PdfImage::read_xdv(resource, page, page_box).map(|(image, _)| image)
}
@@ -14,9 +14,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 91;
const COMPATIBLE_SCHEMAS: [u32; 57] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, SCHEMA,
const SCHEMA: u32 = 92;
const COMPATIBLE_SCHEMAS: [u32; 58] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -61,8 +61,8 @@ struct Envelope {
}
impl FormatImage {
/// The format reopens its declared images by resolved path in the new
/// job. Keep version checks for all other reads, including a path also
/// The format reopens its declared images in the new job. Keep version
/// checks for all other reads, including a path also
/// used in some other role during the dump.
pub fn from_dump_with_trace(execution: Execution, trace: &ResourceTrace) -> Result<Self, String> {
let mut resources = trace.reads.clone();
@@ -221,9 +221,15 @@ impl FormatImage {
image.schema >= 89 && saved.kind == FormatImageKind::Png
&& pdf_objects.is_some_and(|objects| objects.is_png_group(group))
});
let valid_xdv_file = saved.xdv_file.as_ref().is_none_or(|path| {
image.schema >= 92
&& matches!(saved.kind, FormatImageKind::XdvPdf { .. } | FormatImageKind::XdvRaster)
&& !path.as_os_str().is_empty()
});
if !valid_profile
|| !valid_number
|| !valid_group
|| !valid_xdv_file
|| saved.image.id != index + 1
|| saved.path().as_os_str().is_empty()
{
@@ -7,7 +7,7 @@ use crate::{
resources::{LoadedResource, ResourceVersion},
};
use serde::{Deserialize, Serialize};
use std::{path::Path, sync::Arc};
use std::{path::{Path, PathBuf}, sync::Arc};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(in crate::execution) enum FormatImageKind {
@@ -32,6 +32,8 @@ pub(in crate::execution) struct FormatPdfImage {
pub image: Arc<PdfImageUse>,
pub attributes: Vec<Token>,
pub kind: FormatImageKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub xdv_file: Option<PathBuf>,
}
impl FormatPdfImage {
@@ -47,10 +49,11 @@ impl FormatPdfImage {
}),
attributes: attributes.to_vec(),
kind,
xdv_file: None,
}
}
pub(super) fn path(&self) -> &Path {
pub(in crate::execution) fn path(&self) -> &Path {
&self.image.image.version.path
}
@@ -249,6 +249,17 @@ pub trait SourceProvider {
) -> Result<crate::resources::LoadedResource, String> {
Err("host binary resource lookup unavailable".into())
}
/// Retain the lookup spelling when a format defers reopening the resource.
fn resource_with_lookup_path(
&mut self,
kind: crate::resources::ResourceKind,
name: &str,
from: &str,
) -> Result<(crate::resources::LoadedResource, std::path::PathBuf), String> {
let resource = self.resource(kind, name, from)?;
let path = resource.version.path.clone();
Ok((resource, path))
}
/// A missing VF permits the physical font path. Lookup and read errors do not.
fn virtual_font(
&mut self,
+61 -10
View File
@@ -581,13 +581,14 @@ impl FileWorld {
&format!("{name}@{density}dpi"),
from,
variants,
None,
)? {
return self.read_path(path);
}
}
// A bare file may be explicitly supplied by a directory path. Never
// recursively pick an arbitrary dpiNNN/name.pk from another density.
for entry in self.paths(ResourceKind::Pk, from) {
for (entry, _) in self.paths(ResourceKind::Pk, from) {
if let SearchPath::Directory { path, suffix, .. } = entry {
let candidate = self
.config
@@ -1238,19 +1239,22 @@ impl FileWorld {
self.indexes.clear();
}
}
fn paths(&self, kind: ResourceKind, from: &Path) -> Vec<SearchPath> {
fn paths(&self, kind: ResourceKind, from: &Path) -> Vec<(SearchPath, bool)> {
// Images use the TeX namespace and have their own dependency role.
let kind = if kind == ResourceKind::PdfImage {
ResourceKind::Tex
} else {
kind
};
let mut defaults = vec![SearchPath::directory(&self.config.cwd, false)];
// Keep default job-relative paths distinct from explicitly configured
// absolute search entries, even when they name the same directory.
let mut defaults = vec![(SearchPath::directory(&self.config.cwd, false), true)];
if kind == ResourceKind::Tex && self.config.input_policy == InputPolicy::Project {
if let Some(parent) = from.parent() {
let path = self.config.cwd.join(parent);
if path != self.config.cwd {
defaults.push(SearchPath::directory(path, false));
let job_relative = path.starts_with(&self.config.cwd);
defaults.push((SearchPath::directory(path, false), job_relative));
}
}
}
@@ -1264,7 +1268,7 @@ impl FileWorld {
self.config
.texmf_roots
.iter()
.map(|r| SearchPath::directory(r.join(directory), true)),
.map(|r| (SearchPath::directory(r.join(directory), true), false)),
);
}
let mut paths = Vec::new();
@@ -1277,7 +1281,7 @@ impl FileWorld {
{
match entry {
SearchPath::Defaults => paths.extend(defaults.clone()),
e => paths.push(e.clone()),
e => paths.push((e.clone(), false)),
}
}
paths
@@ -1442,7 +1446,7 @@ impl FileWorld {
name: &str,
from: &Path,
) -> Result<Option<PathBuf>, String> {
self.resolve_variants(kind, name, from, Self::variants(kind, name, false))
self.resolve_variants(kind, name, from, Self::variants(kind, name, false), None)
}
/// Apply the TeX input scanner's default suffix alternatives. Raw host
@@ -1450,7 +1454,7 @@ impl FileWorld {
pub fn resolve_tex_input(&mut self, name: &str, from: &Path) -> Result<Option<PathBuf>, String> {
let kind = ResourceKind::Tex;
let fallback = self.config.input_policy == InputPolicy::Tex && self.tex_suffix_fallback;
self.resolve_variants(kind, name, from, Self::variants(kind, name, fallback))
self.resolve_variants(kind, name, from, Self::variants(kind, name, fallback), None)
}
fn resolve_variants(
@@ -1459,16 +1463,26 @@ impl FileWorld {
name: &str,
from: &Path,
variants: Vec<PathBuf>,
mut lookup_path: Option<&mut PathBuf>,
) -> Result<Option<PathBuf>, String> {
let mut candidates = Vec::new();
let result = (|| {
let paths = self.paths(kind, from);
let mut found = None;
if Path::new(name).is_absolute() || name.starts_with("./") || name.starts_with("../") {
let requested = Path::new(name);
if requested.is_absolute()
|| matches!(
requested.components().next(),
Some(std::path::Component::CurDir | std::path::Component::ParentDir)
)
{
for variant in &variants {
let path = self.config.cwd.join(variant);
candidates.push(path.clone());
if let Some(path) = self.probe(&path)? {
if let Some(lookup_path) = lookup_path.as_deref_mut() {
lookup_path.clone_from(variant);
}
found = Some(path);
break;
}
@@ -1477,7 +1491,7 @@ impl FileWorld {
// TeX honors search-path priority before the suffix alternatives.
// A recursive path is one entry: search all of it for .tex before
// trying the bare name, rather than flattening it into directories.
'paths: for entry in &paths {
'paths: for (entry, job_relative) in &paths {
let SearchPath::Directory {
path,
recursive,
@@ -1487,10 +1501,24 @@ impl FileWorld {
unreachable!()
};
let root = self.config.cwd.join(path);
let lookup_name = |cwd: &Path, candidate: &Path| {
if *job_relative
&& let Ok(relative) = candidate.strip_prefix(cwd)
{
return Path::new(".").join(relative);
}
if path.is_relative() && let Ok(relative) = candidate.strip_prefix(&root) {
return path.join(relative);
}
candidate.to_owned()
};
for variant in &variants {
let direct = root.join(suffix).join(variant);
candidates.push(direct.clone());
if let Some(path) = self.probe(&direct)? {
if let Some(lookup_path) = lookup_path.as_deref_mut() {
*lookup_path = lookup_name(&self.config.cwd, &direct);
}
found = Some(path);
break 'paths;
}
@@ -1545,6 +1573,9 @@ impl FileWorld {
}
candidates.push(candidate.clone());
if let Some(path) = self.probe(&candidate)? {
if let Some(lookup_path) = lookup_path.as_deref_mut() {
*lookup_path = lookup_name(&self.config.cwd, &candidate);
}
found = Some(path);
break 'paths;
}
@@ -1574,6 +1605,26 @@ impl FileWorld {
self.read_shared(kind, name, from)
.map(SnapshotFile::into_loaded)
}
/// Read a resource and return the path spelling selected by the lookup.
/// Its version records the resolved identity independently.
pub fn read_with_lookup_path(
&mut self,
kind: ResourceKind,
name: &str,
from: &Path,
) -> Result<(LoadedResource, PathBuf), String> {
let mut lookup_path = PathBuf::new();
let path = self.resolve_variants(
kind,
name,
from,
Self::variants(kind, name, false),
Some(&mut lookup_path),
)?;
let resource = self.read_shared_resolved(kind, name, from, path)?;
Ok((resource.into_loaded(), lookup_path))
}
/// Resolve and record a resource read while sharing the captured bytes.
pub fn read_shared(
&mut self,
@@ -214,7 +214,7 @@ impl FileWorld {
let mut remaining = self.config.max_index_entries;
for (path, file) in project.files() {
if !is_outline(path)
|| !paths.iter().any(|scope| self.font_path_in(scope, path))
|| !paths.iter().any(|(scope, _)| self.font_path_in(scope, path))
{
continue;
}