GitCorner

Code

ossartcraftphotocraft🌐
856f865cf98d
use craft::color_ui::ui::EyedropperOptions;
use craft::draw::ui::crop::{CropSettings, CropSizeFields};
use craft::draw::ui::{PathOptionsSettings, TransformSettings, VectorMode};
use craft::imaging::ui::select::MagneticSettings;

use super::tool::Tool;
use super::{Deserialize, Serialize};

/// Options-bar state for tools (Photoshop keeps these per tool).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ToolOptions {
    pub tolerance: f32,
    pub contiguous: bool,
    pub anti_alias: bool,
    /// Sample All Layers, kept per tool as in Photoshop (#5524). Stored under a new key, so the
    /// single shared `sample_all_layers` of older preferences is ignored on load.
    pub sample_all: SampleAllLayers,
    /// Object Selection › Object Finder: hovering highlights the object a click selects (#4087).
    pub object_finder: bool,
    /// Object Selection › Hard Edge (#12855): off, the result gets a softer, slightly wider rim.
    pub object_hard_edge: bool,
    /// Remove tool: the fill goes to a new layer above the target (Photoshop's Create a new layer).
    pub remove_new_layer: bool,
    /// Remove tool: each stroke is filled when released (Photoshop's default). Off, the strokes
    /// collect as a tint on the canvas and ↩ applies them together (Esc drops them).
    pub remove_after_each_stroke: bool,
    pub feather: f32,
    /// linear | radial | angle | reflected | diamond
    pub gradient_style: String,
    pub gradient_reverse: bool,
    /// Gradient tool: dither to reduce 8-bit banding (Photoshop default on).
    pub gradient_dither: bool,
    /// Gradient tool mode: false = "Gradient" (live: a Gradient Fill layer, editable on canvas),
    /// true = "Classic gradient" (paints the pixels).
    pub gradient_classic: bool,
    /// Blend mode used by both live and classic gradient drags.
    pub gradient_blend_mode: photocraft_color::BlendMode,
    pub fill_opacity: f32,
    /// Paint Bucket fill source: false = Foreground colour, true = Pattern (Patterns panel selection).
    pub bucket_fill_pattern: bool,
    /// Paint Bucket › Mode (any layer mode; Clear is `bucket_clear`).
    pub bucket_blend_mode: photocraft_color::BlendMode,
    /// Paint Bucket › Mode: Clear, which erases the filled area (see `brush_clear`).
    pub bucket_clear: bool,
    /// Type tool: family, style name, size (pt), anti-aliasing and paragraph alignment.
    pub type_font: String,
    pub type_style: String,
    pub type_size: f32,
    pub type_aa: String,
    pub type_align: String,
    /// Character/Paragraph panel defaults beyond the options bar, in `type.setStyle`'s
    /// parameter format. Kept as overrides so saved engine defaults still supply unset fields.
    /// OpenType features and variable-font axes are merged per tag/axis.
    #[serde(default)]
    pub type_style_defaults: serde_json::Map<String, serde_json::Value>,
    /// Type tool: paragraph direction of new type, "auto" (from the first strong character),
    /// "ltr" or "rtl" (TYPE-218-2).
    pub type_direction: String,
    /// Clone Stamp / Healing Brush.
    pub clone_aligned: bool,
    /// Pattern Stamp: lock the tile origin in document space across strokes.
    pub pattern_stamp_aligned: bool,
    /// Pattern Stamp: jitter each dab's phase (seeded, replayable).
    pub pattern_stamp_impressionist: bool,
    /// Pattern Stamp scale %, 1..1000 (100 = the tile's native size).
    pub pattern_stamp_scale: f32,
    /// Pattern Stamp rotation in degrees (counter-clockwise).
    pub pattern_stamp_angle: f32,
    /// current | currentAndBelow | all
    pub clone_sample: String,
    /// Spot Healing: contentAware | createTexture | proximityMatch
    pub spot_type: String,
    /// Patch: source (repair the selection) | destination (repair where it is dragged).
    pub patch_mode: String,
    /// Patch: Content-Aware instead of Normal, with its Structure 1..7 and Color 0..10.
    pub patch_content_aware: bool,
    pub patch_structure: f32,
    pub patch_color: f32,
    /// Content-Aware Move: move | extend, Structure 1..7, Color 0..10.
    pub cam_mode: String,
    pub cam_structure: f32,
    pub cam_color: f32,
    /// Content-Aware Move: Transform On Drop (a transform box on the dropped patch). On by
    /// default (#12185); a saved `false` stays off.
    #[serde(default = "yes")]
    pub cam_transform_on_drop: bool,
    /// Dodge/Burn: shadows | midtones | highlights, exposure %, protect tones.
    pub tone_range: String,
    pub exposure: f32,
    pub protect_tones: bool,
    /// Sponge: desaturate | saturate, vibrance.
    pub sponge_mode: String,
    /// Sponge: Flow %, whole numbers 1..100 (#12976). Settings saved before it load as 50.
    #[serde(default = "fifty")]
    pub sponge_flow: f32,
    pub vibrance: bool,
    /// Blur/Sharpen/Smudge strength %, Sharpen protect detail, Smudge finger painting.
    pub strength: f32,
    pub protect_detail: bool,
    pub finger_painting: bool,
    /// Smudge › Mode (#12959): Normal, Darken, Lighten, Hue, Saturation, Color or Luminosity.
    pub smudge_mode: photocraft_color::BlendMode,
    /// Quick Selection enhance edge.
    pub enhance_edge: bool,
    /// Pen: a work path or a shape layer.
    pub vector_mode: VectorMode,
    /// Pen, Freeform Pen and Curvature Pen › Path Operations (#1397): how a new path combines with
    /// the path or shape it is drawn into: "newLayer" (Shape mode: a new shape layer; Path mode
    /// draws it as "combine"), "combine", "subtract", "intersect" or "exclude".
    #[serde(default = "default_pen_path_op")]
    pub pen_path_op: String,
    /// Shape tools › Path operations (#13235): how a drag combines with the active shape layer
    /// (Shape mode) or work path (Path mode). Same values as `pen_path_op`; in Path mode "newLayer"
    /// means Exclude Overlapping Shapes.
    #[serde(default = "default_shape_path_op")]
    pub shape_path_op: String,
    /// Shape tools: a shape layer or the work path, as Photoshop's tool mode (#9453). Shape by
    /// default, where the Pen's own mode defaults to Path.
    pub shape_mode: VectorMode,
    /// Shape tools: fill with the foreground colour, stroke width (0 = none), rectangle corner
    /// radius, polygon sides, line weight.
    pub shape_fill: bool,
    pub stroke_width: f32,
    #[serde(default)]
    pub shape_stroke: crate::shape_stroke_ui::StrokeOptions,
    /// Shape tools: the gradient the next shape's fill / stroke takes (the swatches' Gradient
    /// tab) instead of the foreground / background colour; `None` = the colour.
    pub shape_fill_gradient: Option<photocraft_doc::Fill>,
    pub shape_stroke_gradient: Option<photocraft_doc::Fill>,
    pub corner_radius: f32,
    /// Shape tools' Align Edges: snap the drawn shape's box to whole pixels. On by default; the
    /// Triangle tool shows it, enabled in Shape mode only (#13370); the other shape tools always snap.
    pub align_edges: bool,
    pub polygon_sides: u32,
    pub line_weight: f32,
    /// Line arrowheads.
    pub arrow_start: bool,
    pub arrow_end: bool,
    pub arrow_width: f32,
    pub arrow_length: f32,
    pub arrow_concavity: f32,
    /// Rectangle tool › gear (#13343): how a drag sizes the rectangle: "unconstrained" (the
    /// default), "square", "fixedSize" or "proportional".
    pub rect_constraint: String,
    /// Rectangle tool › gear › Fixed Size W and H in px; 0 is an empty field, as they start.
    pub rect_fixed_width: f32,
    pub rect_fixed_height: f32,
    /// Rectangle tool › gear › Proportional W : H, 1 : 1 to start.
    pub rect_ratio_width: f32,
    pub rect_ratio_height: f32,
    /// Rectangle tool › gear › From Center: every drag draws from its centre. Off to start.
    pub rect_from_center: bool,
    /// Freeform Pen › Curve Fit: how far (px) the fitted path may stray from the pointer trace.
    #[serde(default = "default_curve_fit")]
    pub curve_fit: f32,
    /// Pen › Auto Add/Delete: a Pen click on a segment of the active path adds an anchor there,
    /// on one of its anchors deletes it (#4144).
    #[serde(default = "yes")]
    pub pen_auto_add_delete: bool,
    /// Pen › gear › Path Options: the rubber band (off by default, as in Photoshop, #12900), the
    /// path colour and the line thickness.
    #[serde(default)]
    pub path_options: PathOptionsSettings,
    /// Marquee options bar: "normal" | "fixedRatio" | "fixedSize", with the ratio or size.
    #[serde(default = "default_marquee_style")]
    pub marquee_style: String,
    #[serde(default = "one")]
    pub marquee_width: f32,
    #[serde(default = "one")]
    pub marquee_height: f32,
    /// The unit Fixed Size's Width and Height show (a [`photocraft_engine::prefs::Unit`] name,
    /// picked by right-clicking them); the size itself stays in pixels (#7910).
    #[serde(default = "default_marquee_unit")]
    pub marquee_unit: String,
    /// Slice tool options bar: the same Styles as the marquee's, with the ratio or the size in px
    /// (#8360).
    #[serde(default = "default_marquee_style")]
    pub slice_style: String,
    #[serde(default = "one")]
    pub slice_width: f32,
    #[serde(default = "one")]
    pub slice_height: f32,
    /// Move tool: Auto-Select (with "layer" or "group" target) and Show Transform Controls.
    /// Auto-Select is on with the "layer" target by default, as Photoshop's Reset Tool leaves it
    /// (measured for #11380; #4056 had asked for "group"); ⌘/Ctrl-click inverts it.
    #[serde(default = "yes")]
    pub move_auto_select: bool,
    #[serde(default = "default_move_target")]
    pub move_target: String,
    #[serde(default)]
    pub move_show_transform: bool,
    /// Move tool options bar, gear menu (#11381), all on by default: outline the layer under the
    /// pointer, open the closed groups of a layer picked by a canvas click, and outline the layer
    /// whose Layers panel row is hovered. Preferences > Show Highlight on Rollover still gates
    /// the two outlines.
    #[serde(default = "yes")]
    pub move_show_hover_bounds: bool,
    #[serde(default = "yes")]
    pub move_expand_group_on_click: bool,
    #[serde(default = "yes")]
    pub move_show_layers_hover_bounds: bool,
    /// Free Transform and the Move tool's Transform controls: Show Reference Point (off by
    /// default, as in Photoshop, #11098), relative positioning (#11679), the last interpolation
    /// picked (unset follows General's default), Legacy scaling, the W/H link and unit.
    #[serde(default)]
    pub transform: TransformSettings,
    /// The Crop tool: ratio, W x H x Resolution, Delete Cropped Pixels, Fill, the guide
    /// overlay and the shield (#1919, #2443, #3823).
    #[serde(default)]
    pub crop: CropSettings,
    /// Perspective Crop's own W, H and Resolution fields; the Crop tool's are `crop.size`.
    #[serde(default)]
    pub perspective_crop: CropSizeFields,
    /// Perspective Crop's Show Grid.
    #[serde(default = "yes")]
    pub perspective_crop_grid: bool,
    /// Magic Eraser opacity % (tolerance, anti-alias and contiguous are shared with the Magic Wand
    /// and Paint Bucket).
    pub magic_eraser_opacity: f32,
    /// Background Eraser: sampling (continuous | once | backgroundSwatch), limits (discontiguous |
    /// contiguous | findEdges), tolerance % and Protect Foreground Color.
    pub bg_sampling: String,
    pub bg_limits: String,
    pub bg_tolerance: f32,
    pub bg_protect_fg: bool,
    /// The Background Eraser popup's "Tolerance:" pen control (#11910): `off`, `penPressure` (the
    /// reference's default) or `stylusWheel`.
    pub bg_tolerance_control: String,
    /// Color Replacement: mode (hue | saturation | color | luminosity), sampling (continuous |
    /// once | backgroundSwatch), limits (discontiguous | contiguous | findEdges), tolerance % and
    /// anti-alias, as `paint.colorReplacement` takes them.
    pub cr_mode: String,
    pub cr_sampling: String,
    pub cr_limits: String,
    pub cr_tolerance: f32,
    pub cr_anti_alias: bool,
    /// Zoom tool › Scrubby Zoom: dragging left/right zooms continuously (else a zoom rectangle).
    #[serde(default = "yes")]
    pub zoom_scrubby: bool,
    /// Zoom tool › Zoom In / Zoom Out: which way a click steps (⌥ turns it around). Reset Tool
    /// leaves it, as in Photoshop.
    #[serde(default = "yes")]
    pub zoom_in: bool,
    /// Hand tool › Scroll All Windows: a Hand drag pans every shown document view, not only the
    /// one dragged in (`scroll_all_windows.rs`). Shift held while dragging does the same.
    #[serde(default)]
    pub hand_scroll_all: bool,
    /// Pencil › Auto Erase: a stroke that starts on the foreground colour paints the background colour.
    #[serde(default)]
    pub pencil_auto_erase: bool,
    /// Brush › Mode: Clear, which erases with the Brush (Photoshop's painting-only mode, #3439).
    /// Not a blend mode, so it is kept beside the brush's `mode` rather than in it.
    #[serde(default)]
    pub brush_clear: bool,
    /// Pencil › Mode: Clear (see `brush_clear`).
    #[serde(default)]
    pub pencil_clear: bool,
    /// Eraser › Mode: `brush` (soft, anti-aliased) or `pencil` (hard, aliased pixels, through
    /// `paint.pencil`), as in Photoshop's options bar (#2662).
    #[serde(default = "default_eraser_mode")]
    pub eraser_mode: String,
    /// Eraser › Erase to History: the Eraser paints the History panel's source state back
    /// instead of erasing, as in Photoshop.
    #[serde(default)]
    pub erase_to_history: bool,
    /// Mixer Brush › Useful mixer brush combinations: the entry last picked, an index into
    /// `craft::draw::ui::MIXER_COMBINATIONS` (0 = Custom, #11946).
    pub mixer_combination: usize,
    /// Magnetic Lasso: detection width, edge contrast, frequency and Stylus Pressure.
    #[serde(default)]
    pub magnetic: MagneticSettings,
    /// Red Eye: pupil search size (1–100) and how far corrected pixels darken (0–100).
    #[serde(default = "fifty")]
    pub red_eye_pupil_size: f32,
    #[serde(default = "fifty")]
    pub red_eye_darken: f32,
    /// Eyedropper: Sample Size, Sample and Show Sampling Ring. The size is shared, as in
    /// Photoshop, with the ⌥-click eyedropper of the painting tools, the dialog eyedroppers and
    /// the Info panel.
    #[serde(default)]
    pub eyedropper: EyedropperOptions,
    /// Art History Brush: dab layout, Area (0–100), Tolerance (0–100).
    #[serde(default = "default_art_history_style")]
    pub art_history_style: String,
    #[serde(default = "fifty")]
    pub art_history_area: f32,
    #[serde(default)]
    pub art_history_tolerance: f32,
}

