GitCorner

Code

ossartcraftdesigncraft๐ŸŒ
88f5a00e389b
use super::content::Content;
use super::paint::Fill;
use super::text_frame::TextWrap;
use super::{Affine, Arc, AssetId, Deserialize, Item, ItemId, PathData, Rect, Serialize};

/// Frame fitting options (Object โ†’ Fitting โ†’ Frame Fitting Options).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Fitting {
    #[default]
    None,
    FillProportionally,
    FitProportionally,
    FitContentToFrame,
    CenterContent,
}

/// Retained IDML layer choices for one placement, independent of shared asset bytes.
/// Scalar attributes are kept verbatim, including view/export/print state and link-update policy.
/// XML Self IDs are regenerated by the exporter and are not stored here.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GraphicLayerOptions {
    pub attributes: std::collections::BTreeMap<String, String>,
    pub layers: Vec<std::collections::BTreeMap<String, String>>,
    /// Parent indices in pre-order; absent entries are top-level layers (older native files).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parents: Vec<Option<usize>>,
}

pub const GRAPHIC_LAYER_RENDERING_WARNING: &str =
    "Placed graphic layer visibility overrides are preserved but are not applied to rendering or PDF output";

impl GraphicLayerOptions {
    pub fn has_visibility_overrides(&self) -> bool {
        self.layers.iter().any(|layer| {
            layer.get("CurrentVisibility").is_some_and(|v| Some(v) != layer.get("OriginalVisibility"))
                || ["HasViewState", "HasExportState", "HasPrintState"].iter().any(|key| layer.get(*key).is_some_and(|v| v == "true"))
        })
    }
}

/// A placed graphic inside a frame.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Graphic {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layer_options: Option<GraphicLayerOptions>,
    pub asset: AssetId,
    /// Natural size of the graphic in points (pixels at its resolution, or PDF page size).
    pub size: (f64, f64),
    /// Graphic space (0,0)-(w,h) โ†’ frame inner space.
    pub xf: Affine,
    /// Clipping path: only the part of the graphic inside it shows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub clip: Option<Arc<ClippingPath>>,
    #[serde(default)]
    pub auto_fit: Fitting,
    /// Frame Fitting Options โ€บ Align From: the reference point (0โ€“8, row-major; 4 = centre).
    #[serde(default = "center_ref")]
    pub fit_align: u8,
    /// Frame Fitting Options โ€บ Crop Amount: top, left, bottom, right (negative adds space).
    #[serde(default)]
    pub crop: [f64; 4],
    /// Text wrap set on the graphic itself (Direct Selection), around the part its frame shows.
    #[serde(default, skip_serializing_if = "TextWrap::is_default")]
    pub wrap: TextWrap,
    /// The swatch applied to the image itself: InDesign colours a greyscale or bitmap image with
    /// it, colour images ignore it. `None` (the default, like InDesign's Black) leaves it as is.
    #[serde(default, skip_serializing_if = "Fill::is_none")]
    pub fill: Fill,
}

fn center_ref() -> u8 {
    4
}

/// Most anchors a clipping path read from a file keeps (detected edges can be dense).
pub const MAX_CLIP_ANCHORS: usize = 100_000;

/// Clipping Path โ€บ Type: where the clipping path came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ClippingKind {
    /// Traced from the image's edges against a light background.
    DetectEdges,
    /// Traced from one of the image's alpha channels.
    AlphaChannel,
    /// A path saved in the image file.
    PhotoshopPath,
    /// One of the above, edited by hand.
    UserModifiedPath,
}

