GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
use super::dnd::{group_of, selection};
use super::libraries::SwatchLibraries;
use super::{
    Kind, LibraryKind, PanelDrag, Response, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, set_pstate,
    widgets,
};

/// The selected swatches and groups that can be deleted: every color group in the document and
/// every swatch that `Swatch::is_reserved` does not reserve (None and Registration). Names the
/// document does not hold are left out.
pub(super) fn deletable(app: &VectorcraftApp, sel: &[String]) -> Vec<String> {
    let Some(d) = app.session.active().map(|st| &st.doc) else { return vec![] };
    sel.iter().filter(|n| d.swatch(n).map_or_else(|| d.swatch_groups.iter().any(|g| g.name == **n), |w| !w.is_reserved())).cloned().collect()
}

/// The selected swatch when exactly one swatch with an editor is selected (not None, Registration
/// or a group).
pub(super) fn editable(app: &VectorcraftApp, sel: &[String]) -> Option<String> {
    match sel {
        [n] if app.session.active().and_then(|st| st.doc.swatch(n)).is_some_and(|w| !w.is_reserved()) => Some(n.clone()),
        _ => None,
    }
}

/// The selected solid-colour swatches in selection order (Merge Swatches keeps the first).
pub(super) fn mergeable(app: &VectorcraftApp, sel: &[String]) -> Vec<String> {
    let Some(st) = app.session.active() else { return vec![] };
    sel.iter().filter(|n| st.doc.swatch(n).is_some_and(|w| w.paint.color().is_some())).cloned().collect()
}

/// The first selected colour group (Ungroup Color Group).
pub(super) fn selected_group(app: &VectorcraftApp, sel: &[String]) -> Option<String> {
    let d = &app.session.active()?.doc;
    sel.iter().find(|n| d.swatch_groups.iter().any(|g| g.name == **n)).cloned()
}

/// The selected color group when it is the whole selection (Color Group Options).
pub(super) fn sole_group(app: &VectorcraftApp, sel: &[String]) -> Option<String> {
    match sel {
        [_] => selected_group(app, sel),
        _ => None,
    }
}

/// Edit or Apply Color Group: Recolor Artwork on colour group `group` (and the selected art).
pub(super) fn edit_group(app: &mut VectorcraftApp, group: &str) {
    app.run("ui.recolorDialog", json!({ "group": group })).ok();
}

/// Delete `names` (swatches and colour groups) after asking, or at once with `now` (Alt-click).
pub(super) fn delete(app: &mut VectorcraftApp, names: Vec<String>, now: bool) {
    let params = json!({"names": names});
    if now {
        app.run("swatch.delete", params).ok();
        return;
    }
    let message = match names.as_slice() {
        [n] => crate::i18n::fmt(tl!("Delete “{name}”?"), &[("name", n)]),
        _ => crate::i18n::tn(names.len() as u64, "Delete this {n} swatch or group?", "Delete these {n} swatches and groups?"),
    };
    crate::dialogs::confirm::ask(app, &message, tl!("Art using a deleted global swatch keeps its colour."), "swatch.delete", params);
}

pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) {
    let kind: Kind = pstate(ui.ctx(), "swatch-kind");
    widgets::bottom_bar(ui, |ui| {
        let open = library_panel::any_open::<SwatchLibraries>(&app.ui);
        let lr = widgets::icon_button(ui, "library", SwatchLibraries::MENU, open, 24.0);
        egui::Popup::menu(&lr).show(|ui| {
            ui.set_min_width(200.0);
            library_panel::library_menu::<SwatchLibraries>(app, ui);
        });
        let kr = widgets::icon_button(ui, "dc-swatch-kinds", tl!("Show Swatch Kinds"), kind != Kind::All, 24.0);
        egui::Popup::menu(&kr).show(|ui| {
            for (k, label) in Kind::ALL {
                if menu_item(ui, label, true, k == kind) {
                    set_pstate(ui.ctx(), "swatch-kind", k);
                }
            }
        });
        // With a colour group selected the options button edits or applies the group.
        let opts = editable(app, sel);
        if let Some(g) = selected_group(app, sel).filter(|_| opts.is_none()) {
            if widgets::icon_button(ui, "palette", tl!("Edit or Apply Color Group"), false, 24.0).clicked() {
                edit_group(app, &g);
            }
        } else if widgets::icon_button_enabled(ui, "dc-options", tl!("Swatch Options"), false, opts.is_some(), 24.0).clicked()
            && let Some(n) = opts
        {
            app.run("ui.swatchOptions", json!({"name": n})).ok();
        }
        ui.add_space((ui.available_width() - 3.0 * 28.0).max(0.0));
        if widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0).clicked() {
            app.run("ui.newColorGroup", json!({"swatches": deletable(app, sel)})).ok();
        }
        // Alt-click skips the dialog; Ctrl/Cmd-click makes a spot color, and Ctrl/Cmd+Shift-click
        // makes a global process color. Swatches dragged from the list and dropped on it are
        // duplicated.
        let copies = dragged_swatches(app, ui.ctx());
        let new = widgets::icon_button(ui, "dc-new-item", tl!("New Swatch"), false, 24.0);
        if new.clicked() {
            new_swatch(app, sel, ui.input(|i| i.modifiers));
        }
        drop_on_new(app, ui, &new, copies);
        // Alt-click deletes without asking. Swatches or color groups dragged from the list can be
        // dropped on it, also with nothing selected: the button is enabled while they are held.
        let del = deletable(app, sel);
        let dragged = dragged_deletable(app, ui.ctx());
        let trash = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty() || !dragged.is_empty(), 24.0);
        if trash.clicked() && !del.is_empty() {
            delete(app, del, ui.input(|i| i.modifiers.alt));
        }
        drop_on_delete(app, ui, &trash, dragged);
    });
}