fn default_art_history_style() -> String {
    "tightShort".into()
}

pub(super) fn yes() -> bool {
    true
}

fn default_move_target() -> String {
    "layer".into()
}

fn default_pen_path_op() -> String {
    "newLayer".into()
}

fn default_shape_path_op() -> String {
    "newLayer".into()
}

fn default_curve_fit() -> f32 {
    2.0
}

fn default_eraser_mode() -> String {
    "brush".into()
}

fn default_marquee_style() -> String {
    "normal".into()
}

fn default_marquee_unit() -> String {
    "pixels".into()
}

fn one() -> f32 {
    1.0
}

fn fifty() -> f32 {
    50.0
}

/// The session brush starts out as the Brush's (the tool the app opens with).
pub(super) fn default_brush_tool() -> Tool {
    Tool::Brush
}

/// Each tool's Sample All Layers (the Paint Bucket calls it All Layers). Photoshop keeps one per
/// tool, all off by default except the Patch tool's Content-Aware Sample All Layers (#5524,
/// #12125): turning it on for the Magic Wand must not leave Blur or Smudge copying the composite
/// onto the active layer. The Mixer Brush keeps its own with the brush (`MixerSettings`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SampleAllLayers {
    pub magic_wand: bool,
    pub quick_selection: bool,
    pub object_selection: bool,
    pub paint_bucket: bool,
    pub magic_eraser: bool,
    pub spot_healing: bool,
    pub patch: bool,
    pub content_aware_move: bool,
    pub remove: bool,
    pub blur: bool,
    pub sharpen: bool,
    pub smudge: bool,
}