/// A placed graphic's clipping path. The tracing options are kept as the file had them; the
/// outline itself is `path`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClippingPath {
    pub kind: ClippingKind,
    /// The outline in graphic space ((0,0)-(w,h) is the graphic's natural rectangle).
    pub path: PathData,
    /// Show the graphic outside the path instead of inside it.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub invert: bool,
    /// Holes inside the traced shape are part of the path.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub include_inside_edges: bool,
    /// Detect Edges: trace only the part of the image the frame shows.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub restrict_to_frame: bool,
    /// Trace the full-resolution image rather than the screen proxy.
    #[serde(default = "yes")]
    pub use_high_resolution: bool,
    /// Detect Edges / Alpha Channel: the darkness or opacity level that counts as inside (0โ€“255).
    #[serde(default = "clip_threshold")]
    pub threshold: f64,
    /// How closely the traced path follows the pixels, in pixels.
    #[serde(default = "clip_tolerance")]
    pub tolerance: f64,
    /// Inset Frame: how far the path is pulled in (points; negative pushes it out).
    #[serde(default)]
    pub inset: f64,
    /// The alpha channel or image path the clip came from.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub source_name: String,
    /// Index of the alpha channel (-1 = none).
    #[serde(default = "no_index")]
    pub source_index: i32,
}

fn yes() -> bool {
    true
}

fn clip_threshold() -> f64 {
    25.0
}

fn clip_tolerance() -> f64 {
    2.0
}

fn no_index() -> i32 {
    -1
}

impl ClippingPath {
    /// A clipping path of `kind` with the default options.
    pub fn new(kind: ClippingKind, path: PathData) -> Self {
        Self {
            kind,
            path,
            invert: false,
            include_inside_edges: false,
            restrict_to_frame: false,
            use_high_resolution: true,
            threshold: clip_threshold(),
            tolerance: clip_tolerance(),
            inset: 0.0,
            source_name: String::new(),
            source_index: no_index(),
        }
    }
}

/// Liquid Layout object rules: which edges stay at their distance from the page edge, and
/// whether the object may stretch.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ObjectLiquid {
    pub resize_width: bool,
    pub resize_height: bool,
    pub pin_top: bool,
    pub pin_bottom: bool,
    pub pin_left: bool,
    pub pin_right: bool,
}

/// Object Export Options: tagged PDF and EPUB/HTML handling of one object.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ExportOptions {
    /// Tagged PDF: the object is decoration (an artifact), not content.
    pub artifact: bool,
    /// EPUB/HTML: export the object as an image (whatever it is).
    pub rasterize: bool,
    /// EPUB/HTML: "left", "center" or "right" ("" = as the flow puts it).
    pub align: String,
    /// EPUB/HTML: start a new page (screen) before the object.
    pub page_break_before: bool,
}

impl ExportOptions {
    pub fn is_default(&self) -> bool {
        *self == ExportOptions::default()
    }
}

/// A PDF form field.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FormField {
    pub kind: FieldKind,
    /// Field name (unique in the exported PDF).
    pub name: String,
    /// Default value: the text, the chosen option, or "On"/"" for a check box.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub value: String,
    /// Choices of a combo box or list box.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub options: Vec<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub multiline: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub required: bool,
    /// Font size of the field's text (0 = auto).
    #[serde(default)]
    pub font_size: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FieldKind {
    TextField,
    CheckBox,
    ComboBox,
    ListBox,
    Signature,
}

/// The source and template of a live caption.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LiveCaption {
    pub source: ItemId,
    pub template: String,
}

/// Media panel options for a placed video or sound.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct MediaOptions {
    pub play_on_page_load: bool,
    #[serde(rename = "loop")]
    pub looping: bool,
    /// Show the player controls.
    pub controls: bool,
    /// Poster image (shown on the page and in print); `None` = a placeholder frame.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub poster: Option<AssetId>,
}

impl Item {
    /// The graphic to draw for this frame: a media frame with a poster draws the poster
    /// stretched over the media rectangle.
    pub fn drawn_graphic(&self, assets: &std::collections::BTreeMap<AssetId, Arc<crate::Asset>>) -> Option<Graphic> {
        let Content::Graphic(g) = &self.content else { return None };
        if let Some(poster) = self.media.as_ref().and_then(|m| m.poster)
            && let Some((pw, ph)) = assets.get(&poster).and_then(|a| a.pixels)
        {
            let (pw, ph) = (pw.max(1) as f64, ph.max(1) as f64);
            return Some(Graphic { asset: poster, size: (pw, ph), xf: g.xf * Affine::scale_non_uniform(g.size.0 / pw, g.size.1 / ph), ..g.clone() });
        }
        Some(g.clone())
    }
}