/// The panel state key of the document (`uid`) the swatches being dragged from the list belong to.
pub(super) const DRAG_DOC: &str = "swatch-drag-doc";

/// The swatches and color groups of the active document being dragged from the list that Delete
/// Swatch can delete: neither None nor Registration, and still in the document. Empty for any other
/// drag, and for a drag started in another document.
fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
    let Some(st) = app.session.active() else { return vec![] };
    let d = &st.doc;
    dragged_rows(app, ctx).into_iter().filter(|n| d.swatch_name_taken(n) && d.swatch(n).is_none_or(|w| !w.is_reserved())).collect()
}

/// The names of the swatches or color groups of the active document being dragged from the list,
/// in panel order. Empty for any other drag, and for a drag started in another document.
fn dragged_rows(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
    let Some(st) = app.session.active() else { return vec![] };
    if pstate::<Option<u64>>(ctx, DRAG_DOC) != Some(st.uid) {
        return vec![];
    }
    match egui::DragAndDrop::payload::<PanelDrag>(ctx).as_deref() {
        Some(PanelDrag::Paint { rows: Some(r), .. }) => r.names.clone(),
        _ => vec![],
    }
}

/// Swatches or color groups (`names`) dragged onto Delete Swatch (`button`): the button is
/// outlined while they are held over it, and the release of the primary button asks to delete them
/// as a plain click does ([`delete`]); Alt does not skip the question. The release of another
/// button ends the drag, and other drags are left to their own targets.
fn drop_on_delete(app: &mut VectorcraftApp, ui: &Ui, button: &Response, names: Vec<String>) {
    if names.is_empty() || button.dnd_hover_payload::<PanelDrag>().is_none() {
        return;
    }
    widgets::drop_target_outline(ui, button.rect);
    if !ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)) {
        return;
    }
    if button.dnd_release_payload::<PanelDrag>().is_some() {
        delete(app, names, false);
    }
}

/// The swatches of the active document being dragged from the list that New Swatch can duplicate,
/// in panel order: the dragged rows ([`dragged_rows`]) that are swatches still in the document,
/// other than None and Registration.
fn dragged_swatches(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
    let Some(st) = app.session.active() else { return vec![] };
    dragged_rows(app, ctx).into_iter().filter(|n| st.doc.swatch(n).is_some_and(|w| !w.is_reserved())).collect()
}

/// Swatches (`names`) dragged onto New Swatch (`button`): the button is outlined while they are
/// held over it, and the release of the primary button duplicates them ([`duplicate`]), whatever
/// modifiers are held. The release of another button ends the drag, and other drags are left to
/// their own targets.
fn drop_on_new(app: &mut VectorcraftApp, ui: &Ui, button: &Response, names: Vec<String>) {
    if names.is_empty() || button.dnd_hover_payload::<PanelDrag>().is_none() {
        return;
    }
    widgets::drop_target_outline(ui, button.rect);
    if !ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)) {
        return;
    }
    if button.dnd_release_payload::<PanelDrag>().is_some() {
        duplicate(app, ui.ctx(), &names);
    }
}

/// Duplicates the swatches `names` (`swatch.duplicate`, each copy just after its swatch and in its
/// color group) in one undo step and selects the copies. A failure is shown in the status bar and
/// changes nothing.
fn duplicate(app: &mut VectorcraftApp, ctx: &egui::Context, names: &[String]) {
    let made = if let [name] = names {
        app.run("swatch.duplicate", json!({ "name": name })).map(|r| vec![r])
    } else {
        let commands: Vec<Value> = names.iter().map(|n| json!({ "command": "swatch.duplicate", "params": { "name": n } })).collect();
        app.run("command.batch", json!({ "label": "Duplicate Swatch", "commands": commands }))
            .map(|r| r["results"].as_array().cloned().unwrap_or_default())
    };
    match made {
        Ok(made) => set_pstate(ctx, "swatch-selected", made.iter().filter_map(|r| r["name"].as_str().map(str::to_string)).collect::<Vec<_>>()),
        Err(e) => app.status(e),
    }
}