impl Default for SampleAllLayers {
    fn default() -> Self {
        Self {
            magic_wand: false,
            quick_selection: false,
            object_selection: false,
            paint_bucket: false,
            magic_eraser: false,
            spot_healing: false,
            patch: true,
            content_aware_move: false,
            remove: false,
            blur: false,
            sharpen: false,
            smudge: false,
        }
    }
}

impl SampleAllLayers {
    /// `tool`'s setting; false for a tool without the option.
    pub fn get(mut self, tool: Tool) -> bool {
        self.slot(tool).is_some_and(|v| *v)
    }

    /// `tool`'s setting, or `None` for a tool without the option.
    pub fn slot(&mut self, tool: Tool) -> Option<&mut bool> {
        Some(match tool {
            Tool::MagicWand => &mut self.magic_wand,
            Tool::QuickSelection => &mut self.quick_selection,
            Tool::ObjectSelection => &mut self.object_selection,
            Tool::PaintBucket => &mut self.paint_bucket,
            Tool::MagicEraser => &mut self.magic_eraser,
            Tool::SpotHealing => &mut self.spot_healing,
            Tool::Patch => &mut self.patch,
            Tool::ContentAwareMove => &mut self.content_aware_move,
            Tool::Remove => &mut self.remove,
            Tool::Blur => &mut self.blur,
            Tool::Sharpen => &mut self.sharpen,
            Tool::Smudge => &mut self.smudge,
            _ => return None,
        })
    }
}

