mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #12275 from Triwarr/pdf-editable
PDF: opt-in editable import (paths and text)
This commit is contained in:
11 files changed
+1891
-3
No files matched your search
Generated
+1
@@ -5618,6 +5618,7 @@ dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"imagesize",
|
||||
"kurbo 0.13.1",
|
||||
"lopdf",
|
||||
"miniz_oxide 0.9.1",
|
||||
"photocraft-affinity",
|
||||
|
||||
@@ -33,7 +33,7 @@ required-features = ["gpu"]
|
||||
photocraft-automation = { path = "../../crates/automation" }
|
||||
photocraft-doc = { workspace = true }
|
||||
photocraft-engine = { workspace = true }
|
||||
photocraft-io = { workspace = true }
|
||||
photocraft-io = { workspace = true, features = ["pdf-editable"] }
|
||||
photocraft-raster = { workspace = true }
|
||||
photocraft-format = { path = "../../crates/format" }
|
||||
photocraft-codecs = { workspace = true }
|
||||
|
||||
@@ -125,6 +125,10 @@ pub(crate) struct ConvertArgs {
|
||||
/// PDF pages to import, 1-based: "3" or "2-7" (default all)
|
||||
#[arg(long)]
|
||||
pub(crate) pdf_pages: Option<String>,
|
||||
/// Import PDF paths and embedded-font text as editable layers (experimental; unsupported
|
||||
/// pages fall back to raster, and embedded fonts may change when edited or reopened)
|
||||
#[arg(long)]
|
||||
pub(crate) pdf_editable: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) gpu: GpuArgs,
|
||||
#[command(flatten)]
|
||||
|
||||
@@ -46,6 +46,7 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write
|
||||
psd_high_memory_approved: a.approve_high_memory,
|
||||
pdf_dpi: a.pdf_dpi.unwrap_or(300.0),
|
||||
pdf_pages: a.pdf_pages.as_deref().map(parse_pdf_pages).transpose()?,
|
||||
pdf_editable: a.pdf_editable,
|
||||
..Default::default()
|
||||
};
|
||||
let mut o = files::open_with_options(input, &import_opts)?;
|
||||
|
||||
@@ -16,6 +16,9 @@ corpus = []
|
||||
heif = ["photocraft-codecs/heif"]
|
||||
# Test support for synthetic memory injection, estimate charges and verification across crates.
|
||||
testgen = []
|
||||
# Editable PDF import (experimental): painted paths and embedded-font text become editable
|
||||
# layers; unsupported constructs keep the raster page.
|
||||
pdf-editable = ["dep:kurbo"]
|
||||
|
||||
[dependencies]
|
||||
photocraft-geom = { workspace = true }
|
||||
@@ -53,6 +56,9 @@ resvg = { version = "0.45", default-features = false, features = ["text", "syste
|
||||
ttf-parser = { version = "0.25", default-features = false }
|
||||
# PDF import (pdf_import.rs): craft-pdf rasterizes pages in pure Rust; no shared library ships.
|
||||
craft-pdf = { workspace = true }
|
||||
# Editable PDF import (pdf_editable.rs): craft-pdf's Device trait uses kurbo paths and transforms.
|
||||
# This is the same kurbo 0.13 that craft-pdf already links; naming it adds no crate to the graph.
|
||||
kurbo = { version = "0.13", optional = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] }
|
||||
|
||||
@@ -65,6 +65,8 @@ pub use ora::losses as ora_losses;
|
||||
pub mod pattern_map;
|
||||
mod pcraft_cache;
|
||||
pub mod pdf;
|
||||
#[cfg(all(feature = "pdf-editable", not(target_arch = "wasm32")))]
|
||||
mod pdf_editable;
|
||||
mod pdf_import;
|
||||
mod pdn;
|
||||
pub use pcraft_cache::PcraftExportCache;
|
||||
@@ -612,6 +614,13 @@ pub struct ImportOptions {
|
||||
pub pdf_dpi: f32,
|
||||
/// The 1-based, inclusive page range to import; `None` imports every page (up to the cap).
|
||||
pub pdf_pages: Option<(u32, u32)>,
|
||||
/// Import PDF painted paths and embedded-font text as editable [`photocraft_doc::ShapeLayer`]s
|
||||
/// and text layers instead of a page raster (experimental). Images, complex clips/masks,
|
||||
/// patterns, non-normal blends and unembedded/Type 3 text make that page fall back to the
|
||||
/// raster importer with a warning. Text that uses fonts embedded in the PDF may change font
|
||||
/// when edited or reopened, because the document format does not carry the font bytes. Off by
|
||||
/// default.
|
||||
pub pdf_editable: bool,
|
||||
/// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget.
|
||||
pub psd_high_memory_approved: bool,
|
||||
/// Optional estimate limit for high-memory approval. When set, approval only applies if
|
||||
@@ -628,6 +637,7 @@ impl Default for ImportOptions {
|
||||
flat_max_pixel_bytes: 0,
|
||||
pdf_dpi: 300.0,
|
||||
pdf_pages: None,
|
||||
pdf_editable: false,
|
||||
psd_high_memory_approved: false,
|
||||
psd_approved_estimate: None,
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -135,6 +135,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -
|
||||
|
||||
let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8);
|
||||
doc.resolution_dpi = dpi as f32;
|
||||
#[cfg(feature = "pdf-editable")]
|
||||
let mut editable_text = false;
|
||||
let mut x: u32 = 0;
|
||||
for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() {
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
@@ -147,6 +149,30 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -
|
||||
if width > raster::MAX_SIDE || height > raster::MAX_SIDE || u64::from(width) * u64::from(height) > raster::MAX_PIXELS {
|
||||
return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI")));
|
||||
}
|
||||
let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32);
|
||||
#[cfg(feature = "pdf-editable")]
|
||||
if opts.pdf_editable {
|
||||
match crate::pdf_editable::page(page, rect, ctl) {
|
||||
Ok(layers) => {
|
||||
if layers.iter().any(|layer| matches!(&layer.content, LayerContent::Text(_))) {
|
||||
editable_text = true;
|
||||
}
|
||||
let group = Group { children: layers, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
|
||||
doc.layers.push(Layer::new(format!("Page {page_number}"), LayerContent::Group(group)));
|
||||
x = x.saturating_add(width).saturating_add(GAP);
|
||||
ctl.progress((index + 1) as f32 / count as f32);
|
||||
continue;
|
||||
}
|
||||
Err(crate::pdf_editable::EditableError::Cancelled) => return Err(IoError::Cancelled),
|
||||
Err(crate::pdf_editable::EditableError::Unsupported(reason)) => {
|
||||
warnings.push(format!("PDF page {page_number}: {reason}; the page was rasterised"));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "pdf-editable"))]
|
||||
if opts.pdf_editable {
|
||||
warnings.push(format!("PDF page {page_number}: editable PDF import is not built into this binary; the page was rasterised"));
|
||||
}
|
||||
// A cache per page, deliberately: a shared one would keep decoded images and fonts alive
|
||||
// across up to 16 pages outside the pixel budget, and would hide an image-decode warning
|
||||
// on a later page after the page that first hit it.
|
||||
@@ -195,13 +221,16 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -
|
||||
let band_height = (rows.len() / row_bytes) as u32;
|
||||
surface.write_region(Rect::from_xywh(x as i32, top, width, band_height), &data);
|
||||
}
|
||||
let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32);
|
||||
let layer = Layer::new(format!("Page {page_number}"), LayerContent::Raster(surface));
|
||||
let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None };
|
||||
doc.layers.push(Layer::new(format!("Page {page_number}"), LayerContent::Group(group)));
|
||||
x = x.saturating_add(width).saturating_add(GAP);
|
||||
ctl.progress((index + 1) as f32 / count as f32);
|
||||
}
|
||||
#[cfg(feature = "pdf-editable")]
|
||||
if editable_text {
|
||||
warnings.push("PDF text uses fonts embedded in the PDF; it may change font when edited or reopened".into());
|
||||
}
|
||||
|
||||
Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false })
|
||||
}
|
||||
|
||||
@@ -295,6 +295,12 @@ impl FontDb {
|
||||
self.register_blob(Blob::new(Arc::new(bytes)), None)
|
||||
}
|
||||
|
||||
/// [`Self::register_font_data`] with the family name overridden, so an embedded subset can be
|
||||
/// registered under a name that cannot shadow an installed full family. Returns the names added.
|
||||
pub fn register_font_data_as(&mut self, bytes: Vec<u8>, family: &str) -> Vec<String> {
|
||||
self.register_blob(Blob::new(Arc::new(bytes)), Some(family))
|
||||
}
|
||||
|
||||
/// Registers embedded font data without copying it.
|
||||
fn register_static_font(&mut self, bytes: &'static [u8]) -> Vec<String> {
|
||||
self.register_blob(Blob::new(Arc::new(bytes)), None)
|
||||
|
||||
@@ -142,6 +142,22 @@ impl TextEngine {
|
||||
layer.cache = Some(r.surface);
|
||||
r.rect
|
||||
}
|
||||
|
||||
/// Registers font bytes (for example a font embedded in an imported PDF) for later layout.
|
||||
/// Returns the family names the font provides, best first.
|
||||
pub fn register_font_data(&mut self, bytes: Vec<u8>) -> Vec<String> {
|
||||
self.fonts.register_font_data(bytes)
|
||||
}
|
||||
|
||||
/// [`Self::register_font_data`] under `family`, which cannot shadow an installed family.
|
||||
pub fn register_font_data_as(&mut self, bytes: Vec<u8>, family: &str) -> Vec<String> {
|
||||
self.fonts.register_font_data_as(bytes, family)
|
||||
}
|
||||
|
||||
/// Whether `family` is available to this engine.
|
||||
pub fn has_family(&mut self, family: &str) -> bool {
|
||||
self.fonts.has_family(family)
|
||||
}
|
||||
}
|
||||
|
||||
static SHARED: warm::Warm<std::sync::Mutex<TextEngine>> = warm::Warm::new();
|
||||
|
||||
@@ -35,7 +35,7 @@ fn zoom_menu_steps_keep_the_view_centre_and_history() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicked_point_preference_and_hand_menu_keep_their_existing_anchors() {
|
||||
fn clicked_point_zoom_keeps_its_anchor_and_hand_menu_rejects_step_commands() {
|
||||
for (tool, center_on_point) in [(Tool::Zoom, true), (Tool::Hand, true), (Tool::Hand, false)] {
|
||||
for (command, direction) in [("view.zoomIn", 1), ("view.zoomOut", -1)] {
|
||||
let mut app = zoom_app(400, 300);
|
||||
@@ -47,6 +47,14 @@ fn clicked_point_preference_and_hand_menu_keep_their_existing_anchors() {
|
||||
right_click(&mut h, p, Modifiers::NONE);
|
||||
let doc = h.state().ui.canvas_tool_menu.as_ref().unwrap().anchor.unwrap().map(|n| n as f32);
|
||||
let ctx = h.ctx.clone();
|
||||
if tool == Tool::Hand {
|
||||
// #12022 gives Hand only fixed zoom rows. An injected step command must not run.
|
||||
assert!(!available(h.state(), h.state().ui.canvas_tool_menu.as_ref().unwrap(), command));
|
||||
choose(h.state_mut(), &ctx, command);
|
||||
let v = &h.state().ui.views[0];
|
||||
assert_eq!((v.zoom, v.center), (before.zoom, before.center), "Hand must reject {command}");
|
||||
continue;
|
||||
}
|
||||
choose(h.state_mut(), &ctx, command);
|
||||
let v = &h.state().ui.views[0];
|
||||
assert_eq!(v.zoom, crate::zoom_levels::step(before.zoom, direction, [400, 300]));
|
||||
|
||||
Reference in new issue
Block a user