/// The colour group the selection points at: the last selected group, or the group of the last
/// selected swatch.
fn target_group(app: &VectorcraftApp, sel: &[String]) -> Option<String> {
    group_of(&app.session.active()?.doc, sel.last()?)
}

/// New Swatch from the active paint (a color goes into the selected color group), for a click
/// with modifiers `m`: a plain click opens the dialog and an Alt-click saves at once. Cmd/Ctrl
/// makes a color a spot color, and Cmd/Ctrl+Shift makes it a global process color.
pub(super) fn new_swatch(app: &mut VectorcraftApp, sel: &[String], m: egui::Modifiers) {
    let paint = active_paint(app);
    let group = paint.color().and_then(|_| target_group(app, sel));
    let (spot, global) = (m.command && !m.shift, m.command && m.shift);
    if !m.alt {
        app.run("ui.newSwatch", json!({"spot": spot, "global": global, "group": group})).ok();
        return;
    }
    let mut params = crate::panels::swatch_paint_params(&paint);
    if paint.color().is_some() {
        params["spot"] = json!(spot);
        params["global"] = json!(global);
    }
    if let Some(g) = group {
        params["group"] = json!(g);
    }
    app.run("swatch.new", params).ok();
}

pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
    let view = app.ui.swatches_view;
    let selected = selection(app, ui);
    let del = deletable(app, &selected);
    let opts = editable(app, &selected);
    if menu_item(ui, tl!("New Swatch…"), true, false) {
        new_swatch(app, &selected, egui::Modifiers::NONE);
    }
    if menu_item(ui, tl!("New Color Group…"), true, false) {
        app.run("ui.newColorGroup", json!({"swatches": del})).ok();
    }
    if menu_item(ui, tl!("Duplicate Swatch"), opts.is_some(), false)
        && let Some(n) = &opts
    {
        app.run("swatch.duplicate", json!({"name": n})).ok();
    }
    // The first selected colour is kept.
    let merge = mergeable(app, &selected);
    if menu_item(ui, tl!("Merge Swatches"), merge.len() > 1, false) {
        app.run("swatch.merge", json!({ "names": merge })).ok();
    }
    if menu_item(ui, tl!("Delete Swatch"), !del.is_empty(), false) {
        delete(app, del, false);
    }
    let group = selected_group(app, &selected);
    if menu_item(ui, tl!("Edit or Apply Color Group…"), group.is_some(), false)
        && let Some(g) = &group
    {
        edit_group(app, g);
    }
    if menu_item(ui, tl!("Ungroup Color Group"), group.is_some(), false)
        && let Some(g) = group
    {
        app.run("swatch.ungroup", json!({ "name": g })).ok();
    }
    let sole = sole_group(app, &selected);
    if menu_item(ui, tl!("Color Group Options…"), sole.is_some(), false)
        && let Some(g) = sole
    {
        app.run("ui.colorGroupOptions", json!({ "group": g })).ok();
    }
    if menu_item(ui, tl!("Select All Unused"), true, false)
        && let Ok(r) = app.run("swatch.unused", json!({}))
    {
        let names: Vec<String> = r["names"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
        set_pstate(ui.ctx(), "swatch-selected", names);
    }
    if menu_item(ui, tl!("Add Used Colors"), true, false) {
        app.run("swatch.addUsedColors", json!({})).ok();
    }
    ui.separator();
    if menu_item(ui, tl!("Sort by Name"), true, false) {
        app.run("swatch.sortByName", json!({})).ok();
    }
    if menu_item(ui, tl!("Sort by Kind"), true, false) {
        app.run("swatch.sortByKind", json!({})).ok();
    }
    ui.separator();
    for (v, label) in View::ALL {
        if menu_item(ui, label, true, v == view) {
            app.run("ui.panelView", json!({ "panel": "swatches", "view": v })).ok();
        }
    }
    ui.separator();
    let find: bool = pstate(ui.ctx(), "swatch-show-find");
    if menu_item(ui, tl!("Show Find Field"), true, find) {
        set_pstate(ui.ctx(), "swatch-show-find", !find);
    }
    let recent = app.ui.swatches_show_recent_colors;
    if menu_item(ui, tl!("Show Recent Colors"), true, recent) {
        app.ui.swatches_show_recent_colors = !recent;
    }
    ui.separator();
    if menu_item(ui, tl!("Swatch Options…"), opts.is_some(), false)
        && let Some(n) = opts
    {
        app.run("ui.swatchOptions", json!({"name": n})).ok();
    }
    if menu_item(ui, tl!("Spot Colors…"), app.session.active().is_some(), false) {
        app.run("ui.spotColors", json!({})).ok();
    }
    ui.separator();
    ui.menu_button(tl!("Open Swatch Library"), |ui| library_panel::library_menu::<SwatchLibraries>(app, ui));
    if menu_item(ui, tl!("Save Swatch Library…"), true, false) {
        app.run("ui.saveSwatchLibrary", json!({ "names": deletable(app, &selected) })).ok();
    }
}