impl Default for ToolOptions {
    fn default() -> Self {
        Self {
            tolerance: 32.0,
            contiguous: true,
            anti_alias: true,
            sample_all: SampleAllLayers::default(),
            object_finder: true,
            object_hard_edge: true,
            remove_new_layer: false,
            remove_after_each_stroke: true,
            feather: 0.0,
            gradient_style: "linear".into(),
            gradient_reverse: false,
            gradient_dither: true,
            gradient_classic: false,
            gradient_blend_mode: photocraft_color::BlendMode::Normal,
            fill_opacity: 100.0,
            bucket_fill_pattern: false,
            bucket_blend_mode: photocraft_color::BlendMode::Normal,
            bucket_clear: false,
            type_font: "Inter".into(),
            type_style: "Regular".into(),
            type_size: 50.0,
            type_aa: "sharp".into(),
            type_align: "left".into(),
            type_style_defaults: serde_json::Map::new(),
            type_direction: "auto".into(),
            clone_aligned: true,
            pattern_stamp_aligned: true,
            pattern_stamp_impressionist: false,
            pattern_stamp_scale: 100.0,
            pattern_stamp_angle: 0.0,
            clone_sample: "current".into(),
            spot_type: "contentAware".into(),
            patch_mode: "source".into(),
            patch_content_aware: false,
            patch_structure: 4.0,
            patch_color: 0.0,
            cam_mode: "move".into(),
            cam_structure: 4.0,
            cam_color: 0.0,
            cam_transform_on_drop: true,
            tone_range: "midtones".into(),
            exposure: 50.0,
            protect_tones: true,
            sponge_mode: "desaturate".into(),
            sponge_flow: 50.0,
            vibrance: true,
            strength: 50.0,
            protect_detail: true,
            finger_painting: false,
            smudge_mode: photocraft_color::BlendMode::Normal,
            enhance_edge: false,
            vector_mode: VectorMode::Path,
            pen_path_op: default_pen_path_op(),
            shape_path_op: default_shape_path_op(),
            shape_mode: VectorMode::Shape,
            shape_fill: true,
            stroke_width: 0.0,
            shape_stroke: Default::default(),
            shape_fill_gradient: None,
            shape_stroke_gradient: None,
            corner_radius: 0.0,
            align_edges: true,
            polygon_sides: 5,
            line_weight: 1.0,
            arrow_start: false,
            arrow_end: false,
            arrow_width: 5.0,
            arrow_length: 10.0,
            arrow_concavity: 0.0,
            rect_constraint: "unconstrained".into(),
            rect_fixed_width: 0.0,
            rect_fixed_height: 0.0,
            rect_ratio_width: 1.0,
            rect_ratio_height: 1.0,
            rect_from_center: false,
            curve_fit: default_curve_fit(),
            pen_auto_add_delete: true,
            path_options: PathOptionsSettings::default(),
            marquee_style: default_marquee_style(),
            marquee_width: 1.0,
            marquee_height: 1.0,
            marquee_unit: default_marquee_unit(),
            slice_style: default_marquee_style(),
            slice_width: 1.0,
            slice_height: 1.0,
            move_auto_select: true,
            move_target: default_move_target(),
            move_show_transform: false,
            move_show_hover_bounds: true,
            move_expand_group_on_click: true,
            move_show_layers_hover_bounds: true,
            transform: TransformSettings::default(),
            crop: CropSettings::default(),
            perspective_crop: CropSizeFields::default(),
            perspective_crop_grid: true,
            magic_eraser_opacity: 100.0,
            bg_sampling: "continuous".into(),
            bg_limits: "contiguous".into(),
            bg_tolerance: 50.0,
            bg_protect_fg: false,
            bg_tolerance_control: "penPressure".into(),
            cr_mode: "color".into(),
            cr_sampling: "continuous".into(),
            cr_limits: "contiguous".into(),
            cr_tolerance: 30.0,
            cr_anti_alias: true,
            zoom_scrubby: true,
            zoom_in: true,
            hand_scroll_all: false,
            pencil_auto_erase: false,
            brush_clear: false,
            pencil_clear: false,
            eraser_mode: default_eraser_mode(),
            erase_to_history: false,
            mixer_combination: 0,
            magnetic: MagneticSettings::default(),
            red_eye_pupil_size: 50.0,
            red_eye_darken: 50.0,
            eyedropper: EyedropperOptions::default(),
            art_history_style: default_art_history_style(),
            art_history_area: 50.0,
            art_history_tolerance: 0.0,
        }
    }
}

#[cfg(test)]
#[path = "../cam_transform_on_drop_default_tests.rs"]
mod cam_transform_on_drop_default_tests;