/// "video" or "audio" for a media MIME type.
pub fn media_kind(mime: &str) -> Option<&'static str> {
    if mime.starts_with("video/") {
        Some("video")
    } else if mime.starts_with("audio/") {
        Some("audio")
    } else {
        None
    }
}

/// MIME type of a media file by its extension.
pub fn media_mime(name: &str) -> Option<&'static str> {
    let ext = name.rsplit('.').next()?.to_ascii_lowercase();
    Some(match ext.as_str() {
        "mp4" | "m4v" => "video/mp4",
        "mov" => "video/quicktime",
        "webm" => "video/webm",
        "ogv" => "video/ogg",
        "mp3" => "audio/mpeg",
        "m4a" => "audio/mp4",
        "wav" => "audio/wav",
        "ogg" | "oga" => "audio/ogg",
        "aac" => "audio/aac",
        _ => return None,
    })
}

/// A button's On Release action.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum ButtonAction {
    GoToPage { page: usize },
    GoToFirstPage,
    GoToLastPage,
    GoToNextPage,
    GoToPreviousPage,
    GoToUrl { url: String },
}

impl Graphic {
    /// The part of the graphic its frame shows, in the frame's inner space (bounding boxes);
    /// None when nothing shows.
    pub fn shown_bounds(&self, frame: Rect) -> Option<Rect> {
        let r = self.xf.transform_rect_bbox(Rect::new(0.0, 0.0, self.size.0, self.size.1)).intersect(frame);
        (r.width() > 0.0 && r.height() > 0.0).then_some(r)
    }

    /// The region the clipping path lets through, in frame inner space, and whether it is filled
    /// even-odd (an inverted clip: the graphic's rectangle minus the path). `None` when the graphic
    /// has no clipping path or the path is empty.
    pub fn clip_region(&self) -> Option<(designcraft_geom::BezPath, bool)> {
        use designcraft_geom::Shape;
        let c = self.clip.as_ref().filter(|c| !c.path.is_empty())?;
        let mut path = c.path.to_bezpath();
        if !c.invert {
            path.apply_affine(self.xf);
            return Some((path, false));
        }
        let outer = Rect::new(0.0, 0.0, self.size.0, self.size.1).union(path.bounding_box()).inflate(1.0, 1.0);
        let mut region = outer.to_path(0.1);
        region.extend(path.iter());
        region.apply_affine(self.xf);
        Some((region, true))
    }

    /// The graphic transform that fits it into `frame` (the frame's inner rect) with `mode`,
    /// honouring the crop amounts and the reference point.
    pub fn fitted(&self, frame: Rect, mode: Fitting) -> Option<Affine> {
        let (nw, nh) = self.size;
        if nw <= 0.0 || nh <= 0.0 {
            return None;
        }
        let [t, l, b, r] = self.crop;
        let area = Rect::new(frame.x0 - l, frame.y0 - t, frame.x1 + r, frame.y1 + b);
        if area.width() <= 0.0 || area.height() <= 0.0 {
            return None;
        }
        let (fx, fy) = ([0.0, 0.5, 1.0][(self.fit_align % 3) as usize], [0.0, 0.5, 1.0][(self.fit_align / 3).min(2) as usize]);
        let place = |w: f64, h: f64| (area.x0 + (area.width() - w) * fx, area.y0 + (area.height() - h) * fy);
        Some(match mode {
            Fitting::None => return None,
            Fitting::FillProportionally | Fitting::FitProportionally => {
                let k = if mode == Fitting::FillProportionally {
                    (area.width() / nw).max(area.height() / nh)
                } else {
                    (area.width() / nw).min(area.height() / nh)
                };
                Affine::translate(place(nw * k, nh * k)) * Affine::scale(k)
            }
            Fitting::FitContentToFrame => Affine::translate((area.x0, area.y0)) * Affine::scale_non_uniform(area.width() / nw, area.height() / nh),
            Fitting::CenterContent => {
                let cur = self.xf.transform_rect_bbox(Rect::new(0.0, 0.0, nw, nh));
                let (x, y) = place(cur.width(), cur.height());
                Affine::translate((x - cur.x0, y - cur.y0)) * self.xf
            }
        })
    }
}