diff --git a/crates/texrra-tex-core/src/execution/engine/device.rs b/crates/texrra-tex-core/src/execution/engine/device.rs index c57f908..a6e01c9 100644 --- a/crates/texrra-tex-core/src/execution/engine/device.rs +++ b/crates/texrra-tex-core/src/execution/engine/device.rs @@ -270,11 +270,38 @@ impl Executor { .map_err(|e| self.error(e, self.current))?; self.events.push(Event::Message { text, span: self.current }); } - let options = PdfHeaderOptions { major, minor: minor as u8, object_compression }; + let draft_mode = if self.state.input_profile() == InputProfile::TeX8Bit { + let mode = self.read_parameter(Parameter::Pdfdraftmode).width(); + if !(0..=1).contains(&mode) { + return self.fail("\\pdfdraftmode can only be changed before anything is written to the output"); + } + mode == 1 + } else { + false + }; + if draft_mode { + object_compression = 0; + self.state.disable_draft_stream_compression(); + } + let options = PdfHeaderOptions { major, minor: minor as u8, object_compression, draft_mode }; self.state.pdf_header_options = Some(options); Ok(options) } + pub(super) fn prepare_pdf_draft_shipout(&mut self) -> Result<(), Error> { + if self.state.input_profile() == InputProfile::TeX8Bit + && let Some(header) = self.state.pdf_header_options + { + if self.read_parameter(Parameter::Pdfdraftmode).width() != i32::from(header.draft_mode) { + return self.fail("\\pdfdraftmode can only be changed before anything is written to the output"); + } + if header.draft_mode { + self.state.disable_draft_stream_compression(); + } + } + Ok(()) + } + pub(super) fn pdf_page_data( &mut self, files: &mut impl SourceProvider, @@ -307,7 +334,9 @@ impl Executor { pk_resolution: pk_resolution.clamp(72, 8000) as u32, }); } - let level = self.read_parameter(Parameter::Pdfcompresslevel).width(); + let level = if header.draft_mode { 0 } else { + self.read_parameter(Parameter::Pdfcompresslevel).width() + }; if level > 9 { return self.fail("invalid native PDF compression level"); } diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 10b0003..6184207 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -323,6 +323,7 @@ impl Executor { } let job_magnification = self.prepare_magnification()?; let magnification = if for_form { 1000 } else { job_magnification }; + self.prepare_pdf_draft_shipout()?; let pdf = self.pdf_page_data(files)?; let unicode_pages = self.state.input_profile() != InputProfile::TeX8Bit; // The XDV driver uses a physical sheet and origin, then applies diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_image.rs b/crates/texrra-tex-core/src/execution/engine/pdf_image.rs index 1086123..576defc 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_image.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_image.rs @@ -513,6 +513,9 @@ impl Executor { let Some(tokens) = registered.attributes.take() else { return Ok(()); }; + if self.state.pdf_draft_mode() { + return Ok(()); + } let mut image = registered.image.clone(); if image.image.has_imported_fonts() { let from = self.source_name(self.current); diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index d97a38d..4c0da33 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -14,9 +14,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 89; -const COMPATIBLE_SCHEMAS: [u32; 56] = [ - 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, SCHEMA, +const SCHEMA: u32 = 90; +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 ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -191,6 +191,9 @@ impl FormatImage { Parameter::Pdfoptionalwaysusepdfpagebox, ]); } + if image.schema < 90 { + image.state.restore_legacy_pdf_parameters(&[Parameter::Pdfdraftmode]); + } let pdf_objects = image.state.pdf_objects.as_deref(); let mut numbered_images = 0; for (index, saved) in image.pdf_images.iter().enumerate() { diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 826a1e4..1dfc00b 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -758,11 +758,13 @@ impl Execution { })?); } } - self.resolve_page_graphics_resources(&mut pages)?; - for form in &mut forms { - let attributes = std::mem::take(&mut form.list.pdf_resources.attributes); - self.resolve_page_graphics_resources(std::slice::from_mut(&mut form.list))?; - form.list.pdf_resources.attributes = attributes; + if !self.state.pdf_draft_mode() { + self.resolve_page_graphics_resources(&mut pages)?; + for form in &mut forms { + let attributes = std::mem::take(&mut form.list.pdf_resources.attributes); + self.resolve_page_graphics_resources(std::slice::from_mut(&mut form.list))?; + form.list.pdf_resources.attributes = attributes; + } } if let Some(first) = pages.first_mut() { first.forms = forms; diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index c673acf..9633866 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -140,6 +140,7 @@ pub enum Parameter { XeTeXlinebreakskip, XeTeXlinebreakpenalty, XeTeXinputnormalization, + Pdfdraftmode, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum ParameterValue { @@ -155,6 +156,7 @@ impl Parameter { | Self::Pdfminorversion | Self::Pdfobjcompresslevel | Self::Pdfcompresslevel + | Self::Pdfdraftmode | Self::Pdfdecimaldigits | Self::Pdfpkresolution | Self::Pdfimageresolution @@ -201,6 +203,7 @@ impl Parameter { Self::Pdfminorversion, Self::Pdfobjcompresslevel, Self::Pdfcompresslevel, + Self::Pdfdraftmode, Self::Pdfdecimaldigits, Self::Pdfpkresolution, Self::Pdfimageresolution, diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 28547b7..02e170a 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1400,6 +1400,13 @@ impl State { self.parameters.remove(&old); } + pub(super) fn disable_draft_stream_compression(&mut self) { + // This is a device update to the current eqtb value. Existing save + // entries still restore the enclosing group's compression setting. + self.parameters + .insert(Parameter::Pdfcompresslevel, ParameterValue::Integer(0)); + } + /// Explicit host selection of the PDF driver (INITEX itself defaults to /// pdfoutput=0). The source can still assign the real parameter. pub fn with_pdf_output(mut self) -> Self { @@ -1746,6 +1753,11 @@ impl State { pub fn is_initex(&self) -> bool { self.initex } + /// Whether this job has started PDF output in TeX's draft mode. + pub fn pdf_draft_mode(&self) -> bool { + self.pdf_header_options.is_some_and(|options| options.draft_mode) + } + /// Final PDF output uses the live state after the last page ships out. pub fn pdf_final_options(&self) -> crate::pdf_unicode::PdfFinalOptions<'_> { crate::pdf_unicode::PdfFinalOptions { diff --git a/crates/texrra-tex-core/src/pdf_device.rs b/crates/texrra-tex-core/src/pdf_device.rs index 8b615de..2fa1883 100644 --- a/crates/texrra-tex-core/src/pdf_device.rs +++ b/crates/texrra-tex-core/src/pdf_device.rs @@ -10,6 +10,8 @@ pub(crate) struct PdfHeaderOptions { pub major: i32, pub minor: u8, pub object_compression: u8, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub draft_mode: bool, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/tests/support/font_world.rs b/crates/texrra-tex-core/tests/support/font_world.rs index 23ddc6b..f9095fd 100644 --- a/crates/texrra-tex-core/tests/support/font_world.rs +++ b/crates/texrra-tex-core/tests/support/font_world.rs @@ -124,7 +124,9 @@ pub fn painted_text(items: &[texrra_tex_core::HorizontalItem]) -> String { }), MathItem::Rule { .. } => {} MathItem::Glyph { .. } => panic!("legacy font in native test material"), - MathItem::PdfImage(_) => panic!("PDF image in a DVI fixture"), + MathItem::PdfImage(_) | MathItem::PdfForm(_) => { + panic!("PDF image or Form in a DVI fixture") + } MathItem::OpenType(_) => panic!("OpenType paint in a classic DVI fixture"), } } diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index e3d5b74..e6dfb32 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -960,6 +960,25 @@ XRef 通过。十一页中九页逐像素一致。两份带 CMR 字形的作业 对照在 target/p3-pdf-draft-mode,覆盖辅助文件、已存在的 PDF, 以及普通对象登记和真正开始 PDF 输出之间的界限。 +### pdfTeX 草稿模式与真实辅助文件 + +原生 pdfdraftmode 在首次固定 PDF 头时锁定,并在后续出页 +检查该状态。草稿停止对象流压缩,在冻结和出页时将实际 +pdfcompresslevel 置零,同时保持分组原有恢复。图像登记仍读取 +真实资源和尺寸,草稿图像写出跳过遮罩等输出对象。常规流 +I/O 和外置 PDF 对象数据仍按原时序读取。 +[pdfTeX 草稿模式与压缩状态](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L17671-L17687) + +库与 CLI 保留真实出页和来源映射,草稿作业发布辅助文件且 +保留已有 PDF 的字节及修改时间。文件编辑从正式切到草稿再 +回到正式时保留上述行为。先建立辅助文件的宿主所有权再比较 +切换。已稳定的正式状态到草稿恢复检查点,辅助文件和来源映射 +与独立全量一致。二十一份 PDF 原版探针通过模式、 +编号、字节或诊断对照,保留的三页普通 PDF 逐像素一致。另核对 +DVI 模式的原生出页几何、两种格式镜像和二十五项定向回归。 +schema90 支持草稿参数持久化,schema89 镜像加载时恢复此原语。 +回执 SHA-256 为 0084b0d17763f7a9b6f5d6d6816334a40e9e1ff069428e3f8880866fb77a3396。 + ### PDF 预览按实际页面资源复用 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 diff --git a/src/main.rs b/src/main.rs index 9235e79..a38de58 100644 --- a/src/main.rs +++ b/src/main.rs @@ -318,7 +318,9 @@ fn native_pdf( let result = NativeCompiler::default() .compile_detailed(request) .map_err(failure_message)?; - if result.output.is_none() { + if result.execution.execution.state.pdf_draft_mode() && !result.pages.is_empty() { + println!("native Route-D draft execution complete ({} pages, PDF output suppressed)", result.pages.len()); + } else if result.output.is_none() { println!("native Route-D execution complete (no pages)"); } else { println!( diff --git a/src/native.rs b/src/native.rs index 07fe119..f59ba0e 100644 --- a/src/native.rs +++ b/src/native.rs @@ -1057,6 +1057,7 @@ impl CompileJob { notify(&request, revision, CompileStage::Executed, &cancellation)?; evidence.phase = AttemptPhase::Layout; let e = &execution.execution; + let draft_mode = request.target == Target::Shipouts && e.state.pdf_draft_mode(); let (mut pages, paper_width, paper_height, origin) = if request.target == Target::Shipouts { @@ -1085,25 +1086,27 @@ impl CompileJob { files.write_layout_manifest(path, e, &pages, &source_map)?; } evidence.phase = AttemptPhase::Fonts; - let mut forms = pages.first_mut().map(|first| std::mem::take(&mut first.forms)) - .unwrap_or_default(); - let actual_pages = pages.len(); - pages.extend(forms.iter_mut().map(|form| std::mem::take(&mut form.list))); - let fonts = self.compiler.font_cache.resolve(&mut pages, files); - for (form, list) in forms.iter_mut().zip(pages.drain(actual_pages..)) { - form.list = list; - } - if let Some(first) = pages.first_mut() { - first.forms = forms; - } - let reported = report(files, &request); - if let Err(error) = fonts { - if let Err(report) = reported { - evidence.gaps.push(report.to_string()); + if !draft_mode { + let mut forms = pages.first_mut().map(|first| std::mem::take(&mut first.forms)) + .unwrap_or_default(); + let actual_pages = pages.len(); + pages.extend(forms.iter_mut().map(|form| std::mem::take(&mut form.list))); + let fonts = self.compiler.font_cache.resolve(&mut pages, files); + for (form, list) in forms.iter_mut().zip(pages.drain(actual_pages..)) { + form.list = list; } - return Err(CompileError::Host(error)); + if let Some(first) = pages.first_mut() { + first.forms = forms; + } + let reported = report(files, &request); + if let Err(error) = fonts { + if let Err(report) = reported { + evidence.gaps.push(report.to_string()); + } + return Err(CompileError::Host(error)); + } + reported?; } - reported?; let source_map = self.compiler.session.source_map(&execution, &pages)?; notify( &request, @@ -1125,6 +1128,8 @@ impl CompileJob { }; let (pdf, export_diagnostics) = if pages.is_empty() { (None, Vec::new()) + } else if draft_mode { + (None, vec![r"\pdfdraftmode enabled, not changing output pdf".into()]) } else if request.target == Target::Shipouts { let mut options = e.state.pdf_final_options(); options.xdv_glyph_names = xdv_glyph_names.as_ref(); @@ -1178,7 +1183,7 @@ impl CompileJob { let previous = self.compiler.latest(); // Identical PDF output allows direct reuse. When it differs, // PDF previews validate the new page and its reachable objects. - let pdf_unchanged = pages.iter().any(DisplayList::has_embedded_pdf) + let pdf_unchanged = pdf.is_some() && pages.iter().any(DisplayList::has_embedded_pdf) && previous .as_deref() .is_some_and(|document| document.pdf.as_deref() == pdf.as_deref()); diff --git a/tests/native_pdf_config.rs b/tests/native_pdf_config.rs index d0c16e8..d44037b 100644 --- a/tests/native_pdf_config.rs +++ b/tests/native_pdf_config.rs @@ -18,6 +18,99 @@ fn directory() -> PathBuf { p } +#[test] +fn pdf_draft_preserves_existing_output_and_writes_real_auxiliary_data() { + let p = directory(); + let source = r"\catcode123=1 \catcode125=2 +\pdfoutput=1 \pdfdraftmode=1 \pdfminorversion=5 +\pdfobjcompresslevel=3 \pdfcompresslevel=8 +\immediate\openout0=probe.aux +\shipout\hbox{\vrule width1pt height2pt + \write0{MODE=\the\pdfdraftmode;ZIP=\the\pdfcompresslevel;}} +\immediate\closeout0 +\end"; + fs::write(p.join("probe.tex"), source).unwrap(); + let published = p.join("probe.pdf"); + fs::write(&published, b"previously published bytes").unwrap(); + let output = native_fonts::command() + .args(["native", "--job", "--initex", "--etex", "probe.tex", "probe.pdf"]) + .current_dir(&p) + .output() + .unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + let log = fs::read_to_string(p.join("probe.log")).unwrap(); + assert!(log.contains(r"\pdfdraftmode enabled, not changing output pdf")); + assert_eq!(fs::read(&published).unwrap(), b"previously published bytes"); + assert_eq!(fs::read(p.join("probe.aux")).unwrap(), b"MODE=1;ZIP=0;\n"); + fs::remove_dir_all(p).unwrap(); +} + +#[test] +fn live_pdf_draft_updates_auxiliary_files_without_replacing_the_published_pdf() { + use std::sync::Arc; + use texrra_engine::native::{ + CompileRequest, Entry, NativeCompiler, ProjectDefinition, ProjectSnapshot, + }; + use texrra_tex_core::{execution::JobTime, resources::WorldConfig}; + + let root = directory(); + let entry = root.join("probe.tex"); + let settings = root.join("settings.tex"); + let configuration = WorldConfig::new(&root); + let prefix = r"\catcode123=1 \catcode125=2 +\pdfoutput=1 \pdfminorversion=5 \pdfobjcompresslevel=1 +"; + let line = format!("{}\n", "\\relax ".repeat(26)); + let body = r"\input settings.tex +\immediate\openout0=probe.aux +\shipout\hbox{\vrule width4pt height5pt \write0{DRAFT=\the\pdfdraftmode;}} +\immediate\closeout0 +\end"; + let source = format!("{prefix}{}{body}", line.repeat(40)); + let project = ProjectSnapshot::new(ProjectDefinition { + configuration: configuration.clone(), + revision: 1, + roots: [root.clone()].into(), + files: [ + (entry.clone(), Arc::<[u8]>::from(source.into_bytes())), + (settings.clone(), Arc::from(br"\pdfdraftmode=0".as_slice())), + ].into(), + directories: Default::default(), + aliases: Default::default(), + generated_roots: [root.clone()].into(), + generated: Default::default(), + }).unwrap(); + let draft_input = project.with_file_edits(2, [(settings.clone(), Arc::from(br"\pdfdraftmode=1".as_slice()))].into()).unwrap(); + let restored_input = draft_input.with_file_edits(3, [(settings, Arc::from(br"\pdfdraftmode=0".as_slice()))].into()).unwrap(); + let time = JobTime::new(2026, 11, 27, 600).unwrap().with_pdf_clock(0, 0).unwrap(); + let mut request = CompileRequest::new(configuration, entry, "probe.pdf", time); + request.entry = Entry::Initex; + request.etex = true; + let live = NativeCompiler::default().with_automatic_entry_checkpoints(); + let first = live.compile(request.clone().with_project(project.clone())).unwrap(); + // The first round establishes ownership of the newly generated aux file. + let settled = live.compile(request.clone().with_project(project)).unwrap(); + assert_eq!(first.pdf, settled.pdf); + let previous_pdf = settled.pdf.as_deref().unwrap(); + let draft = live.compile(request.clone().with_project(draft_input.clone())).unwrap(); + assert!(draft.entry_checkpoint_work.reused_steps > 0, + "settled {:?}; draft {:?}", settled.entry_checkpoint_work, draft.entry_checkpoint_work); + assert_eq!(draft.pages.len(), 1); + assert!(draft.execution.execution.state.pdf_draft_mode()); + assert!(draft.pdf.is_none() && draft.output.is_none()); + assert_eq!(fs::read(root.join("probe.pdf")).unwrap(), previous_pdf); + let aux = fs::read(root.join("probe.aux")).unwrap(); + assert_eq!(aux, b"DRAFT=1;\n"); + let cold = NativeCompiler::default().compile(request.clone().with_project(draft_input)).unwrap(); + assert_eq!(draft.pdf, cold.pdf); + assert_eq!(draft.source_map.pages, cold.source_map.pages); + assert_eq!(fs::read(root.join("probe.aux")).unwrap(), aux); + let output = live.compile(request.with_project(restored_input)).unwrap(); + assert_eq!(output.pdf.as_deref(), Some(previous_pdf)); + assert_eq!(fs::read(root.join("probe.aux")).unwrap(), b"DRAFT=0;\n"); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn reproducible_pdf_dates_keep_register_policy_and_reject_invalid_epochs() { use chrono::{Datelike, Local};