From 28c2a40418363f72158acb26cb702be5f58e2ed4 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 25 Oct 2026 21:34:23 +1000 Subject: [PATCH 01/16] HW-SURFACE: control-surface engine crate (ported from TactileBridge) crates/surface (lightcraft-surface, L2): devices and their controls (MX Creative Console Keypad and Dialpad, its Actions Ring, the Loupedeck+), layouts, profiles and pages, pages that follow the app's context, dial motion (acceleration, fine and big steps, per-value tuning), coalescing and echo suppression, the surface protocol and pairing, and TactileBridge / Loupedeck profile import. The engine, its settings design, defaults, curated layouts and the hand-drawn icon pack (assets/surface-icons) are ported from TactileBridge, Portions Copyright (c) 2026 RAD Films - Roman Alurkoff, contributed under the MIT License; each ported file says so (NOTICE, assets/ATTRIBUTION.md). No Capture One material is included. Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 3 + NOTICE | 7 + assets/ATTRIBUTION.md | 2 + assets/surface-icons/LICENSE.txt | 24 + assets/surface-icons/add-color-readout.svg | 7 + assets/surface-icons/aperture-down.svg | 9 + assets/surface-icons/aperture-up.svg | 9 + assets/surface-icons/apply-adjustments.svg | 7 + assets/surface-icons/apply-normalization.svg | 6 + assets/surface-icons/auto-adjust.svg | 8 + assets/surface-icons/auto-focus-fine.svg | 7 + assets/surface-icons/auto-focus.svg | 6 + assets/surface-icons/auto-sync.svg | 6 + assets/surface-icons/black.svg | 4 + assets/surface-icons/blur-brush.svg | 7 + assets/surface-icons/brightness.svg | 11 + assets/surface-icons/brush-erase.svg | 7 + assets/surface-icons/brush-flow.svg | 8 + assets/surface-icons/brush-hardness.svg | 9 + assets/surface-icons/brush-new.svg | 9 + assets/surface-icons/brush-opacity.svg | 9 + assets/surface-icons/brush-size.svg | 9 + assets/surface-icons/burn.svg | 8 + assets/surface-icons/bw-blue.svg | 6 + assets/surface-icons/bw-cyan.svg | 6 + assets/surface-icons/bw-enable.svg | 6 + assets/surface-icons/bw-green.svg | 6 + assets/surface-icons/bw-highlights-hue.svg | 15 + assets/surface-icons/bw-highlights-sat.svg | 12 + assets/surface-icons/bw-magenta.svg | 6 + assets/surface-icons/bw-orange.svg | 6 + assets/surface-icons/bw-red.svg | 6 + assets/surface-icons/bw-shadows-hue.svg | 15 + assets/surface-icons/bw-shadows-sat.svg | 12 + assets/surface-icons/bw-yellow.svg | 6 + assets/surface-icons/capture.svg | 6 + assets/surface-icons/ce-blue-hue.svg | 7 + assets/surface-icons/ce-blue-light.svg | 7 + assets/surface-icons/ce-blue-sat.svg | 7 + assets/surface-icons/ce-cyan-hue.svg | 7 + assets/surface-icons/ce-cyan-light.svg | 7 + assets/surface-icons/ce-cyan-sat.svg | 7 + assets/surface-icons/ce-green-hue.svg | 7 + assets/surface-icons/ce-green-light.svg | 7 + assets/surface-icons/ce-green-sat.svg | 7 + assets/surface-icons/ce-magenta-hue.svg | 7 + assets/surface-icons/ce-magenta-light.svg | 7 + assets/surface-icons/ce-magenta-sat.svg | 7 + assets/surface-icons/ce-orange-hue.svg | 7 + assets/surface-icons/ce-orange-light.svg | 7 + assets/surface-icons/ce-orange-sat.svg | 7 + assets/surface-icons/ce-purple-hue.svg | 7 + assets/surface-icons/ce-purple-light.svg | 7 + assets/surface-icons/ce-purple-sat.svg | 7 + assets/surface-icons/ce-red-hue.svg | 7 + assets/surface-icons/ce-red-light.svg | 7 + assets/surface-icons/ce-red-sat.svg | 7 + assets/surface-icons/ce-yellow-hue.svg | 7 + assets/surface-icons/ce-yellow-light.svg | 7 + assets/surface-icons/ce-yellow-sat.svg | 7 + assets/surface-icons/clarity.svg | 7 + .../surface-icons/clear-compare-variant.svg | 7 + assets/surface-icons/clear-mask.svg | 7 + assets/surface-icons/clear-rating.svg | 7 + assets/surface-icons/clone-brush.svg | 7 + assets/surface-icons/clone-variant.svg | 9 + assets/surface-icons/color-burn.svg | 7 + assets/surface-icons/color-dodge.svg | 7 + assets/surface-icons/color-picker-tool.svg | 7 + assets/surface-icons/color-tag-blue.svg | 8 + assets/surface-icons/color-tag-green.svg | 8 + assets/surface-icons/color-tag-none.svg | 8 + assets/surface-icons/color-tag-orange.svg | 8 + assets/surface-icons/color-tag-pink.svg | 8 + assets/surface-icons/color-tag-purple.svg | 8 + assets/surface-icons/color-tag-red.svg | 8 + assets/surface-icons/color-tag-yellow.svg | 8 + assets/surface-icons/composition-mode.svg | 6 + assets/surface-icons/contrast-brush.svg | 7 + assets/surface-icons/contrast.svg | 26 + assets/surface-icons/copy-adjustments.svg | 10 + assets/surface-icons/copy-and-apply-adj.svg | 7 + assets/surface-icons/crop-tool.svg | 9 + assets/surface-icons/darken.svg | 6 + assets/surface-icons/decrease-zoom.svg | 6 + assets/surface-icons/defringe.svg | 10 + assets/surface-icons/delete-color-readout.svg | 7 + assets/surface-icons/delete.svg | 7 + assets/surface-icons/demote-variant.svg | 8 + assets/surface-icons/desaturate-brush.svg | 10 + assets/surface-icons/deselect-all.svg | 8 + assets/surface-icons/deselect-primary.svg | 6 + assets/surface-icons/direct-color-editor.svg | 8 + assets/surface-icons/distortion.svg | 9 + assets/surface-icons/dodge.svg | 8 + assets/surface-icons/draw-clone-tool.svg | 9 + assets/surface-icons/draw-heal-tool.svg | 9 + assets/surface-icons/draw-mask-tool.svg | 7 + assets/surface-icons/edit-all-selected.svg | 9 + assets/surface-icons/erase-mask-tool.svg | 7 + assets/surface-icons/export-originals.svg | 7 + assets/surface-icons/export-variants.svg | 7 + assets/surface-icons/exposure-bias-down.svg | 6 + assets/surface-icons/exposure-bias-up.svg | 6 + assets/surface-icons/exposure-brush.svg | 7 + assets/surface-icons/exposure-meter.svg | 6 + assets/surface-icons/exposure.svg | 42 + assets/surface-icons/feather-mask.svg | 7 + assets/surface-icons/fill-mask.svg | 7 + assets/surface-icons/filter-1-star.svg | 11 + assets/surface-icons/filter-2-stars.svg | 11 + assets/surface-icons/filter-3-stars.svg | 11 + assets/surface-icons/filter-4-stars.svg | 11 + assets/surface-icons/filter-5-stars.svg | 11 + assets/surface-icons/filter-approved.svg | 8 + assets/surface-icons/filter-color-tag.svg | 9 + assets/surface-icons/filter-flag.svg | 8 + assets/surface-icons/filter-green.svg | 8 + assets/surface-icons/filter-no-flag.svg | 9 + assets/surface-icons/filter-purple.svg | 8 + assets/surface-icons/filter-rating-1-star.svg | 11 + .../surface-icons/filter-rating-2-stars.svg | 11 + .../surface-icons/filter-rating-3-stars.svg | 11 + .../surface-icons/filter-rating-4-stars.svg | 11 + .../surface-icons/filter-rating-5-stars.svg | 11 + assets/surface-icons/filter-rating-none.svg | 12 + assets/surface-icons/filter-red.svg | 8 + assets/surface-icons/filter-rejected.svg | 8 + assets/surface-icons/filter-tag-blue.svg | 8 + assets/surface-icons/filter-tag-green.svg | 8 + assets/surface-icons/filter-tag-none.svg | 8 + assets/surface-icons/filter-tag-orange.svg | 8 + assets/surface-icons/filter-tag-pink.svg | 8 + assets/surface-icons/filter-tag-purple.svg | 8 + assets/surface-icons/filter-tag-red.svg | 8 + assets/surface-icons/filter-tag-yellow.svg | 8 + assets/surface-icons/filter-yellow.svg | 8 + assets/surface-icons/first-image.svg | 6 + assets/surface-icons/focus-assist.svg | 6 + assets/surface-icons/focus-meter-tool.svg | 7 + assets/surface-icons/focus-point-tool.svg | 7 + assets/surface-icons/full-screen.svg | 7 + assets/surface-icons/grain-granularity.svg | 14 + assets/surface-icons/grain-impact.svg | 12 + assets/surface-icons/hard-light.svg | 7 + assets/surface-icons/heal-brush.svg | 7 + assets/surface-icons/highlight-brush.svg | 7 + assets/surface-icons/highlight-lightness.svg | 9 + assets/surface-icons/highlight-tone-x.svg | 9 + assets/surface-icons/highlight-tone-y.svg | 8 + assets/surface-icons/highlight.svg | 3 + assets/surface-icons/histogram-view.svg | 6 + assets/surface-icons/import-images.svg | 7 + assets/surface-icons/increase-zoom.svg | 6 + assets/surface-icons/invert-mask.svg | 7 + assets/surface-icons/invert-selection.svg | 8 + assets/surface-icons/iso-down.svg | 9 + assets/surface-icons/iso-up.svg | 9 + assets/surface-icons/kelvin.svg | 4 + assets/surface-icons/keystone-horizontal.svg | 7 + assets/surface-icons/keystone-tool.svg | 6 + assets/surface-icons/keystone-vertical.svg | 7 + assets/surface-icons/last-image.svg | 6 + assets/surface-icons/layer-opacity.svg | 7 + assets/surface-icons/light-falloff.svg | 8 + assets/surface-icons/lighten.svg | 6 + assets/surface-icons/linear-gradient-tool.svg | 7 + assets/surface-icons/live-view.svg | 7 + assets/surface-icons/loupe-tool.svg | 6 + assets/surface-icons/luma-range.svg | 6 + assets/surface-icons/mask-invert.svg | 9 + assets/surface-icons/mask-next.svg | 7 + assets/surface-icons/mask-previous.svg | 7 + assets/surface-icons/mask-visible.svg | 8 + assets/surface-icons/master-tone-x.svg | 11 + assets/surface-icons/master-tone-y.svg | 11 + assets/surface-icons/midtone-lightness.svg | 9 + assets/surface-icons/midtone-tone-x.svg | 10 + assets/surface-icons/midtone-tone-y.svg | 10 + assets/surface-icons/moire-amount.svg | 7 + assets/surface-icons/moire-pattern.svg | 9 + assets/surface-icons/move-to-trash.svg | 7 + assets/surface-icons/move-tool.svg | 7 + assets/surface-icons/multiply.svg | 6 + assets/surface-icons/new-clone-layer.svg | 7 + assets/surface-icons/new-empty-layer.svg | 7 + assets/surface-icons/new-filled-layer.svg | 7 + assets/surface-icons/new-heal-layer.svg | 7 + assets/surface-icons/new-variant.svg | 9 + assets/surface-icons/next-collection.svg | 6 + assets/surface-icons/next-group.svg | 6 + assets/surface-icons/next-image-import.svg | 6 + assets/surface-icons/next-image.svg | 6 + assets/surface-icons/next-set.svg | 6 + assets/surface-icons/nr-color.svg | 8 + assets/surface-icons/nr-detail.svg | 7 + assets/surface-icons/nr-luminance.svg | 7 + assets/surface-icons/nr-single-pixel.svg | 7 + assets/surface-icons/overlay-horizontal.svg | 7 + assets/surface-icons/overlay-opacity.svg | 7 + assets/surface-icons/overlay-scale.svg | 6 + assets/surface-icons/overlay-tool.svg | 7 + assets/surface-icons/overlay-vertical.svg | 7 + assets/surface-icons/overlay.svg | 7 + assets/surface-icons/pan-tool.svg | 9 + assets/surface-icons/pen-black.svg | 10 + assets/surface-icons/pen-blue.svg | 10 + assets/surface-icons/pen-green.svg | 10 + assets/surface-icons/pen-red.svg | 10 + assets/surface-icons/pen-size.svg | 9 + assets/surface-icons/pen-white.svg | 10 + assets/surface-icons/pen-yellow.svg | 10 + .../surface-icons/pick-color-correction.svg | 11 + assets/surface-icons/pick-curve-point.svg | 7 + assets/surface-icons/pick-focus-point.svg | 7 + assets/surface-icons/pick-highlight-level.svg | 9 + assets/surface-icons/pick-luma-curve.svg | 6 + assets/surface-icons/pick-norm-target.svg | 10 + assets/surface-icons/pick-shadow-level.svg | 9 + assets/surface-icons/pick-skin-color.svg | 9 + assets/surface-icons/pick-variant.svg | 6 + assets/surface-icons/preset-apply-ai.svg | 11 + assets/surface-icons/preset-apply.svg | 9 + assets/surface-icons/previous-collection.svg | 6 + assets/surface-icons/previous-group.svg | 6 + .../surface-icons/previous-image-import.svg | 6 + assets/surface-icons/previous-image.svg | 6 + assets/surface-icons/previous-set.svg | 6 + assets/surface-icons/print.svg | 7 + assets/surface-icons/process.svg | 7 + assets/surface-icons/promote-variant.svg | 8 + assets/surface-icons/radial-gradient-tool.svg | 7 + assets/surface-icons/rasterize-mask.svg | 7 + assets/surface-icons/rate-1-star.svg | 7 + assets/surface-icons/rate-2-star.svg | 8 + assets/surface-icons/rate-2-stars.svg | 8 + assets/surface-icons/rate-3-star.svg | 9 + assets/surface-icons/rate-3-stars.svg | 9 + assets/surface-icons/rate-4-star.svg | 10 + assets/surface-icons/rate-4-stars.svg | 10 + assets/surface-icons/rate-5-star.svg | 11 + assets/surface-icons/rate-5-stars.svg | 11 + assets/surface-icons/recipe-proofing.svg | 7 + assets/surface-icons/redo.svg | 6 + assets/surface-icons/refine-mask.svg | 7 + assets/surface-icons/regenerate-previews.svg | 10 + assets/surface-icons/remove-layer.svg | 7 + assets/surface-icons/rename.svg | 9 + assets/surface-icons/reset-adjustments.svg | 8 + assets/surface-icons/reset-develop.svg | 9 + assets/surface-icons/rotate-freehand-tool.svg | 9 + assets/surface-icons/rotate-left.svg | 8 + assets/surface-icons/rotate-photo-left.svg | 9 + assets/surface-icons/rotate-photo-right.svg | 9 + assets/surface-icons/rotate-right.svg | 8 + assets/surface-icons/rotation-tool.svg | 7 + assets/surface-icons/saturation-brush.svg | 7 + assets/surface-icons/saturation.svg | 13 + assets/surface-icons/select-1-star.svg | 10 + assets/surface-icons/select-2-stars.svg | 10 + assets/surface-icons/select-3-stars.svg | 10 + assets/surface-icons/select-4-stars.svg | 10 + assets/surface-icons/select-5-stars.svg | 10 + assets/surface-icons/select-all-photos.svg | 9 + assets/surface-icons/select-all.svg | 8 + assets/surface-icons/select-background.svg | 7 + assets/surface-icons/select-brush.svg | 7 + assets/surface-icons/select-by-color.svg | 7 + assets/surface-icons/select-by-shape.svg | 8 + assets/surface-icons/select-by-tone.svg | 8 + assets/surface-icons/select-eraser.svg | 9 + assets/surface-icons/select-freehand.svg | 6 + assets/surface-icons/select-layer-down.svg | 7 + assets/surface-icons/select-layer-up.svg | 7 + assets/surface-icons/select-magic-wand.svg | 9 + assets/surface-icons/select-no-photos.svg | 8 + assets/surface-icons/select-pen.svg | 9 + assets/surface-icons/select-primary-only.svg | 6 + .../surface-icons/select-same-color-tag.svg | 8 + .../surface-icons/select-same-sequence-id.svg | 10 + .../surface-icons/select-same-variant-pos.svg | 7 + assets/surface-icons/select-smooth.svg | 6 + assets/surface-icons/select-subject.svg | 7 + assets/surface-icons/select-tag-blue.svg | 7 + assets/surface-icons/select-tag-green.svg | 7 + assets/surface-icons/select-tag-none.svg | 7 + assets/surface-icons/select-tag-orange.svg | 7 + assets/surface-icons/select-tag-pink.svg | 7 + assets/surface-icons/select-tag-purple.svg | 7 + assets/surface-icons/select-tag-red.svg | 7 + assets/surface-icons/select-tag-yellow.svg | 7 + assets/surface-icons/select-tool.svg | 8 + assets/surface-icons/select-unrated.svg | 10 + assets/surface-icons/set-compare-variant.svg | 7 + assets/surface-icons/shadow-brush.svg | 7 + assets/surface-icons/shadow-lightness.svg | 9 + assets/surface-icons/shadow-tone-x.svg | 8 + assets/surface-icons/shadow-tone-y.svg | 8 + assets/surface-icons/shadow.svg | 3 + assets/surface-icons/sharpen-brush.svg | 7 + assets/surface-icons/sharpening-amount.svg | 9 + assets/surface-icons/sharpening-halo.svg | 8 + assets/surface-icons/sharpening-radius.svg | 10 + assets/surface-icons/sharpening-threshold.svg | 7 + assets/surface-icons/sharpness-falloff.svg | 7 + assets/surface-icons/show-filmstrip.svg | 6 + assets/surface-icons/show-grid.svg | 6 + assets/surface-icons/show-guides.svg | 6 + assets/surface-icons/show-hide-browser.svg | 7 + assets/surface-icons/show-hide-viewer.svg | 7 + assets/surface-icons/show-histogram.svg | 6 + assets/surface-icons/show-in-file-system.svg | 6 + assets/surface-icons/show-in-library.svg | 6 + assets/surface-icons/show-metadata.svg | 6 + assets/surface-icons/shutter-speed-down.svg | 6 + assets/surface-icons/shutter-speed-up.svg | 6 + assets/surface-icons/slide-show.svg | 7 + assets/surface-icons/snap-to-90.svg | 8 + assets/surface-icons/soft-light.svg | 7 + assets/surface-icons/spot-radius.svg | 9 + assets/surface-icons/spot-removal-tool.svg | 9 + assets/surface-icons/straighten-tool.svg | 9 + assets/surface-icons/structure.svg | 6 + .../surface-icons/switch-crop-orientation.svg | 6 + assets/surface-icons/tint.svg | 4 + assets/surface-icons/toggle-before-after.svg | 8 + assets/surface-icons/toggle-exposure-warn.svg | 6 + assets/surface-icons/toggle-focus-mask.svg | 7 + assets/surface-icons/toggle-grading.svg | 8 + assets/surface-icons/toggle-layer-on-off.svg | 7 + assets/surface-icons/toggle-multi-view.svg | 7 + assets/surface-icons/toggle-overlay.svg | 7 + assets/surface-icons/toggle-select-image.svg | 9 + .../surface-icons/toggle-selection-points.svg | 10 + assets/surface-icons/toggle-tools.svg | 7 + assets/surface-icons/tone-curve.svg | 7 + assets/surface-icons/undo.svg | 6 + assets/surface-icons/uniform-light.svg | 8 + assets/surface-icons/vignetting.svg | 7 + assets/surface-icons/watermark-tool.svg | 7 + assets/surface-icons/wb-picker-tool.svg | 9 + assets/surface-icons/white-balance.svg | 6 + assets/surface-icons/white.svg | 3 + assets/surface-icons/zoom-100.svg | 6 + assets/surface-icons/zoom-200.svg | 6 + assets/surface-icons/zoom-400.svg | 6 + assets/surface-icons/zoom-actual-size.svg | 11 + assets/surface-icons/zoom-fit-view.svg | 6 + assets/surface-icons/zoom-in-tool.svg | 7 + assets/surface-icons/zoom-in.svg | 7 + assets/surface-icons/zoom-out-tool.svg | 7 + assets/surface-icons/zoom-out.svg | 7 + assets/surface-icons/zoom-to-fit.svg | 6 + assets/surface-icons/zoom.svg | 9 + crates/surface/Cargo.toml | 16 + crates/surface/src/binding.rs | 135 +++ crates/surface/src/catalog.rs | 225 ++++ crates/surface/src/context.rs | 156 +++ crates/surface/src/defaults.rs | 477 ++++++++ crates/surface/src/devices.rs | 174 +++ crates/surface/src/icon_table.rs | 354 ++++++ crates/surface/src/icons.rs | 356 ++++++ crates/surface/src/layout.rs | 216 ++++ crates/surface/src/lib.rs | 49 + crates/surface/src/loupedeck.rs | 605 ++++++++++ crates/surface/src/motion.rs | 148 +++ crates/surface/src/profile.rs | 210 ++++ crates/surface/src/protocol.rs | 259 ++++ crates/surface/src/runtime.rs | 1074 +++++++++++++++++ crates/surface/src/settings.rs | 484 ++++++++ crates/surface/src/tactilebridge.rs | 1051 ++++++++++++++++ crates/surface/src/targets.rs | 214 ++++ crates/surface/src/zip.rs | 144 +++ xtask/src/layers.rs | 1 + 374 files changed, 9143 insertions(+) create mode 100644 assets/surface-icons/LICENSE.txt create mode 100644 assets/surface-icons/add-color-readout.svg create mode 100644 assets/surface-icons/aperture-down.svg create mode 100644 assets/surface-icons/aperture-up.svg create mode 100644 assets/surface-icons/apply-adjustments.svg create mode 100644 assets/surface-icons/apply-normalization.svg create mode 100644 assets/surface-icons/auto-adjust.svg create mode 100644 assets/surface-icons/auto-focus-fine.svg create mode 100644 assets/surface-icons/auto-focus.svg create mode 100644 assets/surface-icons/auto-sync.svg create mode 100644 assets/surface-icons/black.svg create mode 100644 assets/surface-icons/blur-brush.svg create mode 100644 assets/surface-icons/brightness.svg create mode 100644 assets/surface-icons/brush-erase.svg create mode 100644 assets/surface-icons/brush-flow.svg create mode 100644 assets/surface-icons/brush-hardness.svg create mode 100644 assets/surface-icons/brush-new.svg create mode 100644 assets/surface-icons/brush-opacity.svg create mode 100644 assets/surface-icons/brush-size.svg create mode 100644 assets/surface-icons/burn.svg create mode 100644 assets/surface-icons/bw-blue.svg create mode 100644 assets/surface-icons/bw-cyan.svg create mode 100644 assets/surface-icons/bw-enable.svg create mode 100644 assets/surface-icons/bw-green.svg create mode 100644 assets/surface-icons/bw-highlights-hue.svg create mode 100644 assets/surface-icons/bw-highlights-sat.svg create mode 100644 assets/surface-icons/bw-magenta.svg create mode 100644 assets/surface-icons/bw-orange.svg create mode 100644 assets/surface-icons/bw-red.svg create mode 100644 assets/surface-icons/bw-shadows-hue.svg create mode 100644 assets/surface-icons/bw-shadows-sat.svg create mode 100644 assets/surface-icons/bw-yellow.svg create mode 100644 assets/surface-icons/capture.svg create mode 100644 assets/surface-icons/ce-blue-hue.svg create mode 100644 assets/surface-icons/ce-blue-light.svg create mode 100644 assets/surface-icons/ce-blue-sat.svg create mode 100644 assets/surface-icons/ce-cyan-hue.svg create mode 100644 assets/surface-icons/ce-cyan-light.svg create mode 100644 assets/surface-icons/ce-cyan-sat.svg create mode 100644 assets/surface-icons/ce-green-hue.svg create mode 100644 assets/surface-icons/ce-green-light.svg create mode 100644 assets/surface-icons/ce-green-sat.svg create mode 100644 assets/surface-icons/ce-magenta-hue.svg create mode 100644 assets/surface-icons/ce-magenta-light.svg create mode 100644 assets/surface-icons/ce-magenta-sat.svg create mode 100644 assets/surface-icons/ce-orange-hue.svg create mode 100644 assets/surface-icons/ce-orange-light.svg create mode 100644 assets/surface-icons/ce-orange-sat.svg create mode 100644 assets/surface-icons/ce-purple-hue.svg create mode 100644 assets/surface-icons/ce-purple-light.svg create mode 100644 assets/surface-icons/ce-purple-sat.svg create mode 100644 assets/surface-icons/ce-red-hue.svg create mode 100644 assets/surface-icons/ce-red-light.svg create mode 100644 assets/surface-icons/ce-red-sat.svg create mode 100644 assets/surface-icons/ce-yellow-hue.svg create mode 100644 assets/surface-icons/ce-yellow-light.svg create mode 100644 assets/surface-icons/ce-yellow-sat.svg create mode 100644 assets/surface-icons/clarity.svg create mode 100644 assets/surface-icons/clear-compare-variant.svg create mode 100644 assets/surface-icons/clear-mask.svg create mode 100644 assets/surface-icons/clear-rating.svg create mode 100644 assets/surface-icons/clone-brush.svg create mode 100644 assets/surface-icons/clone-variant.svg create mode 100644 assets/surface-icons/color-burn.svg create mode 100644 assets/surface-icons/color-dodge.svg create mode 100644 assets/surface-icons/color-picker-tool.svg create mode 100644 assets/surface-icons/color-tag-blue.svg create mode 100644 assets/surface-icons/color-tag-green.svg create mode 100644 assets/surface-icons/color-tag-none.svg create mode 100644 assets/surface-icons/color-tag-orange.svg create mode 100644 assets/surface-icons/color-tag-pink.svg create mode 100644 assets/surface-icons/color-tag-purple.svg create mode 100644 assets/surface-icons/color-tag-red.svg create mode 100644 assets/surface-icons/color-tag-yellow.svg create mode 100644 assets/surface-icons/composition-mode.svg create mode 100644 assets/surface-icons/contrast-brush.svg create mode 100644 assets/surface-icons/contrast.svg create mode 100644 assets/surface-icons/copy-adjustments.svg create mode 100644 assets/surface-icons/copy-and-apply-adj.svg create mode 100644 assets/surface-icons/crop-tool.svg create mode 100644 assets/surface-icons/darken.svg create mode 100644 assets/surface-icons/decrease-zoom.svg create mode 100644 assets/surface-icons/defringe.svg create mode 100644 assets/surface-icons/delete-color-readout.svg create mode 100644 assets/surface-icons/delete.svg create mode 100644 assets/surface-icons/demote-variant.svg create mode 100644 assets/surface-icons/desaturate-brush.svg create mode 100644 assets/surface-icons/deselect-all.svg create mode 100644 assets/surface-icons/deselect-primary.svg create mode 100644 assets/surface-icons/direct-color-editor.svg create mode 100644 assets/surface-icons/distortion.svg create mode 100644 assets/surface-icons/dodge.svg create mode 100644 assets/surface-icons/draw-clone-tool.svg create mode 100644 assets/surface-icons/draw-heal-tool.svg create mode 100644 assets/surface-icons/draw-mask-tool.svg create mode 100644 assets/surface-icons/edit-all-selected.svg create mode 100644 assets/surface-icons/erase-mask-tool.svg create mode 100644 assets/surface-icons/export-originals.svg create mode 100644 assets/surface-icons/export-variants.svg create mode 100644 assets/surface-icons/exposure-bias-down.svg create mode 100644 assets/surface-icons/exposure-bias-up.svg create mode 100644 assets/surface-icons/exposure-brush.svg create mode 100644 assets/surface-icons/exposure-meter.svg create mode 100644 assets/surface-icons/exposure.svg create mode 100644 assets/surface-icons/feather-mask.svg create mode 100644 assets/surface-icons/fill-mask.svg create mode 100644 assets/surface-icons/filter-1-star.svg create mode 100644 assets/surface-icons/filter-2-stars.svg create mode 100644 assets/surface-icons/filter-3-stars.svg create mode 100644 assets/surface-icons/filter-4-stars.svg create mode 100644 assets/surface-icons/filter-5-stars.svg create mode 100644 assets/surface-icons/filter-approved.svg create mode 100644 assets/surface-icons/filter-color-tag.svg create mode 100644 assets/surface-icons/filter-flag.svg create mode 100644 assets/surface-icons/filter-green.svg create mode 100644 assets/surface-icons/filter-no-flag.svg create mode 100644 assets/surface-icons/filter-purple.svg create mode 100644 assets/surface-icons/filter-rating-1-star.svg create mode 100644 assets/surface-icons/filter-rating-2-stars.svg create mode 100644 assets/surface-icons/filter-rating-3-stars.svg create mode 100644 assets/surface-icons/filter-rating-4-stars.svg create mode 100644 assets/surface-icons/filter-rating-5-stars.svg create mode 100644 assets/surface-icons/filter-rating-none.svg create mode 100644 assets/surface-icons/filter-red.svg create mode 100644 assets/surface-icons/filter-rejected.svg create mode 100644 assets/surface-icons/filter-tag-blue.svg create mode 100644 assets/surface-icons/filter-tag-green.svg create mode 100644 assets/surface-icons/filter-tag-none.svg create mode 100644 assets/surface-icons/filter-tag-orange.svg create mode 100644 assets/surface-icons/filter-tag-pink.svg create mode 100644 assets/surface-icons/filter-tag-purple.svg create mode 100644 assets/surface-icons/filter-tag-red.svg create mode 100644 assets/surface-icons/filter-tag-yellow.svg create mode 100644 assets/surface-icons/filter-yellow.svg create mode 100644 assets/surface-icons/first-image.svg create mode 100644 assets/surface-icons/focus-assist.svg create mode 100644 assets/surface-icons/focus-meter-tool.svg create mode 100644 assets/surface-icons/focus-point-tool.svg create mode 100644 assets/surface-icons/full-screen.svg create mode 100644 assets/surface-icons/grain-granularity.svg create mode 100644 assets/surface-icons/grain-impact.svg create mode 100644 assets/surface-icons/hard-light.svg create mode 100644 assets/surface-icons/heal-brush.svg create mode 100644 assets/surface-icons/highlight-brush.svg create mode 100644 assets/surface-icons/highlight-lightness.svg create mode 100644 assets/surface-icons/highlight-tone-x.svg create mode 100644 assets/surface-icons/highlight-tone-y.svg create mode 100644 assets/surface-icons/highlight.svg create mode 100644 assets/surface-icons/histogram-view.svg create mode 100644 assets/surface-icons/import-images.svg create mode 100644 assets/surface-icons/increase-zoom.svg create mode 100644 assets/surface-icons/invert-mask.svg create mode 100644 assets/surface-icons/invert-selection.svg create mode 100644 assets/surface-icons/iso-down.svg create mode 100644 assets/surface-icons/iso-up.svg create mode 100644 assets/surface-icons/kelvin.svg create mode 100644 assets/surface-icons/keystone-horizontal.svg create mode 100644 assets/surface-icons/keystone-tool.svg create mode 100644 assets/surface-icons/keystone-vertical.svg create mode 100644 assets/surface-icons/last-image.svg create mode 100644 assets/surface-icons/layer-opacity.svg create mode 100644 assets/surface-icons/light-falloff.svg create mode 100644 assets/surface-icons/lighten.svg create mode 100644 assets/surface-icons/linear-gradient-tool.svg create mode 100644 assets/surface-icons/live-view.svg create mode 100644 assets/surface-icons/loupe-tool.svg create mode 100644 assets/surface-icons/luma-range.svg create mode 100644 assets/surface-icons/mask-invert.svg create mode 100644 assets/surface-icons/mask-next.svg create mode 100644 assets/surface-icons/mask-previous.svg create mode 100644 assets/surface-icons/mask-visible.svg create mode 100644 assets/surface-icons/master-tone-x.svg create mode 100644 assets/surface-icons/master-tone-y.svg create mode 100644 assets/surface-icons/midtone-lightness.svg create mode 100644 assets/surface-icons/midtone-tone-x.svg create mode 100644 assets/surface-icons/midtone-tone-y.svg create mode 100644 assets/surface-icons/moire-amount.svg create mode 100644 assets/surface-icons/moire-pattern.svg create mode 100644 assets/surface-icons/move-to-trash.svg create mode 100644 assets/surface-icons/move-tool.svg create mode 100644 assets/surface-icons/multiply.svg create mode 100644 assets/surface-icons/new-clone-layer.svg create mode 100644 assets/surface-icons/new-empty-layer.svg create mode 100644 assets/surface-icons/new-filled-layer.svg create mode 100644 assets/surface-icons/new-heal-layer.svg create mode 100644 assets/surface-icons/new-variant.svg create mode 100644 assets/surface-icons/next-collection.svg create mode 100644 assets/surface-icons/next-group.svg create mode 100644 assets/surface-icons/next-image-import.svg create mode 100644 assets/surface-icons/next-image.svg create mode 100644 assets/surface-icons/next-set.svg create mode 100644 assets/surface-icons/nr-color.svg create mode 100644 assets/surface-icons/nr-detail.svg create mode 100644 assets/surface-icons/nr-luminance.svg create mode 100644 assets/surface-icons/nr-single-pixel.svg create mode 100644 assets/surface-icons/overlay-horizontal.svg create mode 100644 assets/surface-icons/overlay-opacity.svg create mode 100644 assets/surface-icons/overlay-scale.svg create mode 100644 assets/surface-icons/overlay-tool.svg create mode 100644 assets/surface-icons/overlay-vertical.svg create mode 100644 assets/surface-icons/overlay.svg create mode 100644 assets/surface-icons/pan-tool.svg create mode 100644 assets/surface-icons/pen-black.svg create mode 100644 assets/surface-icons/pen-blue.svg create mode 100644 assets/surface-icons/pen-green.svg create mode 100644 assets/surface-icons/pen-red.svg create mode 100644 assets/surface-icons/pen-size.svg create mode 100644 assets/surface-icons/pen-white.svg create mode 100644 assets/surface-icons/pen-yellow.svg create mode 100644 assets/surface-icons/pick-color-correction.svg create mode 100644 assets/surface-icons/pick-curve-point.svg create mode 100644 assets/surface-icons/pick-focus-point.svg create mode 100644 assets/surface-icons/pick-highlight-level.svg create mode 100644 assets/surface-icons/pick-luma-curve.svg create mode 100644 assets/surface-icons/pick-norm-target.svg create mode 100644 assets/surface-icons/pick-shadow-level.svg create mode 100644 assets/surface-icons/pick-skin-color.svg create mode 100644 assets/surface-icons/pick-variant.svg create mode 100644 assets/surface-icons/preset-apply-ai.svg create mode 100644 assets/surface-icons/preset-apply.svg create mode 100644 assets/surface-icons/previous-collection.svg create mode 100644 assets/surface-icons/previous-group.svg create mode 100644 assets/surface-icons/previous-image-import.svg create mode 100644 assets/surface-icons/previous-image.svg create mode 100644 assets/surface-icons/previous-set.svg create mode 100644 assets/surface-icons/print.svg create mode 100644 assets/surface-icons/process.svg create mode 100644 assets/surface-icons/promote-variant.svg create mode 100644 assets/surface-icons/radial-gradient-tool.svg create mode 100644 assets/surface-icons/rasterize-mask.svg create mode 100644 assets/surface-icons/rate-1-star.svg create mode 100644 assets/surface-icons/rate-2-star.svg create mode 100644 assets/surface-icons/rate-2-stars.svg create mode 100644 assets/surface-icons/rate-3-star.svg create mode 100644 assets/surface-icons/rate-3-stars.svg create mode 100644 assets/surface-icons/rate-4-star.svg create mode 100644 assets/surface-icons/rate-4-stars.svg create mode 100644 assets/surface-icons/rate-5-star.svg create mode 100644 assets/surface-icons/rate-5-stars.svg create mode 100644 assets/surface-icons/recipe-proofing.svg create mode 100644 assets/surface-icons/redo.svg create mode 100644 assets/surface-icons/refine-mask.svg create mode 100644 assets/surface-icons/regenerate-previews.svg create mode 100644 assets/surface-icons/remove-layer.svg create mode 100644 assets/surface-icons/rename.svg create mode 100644 assets/surface-icons/reset-adjustments.svg create mode 100644 assets/surface-icons/reset-develop.svg create mode 100644 assets/surface-icons/rotate-freehand-tool.svg create mode 100644 assets/surface-icons/rotate-left.svg create mode 100644 assets/surface-icons/rotate-photo-left.svg create mode 100644 assets/surface-icons/rotate-photo-right.svg create mode 100644 assets/surface-icons/rotate-right.svg create mode 100644 assets/surface-icons/rotation-tool.svg create mode 100644 assets/surface-icons/saturation-brush.svg create mode 100644 assets/surface-icons/saturation.svg create mode 100644 assets/surface-icons/select-1-star.svg create mode 100644 assets/surface-icons/select-2-stars.svg create mode 100644 assets/surface-icons/select-3-stars.svg create mode 100644 assets/surface-icons/select-4-stars.svg create mode 100644 assets/surface-icons/select-5-stars.svg create mode 100644 assets/surface-icons/select-all-photos.svg create mode 100644 assets/surface-icons/select-all.svg create mode 100644 assets/surface-icons/select-background.svg create mode 100644 assets/surface-icons/select-brush.svg create mode 100644 assets/surface-icons/select-by-color.svg create mode 100644 assets/surface-icons/select-by-shape.svg create mode 100644 assets/surface-icons/select-by-tone.svg create mode 100644 assets/surface-icons/select-eraser.svg create mode 100644 assets/surface-icons/select-freehand.svg create mode 100644 assets/surface-icons/select-layer-down.svg create mode 100644 assets/surface-icons/select-layer-up.svg create mode 100644 assets/surface-icons/select-magic-wand.svg create mode 100644 assets/surface-icons/select-no-photos.svg create mode 100644 assets/surface-icons/select-pen.svg create mode 100644 assets/surface-icons/select-primary-only.svg create mode 100644 assets/surface-icons/select-same-color-tag.svg create mode 100644 assets/surface-icons/select-same-sequence-id.svg create mode 100644 assets/surface-icons/select-same-variant-pos.svg create mode 100644 assets/surface-icons/select-smooth.svg create mode 100644 assets/surface-icons/select-subject.svg create mode 100644 assets/surface-icons/select-tag-blue.svg create mode 100644 assets/surface-icons/select-tag-green.svg create mode 100644 assets/surface-icons/select-tag-none.svg create mode 100644 assets/surface-icons/select-tag-orange.svg create mode 100644 assets/surface-icons/select-tag-pink.svg create mode 100644 assets/surface-icons/select-tag-purple.svg create mode 100644 assets/surface-icons/select-tag-red.svg create mode 100644 assets/surface-icons/select-tag-yellow.svg create mode 100644 assets/surface-icons/select-tool.svg create mode 100644 assets/surface-icons/select-unrated.svg create mode 100644 assets/surface-icons/set-compare-variant.svg create mode 100644 assets/surface-icons/shadow-brush.svg create mode 100644 assets/surface-icons/shadow-lightness.svg create mode 100644 assets/surface-icons/shadow-tone-x.svg create mode 100644 assets/surface-icons/shadow-tone-y.svg create mode 100644 assets/surface-icons/shadow.svg create mode 100644 assets/surface-icons/sharpen-brush.svg create mode 100644 assets/surface-icons/sharpening-amount.svg create mode 100644 assets/surface-icons/sharpening-halo.svg create mode 100644 assets/surface-icons/sharpening-radius.svg create mode 100644 assets/surface-icons/sharpening-threshold.svg create mode 100644 assets/surface-icons/sharpness-falloff.svg create mode 100644 assets/surface-icons/show-filmstrip.svg create mode 100644 assets/surface-icons/show-grid.svg create mode 100644 assets/surface-icons/show-guides.svg create mode 100644 assets/surface-icons/show-hide-browser.svg create mode 100644 assets/surface-icons/show-hide-viewer.svg create mode 100644 assets/surface-icons/show-histogram.svg create mode 100644 assets/surface-icons/show-in-file-system.svg create mode 100644 assets/surface-icons/show-in-library.svg create mode 100644 assets/surface-icons/show-metadata.svg create mode 100644 assets/surface-icons/shutter-speed-down.svg create mode 100644 assets/surface-icons/shutter-speed-up.svg create mode 100644 assets/surface-icons/slide-show.svg create mode 100644 assets/surface-icons/snap-to-90.svg create mode 100644 assets/surface-icons/soft-light.svg create mode 100644 assets/surface-icons/spot-radius.svg create mode 100644 assets/surface-icons/spot-removal-tool.svg create mode 100644 assets/surface-icons/straighten-tool.svg create mode 100644 assets/surface-icons/structure.svg create mode 100644 assets/surface-icons/switch-crop-orientation.svg create mode 100644 assets/surface-icons/tint.svg create mode 100644 assets/surface-icons/toggle-before-after.svg create mode 100644 assets/surface-icons/toggle-exposure-warn.svg create mode 100644 assets/surface-icons/toggle-focus-mask.svg create mode 100644 assets/surface-icons/toggle-grading.svg create mode 100644 assets/surface-icons/toggle-layer-on-off.svg create mode 100644 assets/surface-icons/toggle-multi-view.svg create mode 100644 assets/surface-icons/toggle-overlay.svg create mode 100644 assets/surface-icons/toggle-select-image.svg create mode 100644 assets/surface-icons/toggle-selection-points.svg create mode 100644 assets/surface-icons/toggle-tools.svg create mode 100644 assets/surface-icons/tone-curve.svg create mode 100644 assets/surface-icons/undo.svg create mode 100644 assets/surface-icons/uniform-light.svg create mode 100644 assets/surface-icons/vignetting.svg create mode 100644 assets/surface-icons/watermark-tool.svg create mode 100644 assets/surface-icons/wb-picker-tool.svg create mode 100644 assets/surface-icons/white-balance.svg create mode 100644 assets/surface-icons/white.svg create mode 100644 assets/surface-icons/zoom-100.svg create mode 100644 assets/surface-icons/zoom-200.svg create mode 100644 assets/surface-icons/zoom-400.svg create mode 100644 assets/surface-icons/zoom-actual-size.svg create mode 100644 assets/surface-icons/zoom-fit-view.svg create mode 100644 assets/surface-icons/zoom-in-tool.svg create mode 100644 assets/surface-icons/zoom-in.svg create mode 100644 assets/surface-icons/zoom-out-tool.svg create mode 100644 assets/surface-icons/zoom-out.svg create mode 100644 assets/surface-icons/zoom-to-fit.svg create mode 100644 assets/surface-icons/zoom.svg create mode 100644 crates/surface/Cargo.toml create mode 100644 crates/surface/src/binding.rs create mode 100644 crates/surface/src/catalog.rs create mode 100644 crates/surface/src/context.rs create mode 100644 crates/surface/src/defaults.rs create mode 100644 crates/surface/src/devices.rs create mode 100644 crates/surface/src/icon_table.rs create mode 100644 crates/surface/src/icons.rs create mode 100644 crates/surface/src/layout.rs create mode 100644 crates/surface/src/lib.rs create mode 100644 crates/surface/src/loupedeck.rs create mode 100644 crates/surface/src/motion.rs create mode 100644 crates/surface/src/profile.rs create mode 100644 crates/surface/src/protocol.rs create mode 100644 crates/surface/src/runtime.rs create mode 100644 crates/surface/src/settings.rs create mode 100644 crates/surface/src/tactilebridge.rs create mode 100644 crates/surface/src/targets.rs create mode 100644 crates/surface/src/zip.rs diff --git a/Cargo.toml b/Cargo.toml index c22395b8a4f..b6a95978cbc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ lightcraft-merge = { path = "crates/merge" } lightcraft-engine = { path = "crates/engine" } lightcraft-ui-egui = { path = "crates/ui-egui" } lightcraft-mcp = { path = "crates/mcp" } +lightcraft-surface = { path = "crates/surface" } lightcraft-fetch = { path = "crates/fetch" } lightcraft-heif = { path = "crates/heif" } lightcraft-segment = { path = "crates/segment" } @@ -92,6 +93,8 @@ pollster = "1" # ui egui = "0.36" +# control-surface icons in Settings > Controls and the readout (pure Rust; no text, no raster images) +resvg = { version = "0.45", default-features = false } egui_extras = { version = "0.36", default-features = false } eframe = { version = "0.36", default-features = false } egui_kittest = "0.36" diff --git a/NOTICE b/NOTICE index 8b16eeba0f5..af88fbb77ad 100644 --- a/NOTICE +++ b/NOTICE @@ -22,6 +22,13 @@ Foundation project licensed under the Apache License 2.0, and from the CIE 1931 functions it ships (CIE, CC-BY-4.0). The matrices were fitted by the LightCraft contributors (2026) with tools/spectral_camera_table.py. See assets/ATTRIBUTION.md. +crates/surface (lightcraft-surface), the control-surface support in crates/ui-egui and +apps/lightcraft, and the icons in assets/surface-icons port TactileBridge, Portions Copyright (c) +2026 RAD Films - Roman Alurkoff, contributed under the MIT License: its control-surface engine +(dial acceleration and tuning, coalescing, echo suppression, tool-following layouts, Auto Sync), +its settings design and defaults, its curated layouts and profiles, and its hand-drawn icon pack +(assets/surface-icons/LICENSE.txt). Each ported file says so. No Capture One material is included. + crates/inpaint (lightcraft-inpaint) ports the inpainting (PatchMatch completion) and Poisson membrane fill code of PhotoCraft (https://github.com/storytold/photocraft, crates/algo/src/inpaint.rs and poisson.rs), Copyright the PhotoCraft contributors, licensed under the MIT License or the Apache diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index 30eea5654c8..adfe4ce2414 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -20,6 +20,8 @@ covers a whole directory), or if a licence file referenced in the Licence column | `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none | | `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix | | `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none | +| `assets/surface-icons/*.svg` (335 icons from the pack, plus the 13 below: dial values and key actions for control surfaces) | TactileBridge icon pack | RAD Films - Roman Alurkoff | original hand-drawn work from TactileBridge (the author's own project, contributed to LightCraft) | MIT (`assets/surface-icons/LICENSE.txt`) | 2026-10-14 | renamed from `CaptureOneAdj___.svg` / `CaptureOneCmd___.svg` to kebab-case `.svg`; the authoring tool's generator comment removed from two files; `Clarity.min.svg` (a duplicate) left out; the three Keystone icons added 2026-10-16 as `keystone-tool` / `keystone-vertical` / `keystone-horizontal` (the author confirmed every icon of the pack is their own drawing; a likeness to other apps comes from the generic subject); 2026-10-15: 81 icons that spilled over the edge, sat off-centre or were much smaller than the rest wrapped in one `data-normalized` transform (scaled and placed like the others; drawings unchanged) | +| `assets/surface-icons/{mask-invert,brush-erase,brush-new,mask-previous,mask-next,mask-visible,zoom-fit-view,zoom-actual-size,select-all-photos,select-no-photos,rotate-photo-left,rotate-photo-right,reset-develop,preset-apply,preset-apply-ai}.svg` (15 icons) | Surface icons for functions that shared one generic pack icon (the two preset icons, 2026-10-22: a key that applies a preset, with an "AI" mark for AI-mask presets) | drawn by an AI agent (Claude) for LightCraft in the TactileBridge pack's style | original work | MIT, part of the pack (`assets/surface-icons/LICENSE.txt`) | 2026-10-16 | none; new files beside the pack's originals, which are unchanged | | `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `crates/ui-egui/src/panels/person.rs` | Up arrow on the People page bulk-confirm control, drawn in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-10-13 | n/a | diff --git a/assets/surface-icons/LICENSE.txt b/assets/surface-icons/LICENSE.txt new file mode 100644 index 00000000000..c71be31e931 --- /dev/null +++ b/assets/surface-icons/LICENSE.txt @@ -0,0 +1,24 @@ +MIT License + +Copyright (c) 2026 RAD Films - Roman Alurkoff + +The icons in this folder are original hand-drawn work from TactileBridge, contributed to +LightCraft by their author under the MIT licence. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/assets/surface-icons/add-color-readout.svg b/assets/surface-icons/add-color-readout.svg new file mode 100644 index 00000000000..1b11926509b --- /dev/null +++ b/assets/surface-icons/add-color-readout.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/aperture-down.svg b/assets/surface-icons/aperture-down.svg new file mode 100644 index 00000000000..6827b0c5f4a --- /dev/null +++ b/assets/surface-icons/aperture-down.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/aperture-up.svg b/assets/surface-icons/aperture-up.svg new file mode 100644 index 00000000000..aff107515a7 --- /dev/null +++ b/assets/surface-icons/aperture-up.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/apply-adjustments.svg b/assets/surface-icons/apply-adjustments.svg new file mode 100644 index 00000000000..8fbf245bccd --- /dev/null +++ b/assets/surface-icons/apply-adjustments.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/apply-normalization.svg b/assets/surface-icons/apply-normalization.svg new file mode 100644 index 00000000000..f3a66bc14cd --- /dev/null +++ b/assets/surface-icons/apply-normalization.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/auto-adjust.svg b/assets/surface-icons/auto-adjust.svg new file mode 100644 index 00000000000..f55b8c35d3f --- /dev/null +++ b/assets/surface-icons/auto-adjust.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/auto-focus-fine.svg b/assets/surface-icons/auto-focus-fine.svg new file mode 100644 index 00000000000..94ecdd47615 --- /dev/null +++ b/assets/surface-icons/auto-focus-fine.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/auto-focus.svg b/assets/surface-icons/auto-focus.svg new file mode 100644 index 00000000000..0ae99fa6db3 --- /dev/null +++ b/assets/surface-icons/auto-focus.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/auto-sync.svg b/assets/surface-icons/auto-sync.svg new file mode 100644 index 00000000000..9573e0dfdfe --- /dev/null +++ b/assets/surface-icons/auto-sync.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/black.svg b/assets/surface-icons/black.svg new file mode 100644 index 00000000000..9089816b3c0 --- /dev/null +++ b/assets/surface-icons/black.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/assets/surface-icons/blur-brush.svg b/assets/surface-icons/blur-brush.svg new file mode 100644 index 00000000000..21c96008367 --- /dev/null +++ b/assets/surface-icons/blur-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/brightness.svg b/assets/surface-icons/brightness.svg new file mode 100644 index 00000000000..a31965dadd0 --- /dev/null +++ b/assets/surface-icons/brightness.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/brush-erase.svg b/assets/surface-icons/brush-erase.svg new file mode 100644 index 00000000000..d75fa0325b3 --- /dev/null +++ b/assets/surface-icons/brush-erase.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/surface-icons/brush-flow.svg b/assets/surface-icons/brush-flow.svg new file mode 100644 index 00000000000..ef75eff68d2 --- /dev/null +++ b/assets/surface-icons/brush-flow.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/brush-hardness.svg b/assets/surface-icons/brush-hardness.svg new file mode 100644 index 00000000000..d9a88d245ac --- /dev/null +++ b/assets/surface-icons/brush-hardness.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/brush-new.svg b/assets/surface-icons/brush-new.svg new file mode 100644 index 00000000000..8fcce6560fe --- /dev/null +++ b/assets/surface-icons/brush-new.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/surface-icons/brush-opacity.svg b/assets/surface-icons/brush-opacity.svg new file mode 100644 index 00000000000..7bf630e0af7 --- /dev/null +++ b/assets/surface-icons/brush-opacity.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/brush-size.svg b/assets/surface-icons/brush-size.svg new file mode 100644 index 00000000000..60bdb180b03 --- /dev/null +++ b/assets/surface-icons/brush-size.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/burn.svg b/assets/surface-icons/burn.svg new file mode 100644 index 00000000000..161768f8f70 --- /dev/null +++ b/assets/surface-icons/burn.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-blue.svg b/assets/surface-icons/bw-blue.svg new file mode 100644 index 00000000000..83094a94c2e --- /dev/null +++ b/assets/surface-icons/bw-blue.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-cyan.svg b/assets/surface-icons/bw-cyan.svg new file mode 100644 index 00000000000..6b25989a71f --- /dev/null +++ b/assets/surface-icons/bw-cyan.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-enable.svg b/assets/surface-icons/bw-enable.svg new file mode 100644 index 00000000000..d1aa6246d34 --- /dev/null +++ b/assets/surface-icons/bw-enable.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-green.svg b/assets/surface-icons/bw-green.svg new file mode 100644 index 00000000000..64ebcbbab37 --- /dev/null +++ b/assets/surface-icons/bw-green.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-highlights-hue.svg b/assets/surface-icons/bw-highlights-hue.svg new file mode 100644 index 00000000000..606336c86aa --- /dev/null +++ b/assets/surface-icons/bw-highlights-hue.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-highlights-sat.svg b/assets/surface-icons/bw-highlights-sat.svg new file mode 100644 index 00000000000..fcaf7b72e7b --- /dev/null +++ b/assets/surface-icons/bw-highlights-sat.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-magenta.svg b/assets/surface-icons/bw-magenta.svg new file mode 100644 index 00000000000..707817301b0 --- /dev/null +++ b/assets/surface-icons/bw-magenta.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-orange.svg b/assets/surface-icons/bw-orange.svg new file mode 100644 index 00000000000..d9e05a6b7f5 --- /dev/null +++ b/assets/surface-icons/bw-orange.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-red.svg b/assets/surface-icons/bw-red.svg new file mode 100644 index 00000000000..02a9f559ca4 --- /dev/null +++ b/assets/surface-icons/bw-red.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-shadows-hue.svg b/assets/surface-icons/bw-shadows-hue.svg new file mode 100644 index 00000000000..a6045cdef73 --- /dev/null +++ b/assets/surface-icons/bw-shadows-hue.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-shadows-sat.svg b/assets/surface-icons/bw-shadows-sat.svg new file mode 100644 index 00000000000..78b35346fc9 --- /dev/null +++ b/assets/surface-icons/bw-shadows-sat.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/bw-yellow.svg b/assets/surface-icons/bw-yellow.svg new file mode 100644 index 00000000000..f5cad763aad --- /dev/null +++ b/assets/surface-icons/bw-yellow.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/capture.svg b/assets/surface-icons/capture.svg new file mode 100644 index 00000000000..0cc0ed0cee6 --- /dev/null +++ b/assets/surface-icons/capture.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/ce-blue-hue.svg b/assets/surface-icons/ce-blue-hue.svg new file mode 100644 index 00000000000..47cb5d7b181 --- /dev/null +++ b/assets/surface-icons/ce-blue-hue.svg @@ -0,0 +1,7 @@ + + + + + H + + \ No newline at end of file diff --git a/assets/surface-icons/ce-blue-light.svg b/assets/surface-icons/ce-blue-light.svg new file mode 100644 index 00000000000..a6b1df8bcd9 --- /dev/null +++ b/assets/surface-icons/ce-blue-light.svg @@ -0,0 +1,7 @@ + + + + + L + + \ No newline at end of file diff --git a/assets/surface-icons/ce-blue-sat.svg b/assets/surface-icons/ce-blue-sat.svg new file mode 100644 index 00000000000..ca20f208134 --- /dev/null +++ b/assets/surface-icons/ce-blue-sat.svg @@ -0,0 +1,7 @@ + + + + + S + + \ No newline at end of file diff --git a/assets/surface-icons/ce-cyan-hue.svg b/assets/surface-icons/ce-cyan-hue.svg new file mode 100644 index 00000000000..ddb583d0946 --- /dev/null +++ b/assets/surface-icons/ce-cyan-hue.svg @@ -0,0 +1,7 @@ + + + + + H + + \ No newline at end of file diff --git a/assets/surface-icons/ce-cyan-light.svg b/assets/surface-icons/ce-cyan-light.svg new file mode 100644 index 00000000000..375f64a5d1f --- /dev/null +++ b/assets/surface-icons/ce-cyan-light.svg @@ -0,0 +1,7 @@ + + + + + L + + \ No newline at end of file diff --git a/assets/surface-icons/ce-cyan-sat.svg b/assets/surface-icons/ce-cyan-sat.svg new file mode 100644 index 00000000000..cb89da9cee9 --- /dev/null +++ b/assets/surface-icons/ce-cyan-sat.svg @@ -0,0 +1,7 @@ + + + + + S + + \ No newline at end of file diff --git a/assets/surface-icons/ce-green-hue.svg b/assets/surface-icons/ce-green-hue.svg new file mode 100644 index 00000000000..506374f09c1 --- /dev/null +++ b/assets/surface-icons/ce-green-hue.svg @@ -0,0 +1,7 @@ + + + + + H + + \ No newline at end of file diff --git a/assets/surface-icons/ce-green-light.svg b/assets/surface-icons/ce-green-light.svg new file mode 100644 index 00000000000..710f37b969d --- /dev/null +++ b/assets/surface-icons/ce-green-light.svg @@ -0,0 +1,7 @@ + + + + + L + + \ No newline at end of file diff --git a/assets/surface-icons/ce-green-sat.svg b/assets/surface-icons/ce-green-sat.svg new file mode 100644 index 00000000000..0a61e1212b4 --- /dev/null +++ b/assets/surface-icons/ce-green-sat.svg @@ -0,0 +1,7 @@ + + + + + S + + \ No newline at end of file diff --git a/assets/surface-icons/ce-magenta-hue.svg b/assets/surface-icons/ce-magenta-hue.svg new file mode 100644 index 00000000000..c5dca28a430 --- /dev/null +++ b/assets/surface-icons/ce-magenta-hue.svg @@ -0,0 +1,7 @@ + + + + + H + + \ No newline at end of file diff --git a/assets/surface-icons/ce-magenta-light.svg b/assets/surface-icons/ce-magenta-light.svg new file mode 100644 index 00000000000..a4a54937834 --- /dev/null +++ b/assets/surface-icons/ce-magenta-light.svg @@ -0,0 +1,7 @@ + + + + + L + + \ No newline at end of file diff --git a/assets/surface-icons/ce-magenta-sat.svg b/assets/surface-icons/ce-magenta-sat.svg new file mode 100644 index 00000000000..620c37cbdbf --- /dev/null +++ b/assets/surface-icons/ce-magenta-sat.svg @@ -0,0 +1,7 @@ + + + + + S + + \ No newline at end of file diff --git a/assets/surface-icons/ce-orange-hue.svg b/assets/surface-icons/ce-orange-hue.svg new file mode 100644 index 00000000000..e42837c7a76 --- /dev/null +++ b/assets/surface-icons/ce-orange-hue.svg @@ -0,0 +1,7 @@ + + + + + H + + \ No newline at end of file diff --git a/assets/surface-icons/ce-orange-light.svg b/assets/surface-icons/ce-orange-light.svg new file mode 100644 index 00000000000..914352e77f8 --- /dev/null +++ b/assets/surface-icons/ce-orange-light.svg @@ -0,0 +1,7 @@ + + + + + L + + \ No newline at end of file diff --git a/assets/surface-icons/ce-orange-sat.svg b/assets/surface-icons/ce-orange-sat.svg new file mode 100644 index 00000000000..a509e799736 --- /dev/null +++ b/assets/surface-icons/ce-orange-sat.svg @@ -0,0 +1,7 @@ + + + + + S + + \ No newline at end of file diff --git a/assets/surface-icons/ce-purple-hue.svg b/assets/surface-icons/ce-purple-hue.svg new file mode 100644 index 00000000000..9da57399452 --- /dev/null +++ b/assets/surface-icons/ce-purple-hue.svg @@ -0,0 +1,7 @@ + + + + + H + + \ No newline at end of file diff --git a/assets/surface-icons/ce-purple-light.svg b/assets/surface-icons/ce-purple-light.svg new file mode 100644 index 00000000000..b62cd6d5315 --- /dev/null +++ b/assets/surface-icons/ce-purple-light.svg @@ -0,0 +1,7 @@ + + + + + L + + \ No newline at end of file diff --git a/assets/surface-icons/ce-purple-sat.svg b/assets/surface-icons/ce-purple-sat.svg new file mode 100644 index 00000000000..7ed55ccf15e --- /dev/null +++ b/assets/surface-icons/ce-purple-sat.svg @@ -0,0 +1,7 @@ + + + + + S + + \ No newline at end of file diff --git a/assets/surface-icons/ce-red-hue.svg b/assets/surface-icons/ce-red-hue.svg new file mode 100644 index 00000000000..250da142836 --- /dev/null +++ b/assets/surface-icons/ce-red-hue.svg @@ -0,0 +1,7 @@ + + + + + H + + \ No newline at end of file diff --git a/assets/surface-icons/ce-red-light.svg b/assets/surface-icons/ce-red-light.svg new file mode 100644 index 00000000000..f5111449167 --- /dev/null +++ b/assets/surface-icons/ce-red-light.svg @@ -0,0 +1,7 @@ + + + + + L + + \ No newline at end of file diff --git a/assets/surface-icons/ce-red-sat.svg b/assets/surface-icons/ce-red-sat.svg new file mode 100644 index 00000000000..8fc7529508f --- /dev/null +++ b/assets/surface-icons/ce-red-sat.svg @@ -0,0 +1,7 @@ + + + + + S + + \ No newline at end of file diff --git a/assets/surface-icons/ce-yellow-hue.svg b/assets/surface-icons/ce-yellow-hue.svg new file mode 100644 index 00000000000..716cdf8b312 --- /dev/null +++ b/assets/surface-icons/ce-yellow-hue.svg @@ -0,0 +1,7 @@ + + + + + H + + \ No newline at end of file diff --git a/assets/surface-icons/ce-yellow-light.svg b/assets/surface-icons/ce-yellow-light.svg new file mode 100644 index 00000000000..5e22a7e8323 --- /dev/null +++ b/assets/surface-icons/ce-yellow-light.svg @@ -0,0 +1,7 @@ + + + + + L + + \ No newline at end of file diff --git a/assets/surface-icons/ce-yellow-sat.svg b/assets/surface-icons/ce-yellow-sat.svg new file mode 100644 index 00000000000..ee0a63353d7 --- /dev/null +++ b/assets/surface-icons/ce-yellow-sat.svg @@ -0,0 +1,7 @@ + + + + + S + + \ No newline at end of file diff --git a/assets/surface-icons/clarity.svg b/assets/surface-icons/clarity.svg new file mode 100644 index 00000000000..31a5fc818d7 --- /dev/null +++ b/assets/surface-icons/clarity.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/clear-compare-variant.svg b/assets/surface-icons/clear-compare-variant.svg new file mode 100644 index 00000000000..b6f69c7b592 --- /dev/null +++ b/assets/surface-icons/clear-compare-variant.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/clear-mask.svg b/assets/surface-icons/clear-mask.svg new file mode 100644 index 00000000000..731e6267389 --- /dev/null +++ b/assets/surface-icons/clear-mask.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/clear-rating.svg b/assets/surface-icons/clear-rating.svg new file mode 100644 index 00000000000..b6f69c7b592 --- /dev/null +++ b/assets/surface-icons/clear-rating.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/clone-brush.svg b/assets/surface-icons/clone-brush.svg new file mode 100644 index 00000000000..21c96008367 --- /dev/null +++ b/assets/surface-icons/clone-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/clone-variant.svg b/assets/surface-icons/clone-variant.svg new file mode 100644 index 00000000000..cb0f7ed5389 --- /dev/null +++ b/assets/surface-icons/clone-variant.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-burn.svg b/assets/surface-icons/color-burn.svg new file mode 100644 index 00000000000..32762db620a --- /dev/null +++ b/assets/surface-icons/color-burn.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-dodge.svg b/assets/surface-icons/color-dodge.svg new file mode 100644 index 00000000000..1081a95df3f --- /dev/null +++ b/assets/surface-icons/color-dodge.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-picker-tool.svg b/assets/surface-icons/color-picker-tool.svg new file mode 100644 index 00000000000..61ee5a95293 --- /dev/null +++ b/assets/surface-icons/color-picker-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-tag-blue.svg b/assets/surface-icons/color-tag-blue.svg new file mode 100644 index 00000000000..485939fb0cd --- /dev/null +++ b/assets/surface-icons/color-tag-blue.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-tag-green.svg b/assets/surface-icons/color-tag-green.svg new file mode 100644 index 00000000000..2d52b029846 --- /dev/null +++ b/assets/surface-icons/color-tag-green.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-tag-none.svg b/assets/surface-icons/color-tag-none.svg new file mode 100644 index 00000000000..8d193b3f4e4 --- /dev/null +++ b/assets/surface-icons/color-tag-none.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-tag-orange.svg b/assets/surface-icons/color-tag-orange.svg new file mode 100644 index 00000000000..1d6c855dacc --- /dev/null +++ b/assets/surface-icons/color-tag-orange.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-tag-pink.svg b/assets/surface-icons/color-tag-pink.svg new file mode 100644 index 00000000000..819dd84d1a2 --- /dev/null +++ b/assets/surface-icons/color-tag-pink.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-tag-purple.svg b/assets/surface-icons/color-tag-purple.svg new file mode 100644 index 00000000000..74d1c89b2e0 --- /dev/null +++ b/assets/surface-icons/color-tag-purple.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-tag-red.svg b/assets/surface-icons/color-tag-red.svg new file mode 100644 index 00000000000..864cfb75697 --- /dev/null +++ b/assets/surface-icons/color-tag-red.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/color-tag-yellow.svg b/assets/surface-icons/color-tag-yellow.svg new file mode 100644 index 00000000000..f044f5ca842 --- /dev/null +++ b/assets/surface-icons/color-tag-yellow.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/composition-mode.svg b/assets/surface-icons/composition-mode.svg new file mode 100644 index 00000000000..bde725bc774 --- /dev/null +++ b/assets/surface-icons/composition-mode.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/contrast-brush.svg b/assets/surface-icons/contrast-brush.svg new file mode 100644 index 00000000000..ae28829a8fa --- /dev/null +++ b/assets/surface-icons/contrast-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/contrast.svg b/assets/surface-icons/contrast.svg new file mode 100644 index 00000000000..e8b90b38a50 --- /dev/null +++ b/assets/surface-icons/contrast.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/copy-adjustments.svg b/assets/surface-icons/copy-adjustments.svg new file mode 100644 index 00000000000..2e4b7d9ea56 --- /dev/null +++ b/assets/surface-icons/copy-adjustments.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/copy-and-apply-adj.svg b/assets/surface-icons/copy-and-apply-adj.svg new file mode 100644 index 00000000000..c4acc3191be --- /dev/null +++ b/assets/surface-icons/copy-and-apply-adj.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/crop-tool.svg b/assets/surface-icons/crop-tool.svg new file mode 100644 index 00000000000..0047294156b --- /dev/null +++ b/assets/surface-icons/crop-tool.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/darken.svg b/assets/surface-icons/darken.svg new file mode 100644 index 00000000000..6dd550998e8 --- /dev/null +++ b/assets/surface-icons/darken.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/decrease-zoom.svg b/assets/surface-icons/decrease-zoom.svg new file mode 100644 index 00000000000..171389cfd50 --- /dev/null +++ b/assets/surface-icons/decrease-zoom.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/defringe.svg b/assets/surface-icons/defringe.svg new file mode 100644 index 00000000000..a4d6ebf7b5e --- /dev/null +++ b/assets/surface-icons/defringe.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/delete-color-readout.svg b/assets/surface-icons/delete-color-readout.svg new file mode 100644 index 00000000000..bd32aeee0be --- /dev/null +++ b/assets/surface-icons/delete-color-readout.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/delete.svg b/assets/surface-icons/delete.svg new file mode 100644 index 00000000000..524b3456908 --- /dev/null +++ b/assets/surface-icons/delete.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/demote-variant.svg b/assets/surface-icons/demote-variant.svg new file mode 100644 index 00000000000..1780c5ac56a --- /dev/null +++ b/assets/surface-icons/demote-variant.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/desaturate-brush.svg b/assets/surface-icons/desaturate-brush.svg new file mode 100644 index 00000000000..5161cc0c7e1 --- /dev/null +++ b/assets/surface-icons/desaturate-brush.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/deselect-all.svg b/assets/surface-icons/deselect-all.svg new file mode 100644 index 00000000000..531f2034e23 --- /dev/null +++ b/assets/surface-icons/deselect-all.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/deselect-primary.svg b/assets/surface-icons/deselect-primary.svg new file mode 100644 index 00000000000..44bdcff669f --- /dev/null +++ b/assets/surface-icons/deselect-primary.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/direct-color-editor.svg b/assets/surface-icons/direct-color-editor.svg new file mode 100644 index 00000000000..b6a2e8b5d08 --- /dev/null +++ b/assets/surface-icons/direct-color-editor.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/distortion.svg b/assets/surface-icons/distortion.svg new file mode 100644 index 00000000000..543ef3720ff --- /dev/null +++ b/assets/surface-icons/distortion.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/dodge.svg b/assets/surface-icons/dodge.svg new file mode 100644 index 00000000000..b6f39fb68d7 --- /dev/null +++ b/assets/surface-icons/dodge.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/draw-clone-tool.svg b/assets/surface-icons/draw-clone-tool.svg new file mode 100644 index 00000000000..1ab6cc1fe98 --- /dev/null +++ b/assets/surface-icons/draw-clone-tool.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/draw-heal-tool.svg b/assets/surface-icons/draw-heal-tool.svg new file mode 100644 index 00000000000..1ab6cc1fe98 --- /dev/null +++ b/assets/surface-icons/draw-heal-tool.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/draw-mask-tool.svg b/assets/surface-icons/draw-mask-tool.svg new file mode 100644 index 00000000000..d3e3224cd5b --- /dev/null +++ b/assets/surface-icons/draw-mask-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/edit-all-selected.svg b/assets/surface-icons/edit-all-selected.svg new file mode 100644 index 00000000000..b427a45cb39 --- /dev/null +++ b/assets/surface-icons/edit-all-selected.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/erase-mask-tool.svg b/assets/surface-icons/erase-mask-tool.svg new file mode 100644 index 00000000000..d3e3224cd5b --- /dev/null +++ b/assets/surface-icons/erase-mask-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/export-originals.svg b/assets/surface-icons/export-originals.svg new file mode 100644 index 00000000000..a6fab52fffc --- /dev/null +++ b/assets/surface-icons/export-originals.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/export-variants.svg b/assets/surface-icons/export-variants.svg new file mode 100644 index 00000000000..a6fab52fffc --- /dev/null +++ b/assets/surface-icons/export-variants.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/exposure-bias-down.svg b/assets/surface-icons/exposure-bias-down.svg new file mode 100644 index 00000000000..3f28f26de9c --- /dev/null +++ b/assets/surface-icons/exposure-bias-down.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/exposure-bias-up.svg b/assets/surface-icons/exposure-bias-up.svg new file mode 100644 index 00000000000..3f28f26de9c --- /dev/null +++ b/assets/surface-icons/exposure-bias-up.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/exposure-brush.svg b/assets/surface-icons/exposure-brush.svg new file mode 100644 index 00000000000..ae28829a8fa --- /dev/null +++ b/assets/surface-icons/exposure-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/exposure-meter.svg b/assets/surface-icons/exposure-meter.svg new file mode 100644 index 00000000000..3f28f26de9c --- /dev/null +++ b/assets/surface-icons/exposure-meter.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/exposure.svg b/assets/surface-icons/exposure.svg new file mode 100644 index 00000000000..f94678b7524 --- /dev/null +++ b/assets/surface-icons/exposure.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/feather-mask.svg b/assets/surface-icons/feather-mask.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/feather-mask.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/fill-mask.svg b/assets/surface-icons/fill-mask.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/fill-mask.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-1-star.svg b/assets/surface-icons/filter-1-star.svg new file mode 100644 index 00000000000..ea0f1bcd245 --- /dev/null +++ b/assets/surface-icons/filter-1-star.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-2-stars.svg b/assets/surface-icons/filter-2-stars.svg new file mode 100644 index 00000000000..4ac112b0904 --- /dev/null +++ b/assets/surface-icons/filter-2-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-3-stars.svg b/assets/surface-icons/filter-3-stars.svg new file mode 100644 index 00000000000..15a70a5741b --- /dev/null +++ b/assets/surface-icons/filter-3-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-4-stars.svg b/assets/surface-icons/filter-4-stars.svg new file mode 100644 index 00000000000..2fa66a0f6a0 --- /dev/null +++ b/assets/surface-icons/filter-4-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-5-stars.svg b/assets/surface-icons/filter-5-stars.svg new file mode 100644 index 00000000000..c4aaf7e34c7 --- /dev/null +++ b/assets/surface-icons/filter-5-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-approved.svg b/assets/surface-icons/filter-approved.svg new file mode 100644 index 00000000000..c8402fd368a --- /dev/null +++ b/assets/surface-icons/filter-approved.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-color-tag.svg b/assets/surface-icons/filter-color-tag.svg new file mode 100644 index 00000000000..f5ab27e9122 --- /dev/null +++ b/assets/surface-icons/filter-color-tag.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-flag.svg b/assets/surface-icons/filter-flag.svg new file mode 100644 index 00000000000..ebc03a2ac81 --- /dev/null +++ b/assets/surface-icons/filter-flag.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-green.svg b/assets/surface-icons/filter-green.svg new file mode 100644 index 00000000000..0f2941b8db8 --- /dev/null +++ b/assets/surface-icons/filter-green.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-no-flag.svg b/assets/surface-icons/filter-no-flag.svg new file mode 100644 index 00000000000..9fc7f654cdc --- /dev/null +++ b/assets/surface-icons/filter-no-flag.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-purple.svg b/assets/surface-icons/filter-purple.svg new file mode 100644 index 00000000000..f5c90765ac7 --- /dev/null +++ b/assets/surface-icons/filter-purple.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-rating-1-star.svg b/assets/surface-icons/filter-rating-1-star.svg new file mode 100644 index 00000000000..ea0f1bcd245 --- /dev/null +++ b/assets/surface-icons/filter-rating-1-star.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-rating-2-stars.svg b/assets/surface-icons/filter-rating-2-stars.svg new file mode 100644 index 00000000000..4ac112b0904 --- /dev/null +++ b/assets/surface-icons/filter-rating-2-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-rating-3-stars.svg b/assets/surface-icons/filter-rating-3-stars.svg new file mode 100644 index 00000000000..15a70a5741b --- /dev/null +++ b/assets/surface-icons/filter-rating-3-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-rating-4-stars.svg b/assets/surface-icons/filter-rating-4-stars.svg new file mode 100644 index 00000000000..2fa66a0f6a0 --- /dev/null +++ b/assets/surface-icons/filter-rating-4-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-rating-5-stars.svg b/assets/surface-icons/filter-rating-5-stars.svg new file mode 100644 index 00000000000..c4aaf7e34c7 --- /dev/null +++ b/assets/surface-icons/filter-rating-5-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-rating-none.svg b/assets/surface-icons/filter-rating-none.svg new file mode 100644 index 00000000000..7cbb72b2f18 --- /dev/null +++ b/assets/surface-icons/filter-rating-none.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-red.svg b/assets/surface-icons/filter-red.svg new file mode 100644 index 00000000000..30a8c4dd28b --- /dev/null +++ b/assets/surface-icons/filter-red.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-rejected.svg b/assets/surface-icons/filter-rejected.svg new file mode 100644 index 00000000000..c8125c8bcfa --- /dev/null +++ b/assets/surface-icons/filter-rejected.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-tag-blue.svg b/assets/surface-icons/filter-tag-blue.svg new file mode 100644 index 00000000000..f24e58c162a --- /dev/null +++ b/assets/surface-icons/filter-tag-blue.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-tag-green.svg b/assets/surface-icons/filter-tag-green.svg new file mode 100644 index 00000000000..72b5a757231 --- /dev/null +++ b/assets/surface-icons/filter-tag-green.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-tag-none.svg b/assets/surface-icons/filter-tag-none.svg new file mode 100644 index 00000000000..efc0c23b2f5 --- /dev/null +++ b/assets/surface-icons/filter-tag-none.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-tag-orange.svg b/assets/surface-icons/filter-tag-orange.svg new file mode 100644 index 00000000000..ebc31847dcf --- /dev/null +++ b/assets/surface-icons/filter-tag-orange.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-tag-pink.svg b/assets/surface-icons/filter-tag-pink.svg new file mode 100644 index 00000000000..b6648a111cd --- /dev/null +++ b/assets/surface-icons/filter-tag-pink.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-tag-purple.svg b/assets/surface-icons/filter-tag-purple.svg new file mode 100644 index 00000000000..378ab56dd3d --- /dev/null +++ b/assets/surface-icons/filter-tag-purple.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-tag-red.svg b/assets/surface-icons/filter-tag-red.svg new file mode 100644 index 00000000000..5c1305551d9 --- /dev/null +++ b/assets/surface-icons/filter-tag-red.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-tag-yellow.svg b/assets/surface-icons/filter-tag-yellow.svg new file mode 100644 index 00000000000..2e069f1b041 --- /dev/null +++ b/assets/surface-icons/filter-tag-yellow.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/filter-yellow.svg b/assets/surface-icons/filter-yellow.svg new file mode 100644 index 00000000000..81d694a52e1 --- /dev/null +++ b/assets/surface-icons/filter-yellow.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/first-image.svg b/assets/surface-icons/first-image.svg new file mode 100644 index 00000000000..761bc71094b --- /dev/null +++ b/assets/surface-icons/first-image.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/focus-assist.svg b/assets/surface-icons/focus-assist.svg new file mode 100644 index 00000000000..8701e804e90 --- /dev/null +++ b/assets/surface-icons/focus-assist.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/focus-meter-tool.svg b/assets/surface-icons/focus-meter-tool.svg new file mode 100644 index 00000000000..cfd0c4cd25a --- /dev/null +++ b/assets/surface-icons/focus-meter-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/focus-point-tool.svg b/assets/surface-icons/focus-point-tool.svg new file mode 100644 index 00000000000..0cc5e559115 --- /dev/null +++ b/assets/surface-icons/focus-point-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/full-screen.svg b/assets/surface-icons/full-screen.svg new file mode 100644 index 00000000000..ed54a59402d --- /dev/null +++ b/assets/surface-icons/full-screen.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/grain-granularity.svg b/assets/surface-icons/grain-granularity.svg new file mode 100644 index 00000000000..f7ad06df065 --- /dev/null +++ b/assets/surface-icons/grain-granularity.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/grain-impact.svg b/assets/surface-icons/grain-impact.svg new file mode 100644 index 00000000000..d4dc1e29e41 --- /dev/null +++ b/assets/surface-icons/grain-impact.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/hard-light.svg b/assets/surface-icons/hard-light.svg new file mode 100644 index 00000000000..8d2f52cb1fb --- /dev/null +++ b/assets/surface-icons/hard-light.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/heal-brush.svg b/assets/surface-icons/heal-brush.svg new file mode 100644 index 00000000000..21c96008367 --- /dev/null +++ b/assets/surface-icons/heal-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/highlight-brush.svg b/assets/surface-icons/highlight-brush.svg new file mode 100644 index 00000000000..ae28829a8fa --- /dev/null +++ b/assets/surface-icons/highlight-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/highlight-lightness.svg b/assets/surface-icons/highlight-lightness.svg new file mode 100644 index 00000000000..ab5f5cdd68d --- /dev/null +++ b/assets/surface-icons/highlight-lightness.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/highlight-tone-x.svg b/assets/surface-icons/highlight-tone-x.svg new file mode 100644 index 00000000000..ab5f5cdd68d --- /dev/null +++ b/assets/surface-icons/highlight-tone-x.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/highlight-tone-y.svg b/assets/surface-icons/highlight-tone-y.svg new file mode 100644 index 00000000000..e72ed8050dc --- /dev/null +++ b/assets/surface-icons/highlight-tone-y.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/highlight.svg b/assets/surface-icons/highlight.svg new file mode 100644 index 00000000000..059d69a7264 --- /dev/null +++ b/assets/surface-icons/highlight.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/assets/surface-icons/histogram-view.svg b/assets/surface-icons/histogram-view.svg new file mode 100644 index 00000000000..bce65b0ec8e --- /dev/null +++ b/assets/surface-icons/histogram-view.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/import-images.svg b/assets/surface-icons/import-images.svg new file mode 100644 index 00000000000..a6fab52fffc --- /dev/null +++ b/assets/surface-icons/import-images.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/increase-zoom.svg b/assets/surface-icons/increase-zoom.svg new file mode 100644 index 00000000000..171389cfd50 --- /dev/null +++ b/assets/surface-icons/increase-zoom.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/invert-mask.svg b/assets/surface-icons/invert-mask.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/invert-mask.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/invert-selection.svg b/assets/surface-icons/invert-selection.svg new file mode 100644 index 00000000000..531f2034e23 --- /dev/null +++ b/assets/surface-icons/invert-selection.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/iso-down.svg b/assets/surface-icons/iso-down.svg new file mode 100644 index 00000000000..1509c2084cb --- /dev/null +++ b/assets/surface-icons/iso-down.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/iso-up.svg b/assets/surface-icons/iso-up.svg new file mode 100644 index 00000000000..1459dbe7009 --- /dev/null +++ b/assets/surface-icons/iso-up.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/kelvin.svg b/assets/surface-icons/kelvin.svg new file mode 100644 index 00000000000..2cb909961f9 --- /dev/null +++ b/assets/surface-icons/kelvin.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/assets/surface-icons/keystone-horizontal.svg b/assets/surface-icons/keystone-horizontal.svg new file mode 100644 index 00000000000..c58d3a89aec --- /dev/null +++ b/assets/surface-icons/keystone-horizontal.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/keystone-tool.svg b/assets/surface-icons/keystone-tool.svg new file mode 100644 index 00000000000..7d765a6df52 --- /dev/null +++ b/assets/surface-icons/keystone-tool.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/keystone-vertical.svg b/assets/surface-icons/keystone-vertical.svg new file mode 100644 index 00000000000..c2bddb71d7d --- /dev/null +++ b/assets/surface-icons/keystone-vertical.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/last-image.svg b/assets/surface-icons/last-image.svg new file mode 100644 index 00000000000..012b436b758 --- /dev/null +++ b/assets/surface-icons/last-image.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/layer-opacity.svg b/assets/surface-icons/layer-opacity.svg new file mode 100644 index 00000000000..29564b1bba2 --- /dev/null +++ b/assets/surface-icons/layer-opacity.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/light-falloff.svg b/assets/surface-icons/light-falloff.svg new file mode 100644 index 00000000000..8079b29a1a1 --- /dev/null +++ b/assets/surface-icons/light-falloff.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/lighten.svg b/assets/surface-icons/lighten.svg new file mode 100644 index 00000000000..d14ab182ef5 --- /dev/null +++ b/assets/surface-icons/lighten.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/linear-gradient-tool.svg b/assets/surface-icons/linear-gradient-tool.svg new file mode 100644 index 00000000000..44f473e964f --- /dev/null +++ b/assets/surface-icons/linear-gradient-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/live-view.svg b/assets/surface-icons/live-view.svg new file mode 100644 index 00000000000..1cd7e9c0786 --- /dev/null +++ b/assets/surface-icons/live-view.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/loupe-tool.svg b/assets/surface-icons/loupe-tool.svg new file mode 100644 index 00000000000..4ea79d0d631 --- /dev/null +++ b/assets/surface-icons/loupe-tool.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/luma-range.svg b/assets/surface-icons/luma-range.svg new file mode 100644 index 00000000000..f4484c9fc9a --- /dev/null +++ b/assets/surface-icons/luma-range.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/mask-invert.svg b/assets/surface-icons/mask-invert.svg new file mode 100644 index 00000000000..75beb554764 --- /dev/null +++ b/assets/surface-icons/mask-invert.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/surface-icons/mask-next.svg b/assets/surface-icons/mask-next.svg new file mode 100644 index 00000000000..d9d3b94fe7e --- /dev/null +++ b/assets/surface-icons/mask-next.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/surface-icons/mask-previous.svg b/assets/surface-icons/mask-previous.svg new file mode 100644 index 00000000000..06018aaa3d8 --- /dev/null +++ b/assets/surface-icons/mask-previous.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/surface-icons/mask-visible.svg b/assets/surface-icons/mask-visible.svg new file mode 100644 index 00000000000..1ee1558ab61 --- /dev/null +++ b/assets/surface-icons/mask-visible.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/surface-icons/master-tone-x.svg b/assets/surface-icons/master-tone-x.svg new file mode 100644 index 00000000000..45f2cc8f3e4 --- /dev/null +++ b/assets/surface-icons/master-tone-x.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/master-tone-y.svg b/assets/surface-icons/master-tone-y.svg new file mode 100644 index 00000000000..4e0bd5c7f52 --- /dev/null +++ b/assets/surface-icons/master-tone-y.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/midtone-lightness.svg b/assets/surface-icons/midtone-lightness.svg new file mode 100644 index 00000000000..ab5f5cdd68d --- /dev/null +++ b/assets/surface-icons/midtone-lightness.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/midtone-tone-x.svg b/assets/surface-icons/midtone-tone-x.svg new file mode 100644 index 00000000000..3f3af888e2a --- /dev/null +++ b/assets/surface-icons/midtone-tone-x.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/midtone-tone-y.svg b/assets/surface-icons/midtone-tone-y.svg new file mode 100644 index 00000000000..713b38ece41 --- /dev/null +++ b/assets/surface-icons/midtone-tone-y.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/moire-amount.svg b/assets/surface-icons/moire-amount.svg new file mode 100644 index 00000000000..11762e807de --- /dev/null +++ b/assets/surface-icons/moire-amount.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/moire-pattern.svg b/assets/surface-icons/moire-pattern.svg new file mode 100644 index 00000000000..32d391629ed --- /dev/null +++ b/assets/surface-icons/moire-pattern.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/move-to-trash.svg b/assets/surface-icons/move-to-trash.svg new file mode 100644 index 00000000000..524b3456908 --- /dev/null +++ b/assets/surface-icons/move-to-trash.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/move-tool.svg b/assets/surface-icons/move-tool.svg new file mode 100644 index 00000000000..7a4f079c882 --- /dev/null +++ b/assets/surface-icons/move-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/multiply.svg b/assets/surface-icons/multiply.svg new file mode 100644 index 00000000000..85176f8cd0d --- /dev/null +++ b/assets/surface-icons/multiply.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/new-clone-layer.svg b/assets/surface-icons/new-clone-layer.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/new-clone-layer.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/new-empty-layer.svg b/assets/surface-icons/new-empty-layer.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/new-empty-layer.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/new-filled-layer.svg b/assets/surface-icons/new-filled-layer.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/new-filled-layer.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/new-heal-layer.svg b/assets/surface-icons/new-heal-layer.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/new-heal-layer.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/new-variant.svg b/assets/surface-icons/new-variant.svg new file mode 100644 index 00000000000..b427a45cb39 --- /dev/null +++ b/assets/surface-icons/new-variant.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/next-collection.svg b/assets/surface-icons/next-collection.svg new file mode 100644 index 00000000000..012b436b758 --- /dev/null +++ b/assets/surface-icons/next-collection.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/next-group.svg b/assets/surface-icons/next-group.svg new file mode 100644 index 00000000000..081e3b3667d --- /dev/null +++ b/assets/surface-icons/next-group.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/next-image-import.svg b/assets/surface-icons/next-image-import.svg new file mode 100644 index 00000000000..18fd50f09b0 --- /dev/null +++ b/assets/surface-icons/next-image-import.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/next-image.svg b/assets/surface-icons/next-image.svg new file mode 100644 index 00000000000..012b436b758 --- /dev/null +++ b/assets/surface-icons/next-image.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/next-set.svg b/assets/surface-icons/next-set.svg new file mode 100644 index 00000000000..012b436b758 --- /dev/null +++ b/assets/surface-icons/next-set.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/nr-color.svg b/assets/surface-icons/nr-color.svg new file mode 100644 index 00000000000..2ae59d00f09 --- /dev/null +++ b/assets/surface-icons/nr-color.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/nr-detail.svg b/assets/surface-icons/nr-detail.svg new file mode 100644 index 00000000000..a83aafa7711 --- /dev/null +++ b/assets/surface-icons/nr-detail.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/nr-luminance.svg b/assets/surface-icons/nr-luminance.svg new file mode 100644 index 00000000000..ea003fdc507 --- /dev/null +++ b/assets/surface-icons/nr-luminance.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/nr-single-pixel.svg b/assets/surface-icons/nr-single-pixel.svg new file mode 100644 index 00000000000..494c099aa26 --- /dev/null +++ b/assets/surface-icons/nr-single-pixel.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/overlay-horizontal.svg b/assets/surface-icons/overlay-horizontal.svg new file mode 100644 index 00000000000..8625e3aae0e --- /dev/null +++ b/assets/surface-icons/overlay-horizontal.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/overlay-opacity.svg b/assets/surface-icons/overlay-opacity.svg new file mode 100644 index 00000000000..92119501c5b --- /dev/null +++ b/assets/surface-icons/overlay-opacity.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/overlay-scale.svg b/assets/surface-icons/overlay-scale.svg new file mode 100644 index 00000000000..0c936ad73c4 --- /dev/null +++ b/assets/surface-icons/overlay-scale.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/overlay-tool.svg b/assets/surface-icons/overlay-tool.svg new file mode 100644 index 00000000000..6a785a4b06d --- /dev/null +++ b/assets/surface-icons/overlay-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/overlay-vertical.svg b/assets/surface-icons/overlay-vertical.svg new file mode 100644 index 00000000000..859e6fa3271 --- /dev/null +++ b/assets/surface-icons/overlay-vertical.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/overlay.svg b/assets/surface-icons/overlay.svg new file mode 100644 index 00000000000..350ec74cace --- /dev/null +++ b/assets/surface-icons/overlay.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pan-tool.svg b/assets/surface-icons/pan-tool.svg new file mode 100644 index 00000000000..7dc3a3305da --- /dev/null +++ b/assets/surface-icons/pan-tool.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pen-black.svg b/assets/surface-icons/pen-black.svg new file mode 100644 index 00000000000..ac8a187511f --- /dev/null +++ b/assets/surface-icons/pen-black.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pen-blue.svg b/assets/surface-icons/pen-blue.svg new file mode 100644 index 00000000000..31da10983bf --- /dev/null +++ b/assets/surface-icons/pen-blue.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pen-green.svg b/assets/surface-icons/pen-green.svg new file mode 100644 index 00000000000..ecdd40823fa --- /dev/null +++ b/assets/surface-icons/pen-green.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pen-red.svg b/assets/surface-icons/pen-red.svg new file mode 100644 index 00000000000..27affc4ce39 --- /dev/null +++ b/assets/surface-icons/pen-red.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pen-size.svg b/assets/surface-icons/pen-size.svg new file mode 100644 index 00000000000..60bdb180b03 --- /dev/null +++ b/assets/surface-icons/pen-size.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pen-white.svg b/assets/surface-icons/pen-white.svg new file mode 100644 index 00000000000..154c9d4c462 --- /dev/null +++ b/assets/surface-icons/pen-white.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pen-yellow.svg b/assets/surface-icons/pen-yellow.svg new file mode 100644 index 00000000000..1dbb5b89e6b --- /dev/null +++ b/assets/surface-icons/pen-yellow.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-color-correction.svg b/assets/surface-icons/pick-color-correction.svg new file mode 100644 index 00000000000..38dfa2ac383 --- /dev/null +++ b/assets/surface-icons/pick-color-correction.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-curve-point.svg b/assets/surface-icons/pick-curve-point.svg new file mode 100644 index 00000000000..901066b597b --- /dev/null +++ b/assets/surface-icons/pick-curve-point.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-focus-point.svg b/assets/surface-icons/pick-focus-point.svg new file mode 100644 index 00000000000..25ae9b924f3 --- /dev/null +++ b/assets/surface-icons/pick-focus-point.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-highlight-level.svg b/assets/surface-icons/pick-highlight-level.svg new file mode 100644 index 00000000000..9254b539f45 --- /dev/null +++ b/assets/surface-icons/pick-highlight-level.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-luma-curve.svg b/assets/surface-icons/pick-luma-curve.svg new file mode 100644 index 00000000000..0c89787163c --- /dev/null +++ b/assets/surface-icons/pick-luma-curve.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-norm-target.svg b/assets/surface-icons/pick-norm-target.svg new file mode 100644 index 00000000000..94e5d81a9d5 --- /dev/null +++ b/assets/surface-icons/pick-norm-target.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-shadow-level.svg b/assets/surface-icons/pick-shadow-level.svg new file mode 100644 index 00000000000..7c5622ca889 --- /dev/null +++ b/assets/surface-icons/pick-shadow-level.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-skin-color.svg b/assets/surface-icons/pick-skin-color.svg new file mode 100644 index 00000000000..e20e2fc7085 --- /dev/null +++ b/assets/surface-icons/pick-skin-color.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/pick-variant.svg b/assets/surface-icons/pick-variant.svg new file mode 100644 index 00000000000..638c3b3d95d --- /dev/null +++ b/assets/surface-icons/pick-variant.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/preset-apply-ai.svg b/assets/surface-icons/preset-apply-ai.svg new file mode 100644 index 00000000000..7e670b8bd2f --- /dev/null +++ b/assets/surface-icons/preset-apply-ai.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/assets/surface-icons/preset-apply.svg b/assets/surface-icons/preset-apply.svg new file mode 100644 index 00000000000..fb6da353a9d --- /dev/null +++ b/assets/surface-icons/preset-apply.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/surface-icons/previous-collection.svg b/assets/surface-icons/previous-collection.svg new file mode 100644 index 00000000000..761bc71094b --- /dev/null +++ b/assets/surface-icons/previous-collection.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/previous-group.svg b/assets/surface-icons/previous-group.svg new file mode 100644 index 00000000000..76c0453d84a --- /dev/null +++ b/assets/surface-icons/previous-group.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/previous-image-import.svg b/assets/surface-icons/previous-image-import.svg new file mode 100644 index 00000000000..439bbbabf99 --- /dev/null +++ b/assets/surface-icons/previous-image-import.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/previous-image.svg b/assets/surface-icons/previous-image.svg new file mode 100644 index 00000000000..761bc71094b --- /dev/null +++ b/assets/surface-icons/previous-image.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/previous-set.svg b/assets/surface-icons/previous-set.svg new file mode 100644 index 00000000000..761bc71094b --- /dev/null +++ b/assets/surface-icons/previous-set.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/print.svg b/assets/surface-icons/print.svg new file mode 100644 index 00000000000..38a13a7a4d1 --- /dev/null +++ b/assets/surface-icons/print.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/process.svg b/assets/surface-icons/process.svg new file mode 100644 index 00000000000..a6fab52fffc --- /dev/null +++ b/assets/surface-icons/process.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/promote-variant.svg b/assets/surface-icons/promote-variant.svg new file mode 100644 index 00000000000..62c902196ac --- /dev/null +++ b/assets/surface-icons/promote-variant.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/radial-gradient-tool.svg b/assets/surface-icons/radial-gradient-tool.svg new file mode 100644 index 00000000000..caeb05c1f00 --- /dev/null +++ b/assets/surface-icons/radial-gradient-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rasterize-mask.svg b/assets/surface-icons/rasterize-mask.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/rasterize-mask.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-1-star.svg b/assets/surface-icons/rate-1-star.svg new file mode 100644 index 00000000000..8451f134f18 --- /dev/null +++ b/assets/surface-icons/rate-1-star.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-2-star.svg b/assets/surface-icons/rate-2-star.svg new file mode 100644 index 00000000000..11ae16de688 --- /dev/null +++ b/assets/surface-icons/rate-2-star.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-2-stars.svg b/assets/surface-icons/rate-2-stars.svg new file mode 100644 index 00000000000..11ae16de688 --- /dev/null +++ b/assets/surface-icons/rate-2-stars.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-3-star.svg b/assets/surface-icons/rate-3-star.svg new file mode 100644 index 00000000000..ed4ce210a8b --- /dev/null +++ b/assets/surface-icons/rate-3-star.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-3-stars.svg b/assets/surface-icons/rate-3-stars.svg new file mode 100644 index 00000000000..ed4ce210a8b --- /dev/null +++ b/assets/surface-icons/rate-3-stars.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-4-star.svg b/assets/surface-icons/rate-4-star.svg new file mode 100644 index 00000000000..cf1f0ce869a --- /dev/null +++ b/assets/surface-icons/rate-4-star.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-4-stars.svg b/assets/surface-icons/rate-4-stars.svg new file mode 100644 index 00000000000..cf1f0ce869a --- /dev/null +++ b/assets/surface-icons/rate-4-stars.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-5-star.svg b/assets/surface-icons/rate-5-star.svg new file mode 100644 index 00000000000..7ef0c582ea0 --- /dev/null +++ b/assets/surface-icons/rate-5-star.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rate-5-stars.svg b/assets/surface-icons/rate-5-stars.svg new file mode 100644 index 00000000000..7ef0c582ea0 --- /dev/null +++ b/assets/surface-icons/rate-5-stars.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/recipe-proofing.svg b/assets/surface-icons/recipe-proofing.svg new file mode 100644 index 00000000000..273570d77e8 --- /dev/null +++ b/assets/surface-icons/recipe-proofing.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/redo.svg b/assets/surface-icons/redo.svg new file mode 100644 index 00000000000..1108320377f --- /dev/null +++ b/assets/surface-icons/redo.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/refine-mask.svg b/assets/surface-icons/refine-mask.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/refine-mask.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/regenerate-previews.svg b/assets/surface-icons/regenerate-previews.svg new file mode 100644 index 00000000000..5161cc0c7e1 --- /dev/null +++ b/assets/surface-icons/regenerate-previews.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/remove-layer.svg b/assets/surface-icons/remove-layer.svg new file mode 100644 index 00000000000..731e6267389 --- /dev/null +++ b/assets/surface-icons/remove-layer.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rename.svg b/assets/surface-icons/rename.svg new file mode 100644 index 00000000000..57f23d008dc --- /dev/null +++ b/assets/surface-icons/rename.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/reset-adjustments.svg b/assets/surface-icons/reset-adjustments.svg new file mode 100644 index 00000000000..9934213000e --- /dev/null +++ b/assets/surface-icons/reset-adjustments.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/reset-develop.svg b/assets/surface-icons/reset-develop.svg new file mode 100644 index 00000000000..f93f5b3223e --- /dev/null +++ b/assets/surface-icons/reset-develop.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/surface-icons/rotate-freehand-tool.svg b/assets/surface-icons/rotate-freehand-tool.svg new file mode 100644 index 00000000000..8956150ea41 --- /dev/null +++ b/assets/surface-icons/rotate-freehand-tool.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rotate-left.svg b/assets/surface-icons/rotate-left.svg new file mode 100644 index 00000000000..9934213000e --- /dev/null +++ b/assets/surface-icons/rotate-left.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rotate-photo-left.svg b/assets/surface-icons/rotate-photo-left.svg new file mode 100644 index 00000000000..fbbc0702722 --- /dev/null +++ b/assets/surface-icons/rotate-photo-left.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/surface-icons/rotate-photo-right.svg b/assets/surface-icons/rotate-photo-right.svg new file mode 100644 index 00000000000..acb03417eb7 --- /dev/null +++ b/assets/surface-icons/rotate-photo-right.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/surface-icons/rotate-right.svg b/assets/surface-icons/rotate-right.svg new file mode 100644 index 00000000000..9934213000e --- /dev/null +++ b/assets/surface-icons/rotate-right.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/rotation-tool.svg b/assets/surface-icons/rotation-tool.svg new file mode 100644 index 00000000000..b96ca638fd1 --- /dev/null +++ b/assets/surface-icons/rotation-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/saturation-brush.svg b/assets/surface-icons/saturation-brush.svg new file mode 100644 index 00000000000..ae28829a8fa --- /dev/null +++ b/assets/surface-icons/saturation-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/saturation.svg b/assets/surface-icons/saturation.svg new file mode 100644 index 00000000000..a0f8c1e3d00 --- /dev/null +++ b/assets/surface-icons/saturation.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-1-star.svg b/assets/surface-icons/select-1-star.svg new file mode 100644 index 00000000000..5161cc0c7e1 --- /dev/null +++ b/assets/surface-icons/select-1-star.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-2-stars.svg b/assets/surface-icons/select-2-stars.svg new file mode 100644 index 00000000000..5161cc0c7e1 --- /dev/null +++ b/assets/surface-icons/select-2-stars.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-3-stars.svg b/assets/surface-icons/select-3-stars.svg new file mode 100644 index 00000000000..5161cc0c7e1 --- /dev/null +++ b/assets/surface-icons/select-3-stars.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-4-stars.svg b/assets/surface-icons/select-4-stars.svg new file mode 100644 index 00000000000..5161cc0c7e1 --- /dev/null +++ b/assets/surface-icons/select-4-stars.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-5-stars.svg b/assets/surface-icons/select-5-stars.svg new file mode 100644 index 00000000000..5161cc0c7e1 --- /dev/null +++ b/assets/surface-icons/select-5-stars.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-all-photos.svg b/assets/surface-icons/select-all-photos.svg new file mode 100644 index 00000000000..9487b20331e --- /dev/null +++ b/assets/surface-icons/select-all-photos.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/surface-icons/select-all.svg b/assets/surface-icons/select-all.svg new file mode 100644 index 00000000000..531f2034e23 --- /dev/null +++ b/assets/surface-icons/select-all.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-background.svg b/assets/surface-icons/select-background.svg new file mode 100644 index 00000000000..9439d4e39c0 --- /dev/null +++ b/assets/surface-icons/select-background.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-brush.svg b/assets/surface-icons/select-brush.svg new file mode 100644 index 00000000000..21c96008367 --- /dev/null +++ b/assets/surface-icons/select-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-by-color.svg b/assets/surface-icons/select-by-color.svg new file mode 100644 index 00000000000..ba3cde70827 --- /dev/null +++ b/assets/surface-icons/select-by-color.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-by-shape.svg b/assets/surface-icons/select-by-shape.svg new file mode 100644 index 00000000000..d39e8e320a9 --- /dev/null +++ b/assets/surface-icons/select-by-shape.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-by-tone.svg b/assets/surface-icons/select-by-tone.svg new file mode 100644 index 00000000000..27d447952a8 --- /dev/null +++ b/assets/surface-icons/select-by-tone.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-eraser.svg b/assets/surface-icons/select-eraser.svg new file mode 100644 index 00000000000..1ab6cc1fe98 --- /dev/null +++ b/assets/surface-icons/select-eraser.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-freehand.svg b/assets/surface-icons/select-freehand.svg new file mode 100644 index 00000000000..c51481ffac5 --- /dev/null +++ b/assets/surface-icons/select-freehand.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-layer-down.svg b/assets/surface-icons/select-layer-down.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/select-layer-down.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-layer-up.svg b/assets/surface-icons/select-layer-up.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/select-layer-up.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-magic-wand.svg b/assets/surface-icons/select-magic-wand.svg new file mode 100644 index 00000000000..5e9caa99ddd --- /dev/null +++ b/assets/surface-icons/select-magic-wand.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-no-photos.svg b/assets/surface-icons/select-no-photos.svg new file mode 100644 index 00000000000..afc5e2efc61 --- /dev/null +++ b/assets/surface-icons/select-no-photos.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/surface-icons/select-pen.svg b/assets/surface-icons/select-pen.svg new file mode 100644 index 00000000000..1ab6cc1fe98 --- /dev/null +++ b/assets/surface-icons/select-pen.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-primary-only.svg b/assets/surface-icons/select-primary-only.svg new file mode 100644 index 00000000000..c0037607287 --- /dev/null +++ b/assets/surface-icons/select-primary-only.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-same-color-tag.svg b/assets/surface-icons/select-same-color-tag.svg new file mode 100644 index 00000000000..8d193b3f4e4 --- /dev/null +++ b/assets/surface-icons/select-same-color-tag.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-same-sequence-id.svg b/assets/surface-icons/select-same-sequence-id.svg new file mode 100644 index 00000000000..a390e711dd6 --- /dev/null +++ b/assets/surface-icons/select-same-sequence-id.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-same-variant-pos.svg b/assets/surface-icons/select-same-variant-pos.svg new file mode 100644 index 00000000000..50c9c222d67 --- /dev/null +++ b/assets/surface-icons/select-same-variant-pos.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-smooth.svg b/assets/surface-icons/select-smooth.svg new file mode 100644 index 00000000000..8c2bedd3703 --- /dev/null +++ b/assets/surface-icons/select-smooth.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-subject.svg b/assets/surface-icons/select-subject.svg new file mode 100644 index 00000000000..0243e9e1b3c --- /dev/null +++ b/assets/surface-icons/select-subject.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tag-blue.svg b/assets/surface-icons/select-tag-blue.svg new file mode 100644 index 00000000000..08c5c8357a4 --- /dev/null +++ b/assets/surface-icons/select-tag-blue.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tag-green.svg b/assets/surface-icons/select-tag-green.svg new file mode 100644 index 00000000000..f793708b4f3 --- /dev/null +++ b/assets/surface-icons/select-tag-green.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tag-none.svg b/assets/surface-icons/select-tag-none.svg new file mode 100644 index 00000000000..57bc1971fda --- /dev/null +++ b/assets/surface-icons/select-tag-none.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tag-orange.svg b/assets/surface-icons/select-tag-orange.svg new file mode 100644 index 00000000000..6e77522cd4b --- /dev/null +++ b/assets/surface-icons/select-tag-orange.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tag-pink.svg b/assets/surface-icons/select-tag-pink.svg new file mode 100644 index 00000000000..5baee9cd6eb --- /dev/null +++ b/assets/surface-icons/select-tag-pink.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tag-purple.svg b/assets/surface-icons/select-tag-purple.svg new file mode 100644 index 00000000000..9a97c94e6a8 --- /dev/null +++ b/assets/surface-icons/select-tag-purple.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tag-red.svg b/assets/surface-icons/select-tag-red.svg new file mode 100644 index 00000000000..dec04060e0b --- /dev/null +++ b/assets/surface-icons/select-tag-red.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tag-yellow.svg b/assets/surface-icons/select-tag-yellow.svg new file mode 100644 index 00000000000..3a006a2aa02 --- /dev/null +++ b/assets/surface-icons/select-tag-yellow.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-tool.svg b/assets/surface-icons/select-tool.svg new file mode 100644 index 00000000000..4bda22b8184 --- /dev/null +++ b/assets/surface-icons/select-tool.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/select-unrated.svg b/assets/surface-icons/select-unrated.svg new file mode 100644 index 00000000000..5161cc0c7e1 --- /dev/null +++ b/assets/surface-icons/select-unrated.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/set-compare-variant.svg b/assets/surface-icons/set-compare-variant.svg new file mode 100644 index 00000000000..d4ab00942b3 --- /dev/null +++ b/assets/surface-icons/set-compare-variant.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/shadow-brush.svg b/assets/surface-icons/shadow-brush.svg new file mode 100644 index 00000000000..58df1a86715 --- /dev/null +++ b/assets/surface-icons/shadow-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/shadow-lightness.svg b/assets/surface-icons/shadow-lightness.svg new file mode 100644 index 00000000000..ab5f5cdd68d --- /dev/null +++ b/assets/surface-icons/shadow-lightness.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/shadow-tone-x.svg b/assets/surface-icons/shadow-tone-x.svg new file mode 100644 index 00000000000..7c42eb0052c --- /dev/null +++ b/assets/surface-icons/shadow-tone-x.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/shadow-tone-y.svg b/assets/surface-icons/shadow-tone-y.svg new file mode 100644 index 00000000000..9930778a103 --- /dev/null +++ b/assets/surface-icons/shadow-tone-y.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/shadow.svg b/assets/surface-icons/shadow.svg new file mode 100644 index 00000000000..567164f2df1 --- /dev/null +++ b/assets/surface-icons/shadow.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/assets/surface-icons/sharpen-brush.svg b/assets/surface-icons/sharpen-brush.svg new file mode 100644 index 00000000000..21c96008367 --- /dev/null +++ b/assets/surface-icons/sharpen-brush.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/sharpening-amount.svg b/assets/surface-icons/sharpening-amount.svg new file mode 100644 index 00000000000..6ccd731e4f0 --- /dev/null +++ b/assets/surface-icons/sharpening-amount.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/sharpening-halo.svg b/assets/surface-icons/sharpening-halo.svg new file mode 100644 index 00000000000..0e006759482 --- /dev/null +++ b/assets/surface-icons/sharpening-halo.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/sharpening-radius.svg b/assets/surface-icons/sharpening-radius.svg new file mode 100644 index 00000000000..3ad44a59ff8 --- /dev/null +++ b/assets/surface-icons/sharpening-radius.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/sharpening-threshold.svg b/assets/surface-icons/sharpening-threshold.svg new file mode 100644 index 00000000000..dd4451042d2 --- /dev/null +++ b/assets/surface-icons/sharpening-threshold.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/sharpness-falloff.svg b/assets/surface-icons/sharpness-falloff.svg new file mode 100644 index 00000000000..87eef788a22 --- /dev/null +++ b/assets/surface-icons/sharpness-falloff.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-filmstrip.svg b/assets/surface-icons/show-filmstrip.svg new file mode 100644 index 00000000000..bab1b5a2cc0 --- /dev/null +++ b/assets/surface-icons/show-filmstrip.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-grid.svg b/assets/surface-icons/show-grid.svg new file mode 100644 index 00000000000..d723ad323ce --- /dev/null +++ b/assets/surface-icons/show-grid.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-guides.svg b/assets/surface-icons/show-guides.svg new file mode 100644 index 00000000000..1c6ecc4093c --- /dev/null +++ b/assets/surface-icons/show-guides.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-hide-browser.svg b/assets/surface-icons/show-hide-browser.svg new file mode 100644 index 00000000000..ed54a59402d --- /dev/null +++ b/assets/surface-icons/show-hide-browser.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-hide-viewer.svg b/assets/surface-icons/show-hide-viewer.svg new file mode 100644 index 00000000000..ed54a59402d --- /dev/null +++ b/assets/surface-icons/show-hide-viewer.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-histogram.svg b/assets/surface-icons/show-histogram.svg new file mode 100644 index 00000000000..bce65b0ec8e --- /dev/null +++ b/assets/surface-icons/show-histogram.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-in-file-system.svg b/assets/surface-icons/show-in-file-system.svg new file mode 100644 index 00000000000..80da3388232 --- /dev/null +++ b/assets/surface-icons/show-in-file-system.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-in-library.svg b/assets/surface-icons/show-in-library.svg new file mode 100644 index 00000000000..625ad7eba90 --- /dev/null +++ b/assets/surface-icons/show-in-library.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/show-metadata.svg b/assets/surface-icons/show-metadata.svg new file mode 100644 index 00000000000..1a00fa704ab --- /dev/null +++ b/assets/surface-icons/show-metadata.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/shutter-speed-down.svg b/assets/surface-icons/shutter-speed-down.svg new file mode 100644 index 00000000000..75b223462c7 --- /dev/null +++ b/assets/surface-icons/shutter-speed-down.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/shutter-speed-up.svg b/assets/surface-icons/shutter-speed-up.svg new file mode 100644 index 00000000000..91370a2511f --- /dev/null +++ b/assets/surface-icons/shutter-speed-up.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/slide-show.svg b/assets/surface-icons/slide-show.svg new file mode 100644 index 00000000000..492694aad70 --- /dev/null +++ b/assets/surface-icons/slide-show.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/snap-to-90.svg b/assets/surface-icons/snap-to-90.svg new file mode 100644 index 00000000000..8dcee2e6aaa --- /dev/null +++ b/assets/surface-icons/snap-to-90.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/soft-light.svg b/assets/surface-icons/soft-light.svg new file mode 100644 index 00000000000..d91cce03317 --- /dev/null +++ b/assets/surface-icons/soft-light.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/spot-radius.svg b/assets/surface-icons/spot-radius.svg new file mode 100644 index 00000000000..7f40aca4825 --- /dev/null +++ b/assets/surface-icons/spot-radius.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/spot-removal-tool.svg b/assets/surface-icons/spot-removal-tool.svg new file mode 100644 index 00000000000..1ab6cc1fe98 --- /dev/null +++ b/assets/surface-icons/spot-removal-tool.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/straighten-tool.svg b/assets/surface-icons/straighten-tool.svg new file mode 100644 index 00000000000..0047294156b --- /dev/null +++ b/assets/surface-icons/straighten-tool.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/structure.svg b/assets/surface-icons/structure.svg new file mode 100644 index 00000000000..657a6d9363a --- /dev/null +++ b/assets/surface-icons/structure.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/switch-crop-orientation.svg b/assets/surface-icons/switch-crop-orientation.svg new file mode 100644 index 00000000000..2a37399a397 --- /dev/null +++ b/assets/surface-icons/switch-crop-orientation.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/tint.svg b/assets/surface-icons/tint.svg new file mode 100644 index 00000000000..792b35b8bd5 --- /dev/null +++ b/assets/surface-icons/tint.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-before-after.svg b/assets/surface-icons/toggle-before-after.svg new file mode 100644 index 00000000000..ad1d8353a4a --- /dev/null +++ b/assets/surface-icons/toggle-before-after.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-exposure-warn.svg b/assets/surface-icons/toggle-exposure-warn.svg new file mode 100644 index 00000000000..3f28f26de9c --- /dev/null +++ b/assets/surface-icons/toggle-exposure-warn.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-focus-mask.svg b/assets/surface-icons/toggle-focus-mask.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/toggle-focus-mask.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-grading.svg b/assets/surface-icons/toggle-grading.svg new file mode 100644 index 00000000000..f6e3620a729 --- /dev/null +++ b/assets/surface-icons/toggle-grading.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-layer-on-off.svg b/assets/surface-icons/toggle-layer-on-off.svg new file mode 100644 index 00000000000..0f002df5f13 --- /dev/null +++ b/assets/surface-icons/toggle-layer-on-off.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-multi-view.svg b/assets/surface-icons/toggle-multi-view.svg new file mode 100644 index 00000000000..3172e6b0b47 --- /dev/null +++ b/assets/surface-icons/toggle-multi-view.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-overlay.svg b/assets/surface-icons/toggle-overlay.svg new file mode 100644 index 00000000000..350ec74cace --- /dev/null +++ b/assets/surface-icons/toggle-overlay.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-select-image.svg b/assets/surface-icons/toggle-select-image.svg new file mode 100644 index 00000000000..38ce1adda6c --- /dev/null +++ b/assets/surface-icons/toggle-select-image.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-selection-points.svg b/assets/surface-icons/toggle-selection-points.svg new file mode 100644 index 00000000000..cdd2ec49a2d --- /dev/null +++ b/assets/surface-icons/toggle-selection-points.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/toggle-tools.svg b/assets/surface-icons/toggle-tools.svg new file mode 100644 index 00000000000..ed54a59402d --- /dev/null +++ b/assets/surface-icons/toggle-tools.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/tone-curve.svg b/assets/surface-icons/tone-curve.svg new file mode 100644 index 00000000000..a1cddc5e4cf --- /dev/null +++ b/assets/surface-icons/tone-curve.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/undo.svg b/assets/surface-icons/undo.svg new file mode 100644 index 00000000000..3393a2514df --- /dev/null +++ b/assets/surface-icons/undo.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/uniform-light.svg b/assets/surface-icons/uniform-light.svg new file mode 100644 index 00000000000..68554fbcd20 --- /dev/null +++ b/assets/surface-icons/uniform-light.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/vignetting.svg b/assets/surface-icons/vignetting.svg new file mode 100644 index 00000000000..2b853e8bc34 --- /dev/null +++ b/assets/surface-icons/vignetting.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/watermark-tool.svg b/assets/surface-icons/watermark-tool.svg new file mode 100644 index 00000000000..f5e19ad88ee --- /dev/null +++ b/assets/surface-icons/watermark-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/wb-picker-tool.svg b/assets/surface-icons/wb-picker-tool.svg new file mode 100644 index 00000000000..feac018b97e --- /dev/null +++ b/assets/surface-icons/wb-picker-tool.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/white-balance.svg b/assets/surface-icons/white-balance.svg new file mode 100644 index 00000000000..3f28f26de9c --- /dev/null +++ b/assets/surface-icons/white-balance.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/white.svg b/assets/surface-icons/white.svg new file mode 100644 index 00000000000..94073b98904 --- /dev/null +++ b/assets/surface-icons/white.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom-100.svg b/assets/surface-icons/zoom-100.svg new file mode 100644 index 00000000000..171389cfd50 --- /dev/null +++ b/assets/surface-icons/zoom-100.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom-200.svg b/assets/surface-icons/zoom-200.svg new file mode 100644 index 00000000000..171389cfd50 --- /dev/null +++ b/assets/surface-icons/zoom-200.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom-400.svg b/assets/surface-icons/zoom-400.svg new file mode 100644 index 00000000000..171389cfd50 --- /dev/null +++ b/assets/surface-icons/zoom-400.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom-actual-size.svg b/assets/surface-icons/zoom-actual-size.svg new file mode 100644 index 00000000000..e8b8b6adb7c --- /dev/null +++ b/assets/surface-icons/zoom-actual-size.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/assets/surface-icons/zoom-fit-view.svg b/assets/surface-icons/zoom-fit-view.svg new file mode 100644 index 00000000000..e737ba1c034 --- /dev/null +++ b/assets/surface-icons/zoom-fit-view.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/surface-icons/zoom-in-tool.svg b/assets/surface-icons/zoom-in-tool.svg new file mode 100644 index 00000000000..dd3a2b77339 --- /dev/null +++ b/assets/surface-icons/zoom-in-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom-in.svg b/assets/surface-icons/zoom-in.svg new file mode 100644 index 00000000000..663dd7058e0 --- /dev/null +++ b/assets/surface-icons/zoom-in.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom-out-tool.svg b/assets/surface-icons/zoom-out-tool.svg new file mode 100644 index 00000000000..a4e6cb406f8 --- /dev/null +++ b/assets/surface-icons/zoom-out-tool.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom-out.svg b/assets/surface-icons/zoom-out.svg new file mode 100644 index 00000000000..13f79c4ca54 --- /dev/null +++ b/assets/surface-icons/zoom-out.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom-to-fit.svg b/assets/surface-icons/zoom-to-fit.svg new file mode 100644 index 00000000000..171389cfd50 --- /dev/null +++ b/assets/surface-icons/zoom-to-fit.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/assets/surface-icons/zoom.svg b/assets/surface-icons/zoom.svg new file mode 100644 index 00000000000..51a209bcc9c --- /dev/null +++ b/assets/surface-icons/zoom.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/crates/surface/Cargo.toml b/crates/surface/Cargo.toml new file mode 100644 index 00000000000..881d029d623 --- /dev/null +++ b/crates/surface/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "lightcraft-surface" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "LightCraft control surfaces: devices, layouts, profiles, dial motion, contexts, feedback and the surface protocol (L2)" + +[lints] +workspace = true + +[dependencies] +lightcraft-develop = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +miniz_oxide = { workspace = true } diff --git a/crates/surface/src/binding.rs b/crates/surface/src/binding.rs new file mode 100644 index 00000000000..9a68c1c2902 --- /dev/null +++ b/crates/surface/src/binding.rs @@ -0,0 +1,135 @@ +//! What a control does. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::devices::PageGroup; + +/// A modifier held on a key or button while turning a dial. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Modifier { + /// Smaller steps (precise work). + Fine, + /// Bigger steps (sweeping changes). + Coarse, +} + +/// The action bound to a control. Stored in profiles (`control-surfaces.json`) and sent to +/// surfaces as JSON: `{"kind": "value", "target": "light.exposure"}`, +/// `{"kind": "command", "command": "photo.rate", "params": {"rating": 5}}`, … +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum Binding { + /// Turning moves this value (a dial); pressing a key bound to it makes the dials move it + /// until pressed again (TactileBridge's adjustment dial toggle). + Value { target: String }, + /// Run a LightCraft command (any engine or UI command id; `engine.commands` lists them). + Command { + command: String, + #[serde(default, skip_serializing_if = "Value::is_null")] + params: Value, + }, + /// Hold for smaller or bigger dial steps. + Modifier { modifier: Modifier }, + /// Next / previous page of a group (both groups when `group` is missing). + PageNext { + #[serde(default, skip_serializing_if = "Option::is_none")] + group: Option, + }, + PagePrevious { + #[serde(default, skip_serializing_if = "Option::is_none")] + group: Option, + }, + /// Show a page by name. + Page { page: String }, + /// Switch to a profile by name. + Profile { profile: String }, + /// The next profile in the list. + ProfileNext, + /// Put the value the dial moves back to its default (a dial press). + Reset, + /// Dials change every selected photo, not just the active one (TactileBridge's Auto Sync; + /// toggles). + ApplyToSelected, + /// Pages follow what LightCraft shows (toggles automatic switching). + FollowContext, +} + +impl Binding { + pub fn value(target: &str) -> Binding { + Binding::Value { target: target.to_string() } + } + + pub fn command(command: &str) -> Binding { + Binding::Command { command: command.to_string(), params: Value::Null } + } + + pub fn command_with(command: &str, params: Value) -> Binding { + Binding::Command { command: command.to_string(), params } + } + + /// The value this binding moves or focuses, if any. + pub fn target(&self) -> Option<&str> { + match self { + Binding::Value { target } => Some(target), + _ => None, + } + } + + /// A short English name for the binding (editor lists, device labels when no better one is + /// known). + pub fn describe(&self) -> String { + match self { + Binding::Value { target } => crate::targets::target_spec(target).map_or_else(|| target.clone(), |t| t.label.to_string()), + Binding::Command { command, params } => crate::icons::command_label(command, params), + Binding::Modifier { modifier: Modifier::Fine } => "Fine".into(), + Binding::Modifier { modifier: Modifier::Coarse } => "Coarse".into(), + Binding::PageNext { group: Some(PageGroup::Keys) } => "Next Key Page".into(), + Binding::PageNext { group: Some(PageGroup::Dials) } => "Next Dial Page".into(), + Binding::PageNext { group: None } => "Next Page".into(), + Binding::PagePrevious { group: Some(PageGroup::Keys) } => "Previous Key Page".into(), + Binding::PagePrevious { group: Some(PageGroup::Dials) } => "Previous Dial Page".into(), + Binding::PagePrevious { group: None } => "Previous Page".into(), + Binding::Page { page } => page.clone(), + Binding::Profile { profile } => profile.clone(), + Binding::ProfileNext => "Next Profile".into(), + Binding::Reset => "Reset Dial Value".into(), + Binding::ApplyToSelected => "Apply to Selected".into(), + Binding::FollowContext => "Follow Context".into(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn bindings_round_trip_as_tagged_json() { + let all = vec![ + Binding::value("light.exposure"), + Binding::command_with("photo.rate", json!({"rating": 5})), + Binding::command("edit.undo"), + Binding::Modifier { modifier: Modifier::Fine }, + Binding::PageNext { group: Some(PageGroup::Dials) }, + Binding::PagePrevious { group: None }, + Binding::Page { page: "Cull".into() }, + Binding::Profile { profile: "Wedding".into() }, + Binding::ProfileNext, + Binding::Reset, + Binding::ApplyToSelected, + Binding::FollowContext, + ]; + for b in all { + let v = serde_json::to_value(&b).unwrap(); + assert!(v["kind"].is_string(), "{v}"); + assert_eq!(serde_json::from_value::(v).unwrap(), b); + } + assert_eq!(serde_json::to_value(Binding::command("edit.undo")).unwrap(), json!({"kind": "command", "command": "edit.undo"})); + assert!(serde_json::from_value::(json!({"kind": "nope"})).is_err()); + } +} diff --git a/crates/surface/src/catalog.rs b/crates/surface/src/catalog.rs new file mode 100644 index 00000000000..839b963d229 --- /dev/null +++ b/crates/surface/src/catalog.rs @@ -0,0 +1,225 @@ +//! Every action a control can be given, in categories: the editor's action picker and the +//! actions a surface plugin lists in its own app (the Logi Options+ actions panel), so a user can +//! put LightCraft actions on keys and dials there too. +//! +//! Each entry has a stable `key` (`v.light.exposure`, `c.photo.rate.rating-5`, `s.applyToSelected`) +//! that plugins store in their own profiles; it is made from the binding alone, so it stays the +//! same between LightCraft versions as long as the binding does. + +use serde::Serialize; +use serde_json::Value; + +use crate::binding::{Binding, Modifier}; +use crate::devices::PageGroup; +use crate::targets::{TargetKind, all_targets}; + +/// One action. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Entry { + /// Stable id (see the module docs). + pub key: String, + /// The category (English; hosts translate it). + pub group: &'static str, + /// The action's name (English; hosts translate it or use a better label of their own). + pub label: String, + /// The icon (`surface.icons` returns its SVG). + pub icon: Option<&'static str>, + /// A value (turned on a dial) rather than something a key does once. + pub value: bool, + pub binding: Binding, +} + +/// Categories of key actions, in the order lists show them. +pub const COMMAND_GROUPS: &[&str] = &["Rating & Labels", "Browse & Select", "Edit", "Tools", "Masking", "View", "Photo", "Control Surface", "Other"]; + +/// The category of a key action. +pub fn command_group(b: &Binding) -> &'static str { + let Binding::Command { command, .. } = b else { return "Control Surface" }; + let head = command.split('.').next().unwrap_or(""); + match command.as_str() { + "photo.rate" | "photo.label" | "photo.flag" | "photo.pick" | "photo.reject" | "photo.unflag" => "Rating & Labels", + "photo.rotateLeft" | "photo.rotateRight" => "Photo", + "surface.maskPrevious" | "surface.maskNext" => "Masking", + "surface.dialogConfirm" | "surface.dialogCancel" => "Other", + _ => match head { + "library" | "select" | "selection" => "Browse & Select", + "edit" | "develop" | "settings" | "preset" => "Edit", + "tool" | "crop" | "spot" | "remove" | "brush" => "Tools", + "mask" => "Masking", + "view" | "zoom" => "View", + "photo" | "metadata" => "Photo", + "surface" => "Control Surface", + _ => "Other", + }, + } +} + +/// A short, safe slug of a JSON value for keys (`5`, `red`, `none`, `true`). +fn slug(v: &Value) -> String { + let raw = match v { + Value::Null => "none".to_string(), + Value::String(s) => s.clone(), + other => other.to_string(), + }; + raw.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').take(32).collect() +} + +/// The stable key of a binding. +pub fn key_of(b: &Binding) -> String { + match b { + Binding::Value { target } => format!("v.{target}"), + Binding::Command { command, params } => { + let mut k = format!("c.{command}"); + if let Value::Object(m) = params { + let mut fields: Vec<_> = m.iter().collect(); + fields.sort_by(|a, b| a.0.cmp(b.0)); + for (name, v) in fields { + k.push('.'); + k.extend(name.chars().filter(char::is_ascii_alphanumeric)); + k.push('-'); + k.push_str(&slug(v)); + } + } + k + } + Binding::Modifier { modifier: Modifier::Fine } => "s.fine".into(), + Binding::Modifier { modifier: Modifier::Coarse } => "s.coarse".into(), + Binding::PageNext { group } => format!("s.pageNext{}", group_suffix(*group)), + Binding::PagePrevious { group } => format!("s.pagePrevious{}", group_suffix(*group)), + Binding::Page { page } => format!("s.page.{}", slug(&Value::String(page.clone()))), + Binding::Profile { profile } => format!("s.profile.{}", slug(&Value::String(profile.clone()))), + Binding::ProfileNext => "s.profileNext".into(), + Binding::Reset => "s.reset".into(), + Binding::ApplyToSelected => "s.applyToSelected".into(), + Binding::FollowContext => "s.followContext".into(), + } +} + +fn group_suffix(g: Option) -> &'static str { + match g { + Some(PageGroup::Keys) => ".keys", + Some(PageGroup::Dials) => ".dials", + None => "", + } +} + +/// The surface's own actions (pages, modifiers, toggles). +fn surface_actions() -> Vec { + vec![ + Binding::PageNext { group: Some(PageGroup::Keys) }, + Binding::PagePrevious { group: Some(PageGroup::Keys) }, + Binding::PageNext { group: Some(PageGroup::Dials) }, + Binding::PagePrevious { group: Some(PageGroup::Dials) }, + Binding::Modifier { modifier: Modifier::Fine }, + Binding::Modifier { modifier: Modifier::Coarse }, + Binding::Reset, + Binding::ApplyToSelected, + Binding::FollowContext, + Binding::ProfileNext, + ] +} + +/// Every action: the dial values (develop panels in order, then masks, brush, Remove and view), +/// then the key actions by category. Keys are unique. +pub fn entries() -> Vec { + let mut out: Vec = all_targets() + .into_iter() + .map(|t| { + let b = Binding::value(&t.id); + Entry { + key: key_of(&b), + group: match t.kind { + TargetKind::Develop => t.group, + TargetKind::Mask => "Mask", + TargetKind::Ui => t.group, + }, + label: t.label.to_string(), + icon: crate::icons::icon_for(&b), + value: true, + binding: b, + } + }) + .collect(); + // key actions: TactileBridge's list as LightCraft maps it, then what the built-in profiles use + let mut commands: Vec = crate::tactilebridge::COMMANDS.iter().filter_map(|k| crate::tactilebridge::binding_of(k)).collect(); + for p in crate::defaults::profiles() { + commands.extend(p.base.values().cloned()); + for pg in &p.pages { + commands.extend(pg.bindings.values().cloned()); + } + } + commands.retain(|b| matches!(b, Binding::Command { .. })); + commands.extend(surface_actions()); + let mut seen = std::collections::BTreeSet::new(); + for o in &out { + seen.insert(o.key.clone()); + } + let mut keyed: Vec = Vec::new(); + for b in commands { + let key = key_of(&b); + if !seen.insert(key.clone()) { + continue; + } + keyed.push(Entry { key, group: command_group(&b), label: b.describe(), icon: crate::icons::icon_for(&b), value: false, binding: b }); + } + keyed.sort_by_key(|e| COMMAND_GROUPS.iter().position(|g| *g == e.group).unwrap_or(COMMAND_GROUPS.len())); + out.extend(keyed); + out +} + +/// [`entries`], built once. +pub fn cached() -> &'static [Entry] { + static ALL: std::sync::OnceLock> = std::sync::OnceLock::new(); + ALL.get_or_init(entries) +} + +/// The entry with this key. +pub fn find(key: &str) -> Option { + cached().iter().find(|e| e.key == key).cloned() +} + +/// The entry of a binding, if the catalogue has it. +pub fn of(b: &Binding) -> Option<&'static Entry> { + let key = key_of(b); + cached().iter().find(|e| e.key == key) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn keys_are_unique_stable_and_safe() { + let all = entries(); + assert!(all.len() > 150, "{}", all.len()); + let mut keys: Vec<_> = all.iter().map(|e| e.key.as_str()).collect(); + keys.sort_unstable(); + let n = keys.len(); + keys.dedup(); + assert_eq!(keys.len(), n, "keys are unique"); + for k in &keys { + assert!(!k.contains("___"), "{k}: Logi profiles split on ___"); + assert!(k.chars().all(|c| c.is_ascii_alphanumeric() || ".-".contains(c)), "{k}"); + } + assert_eq!(key_of(&Binding::value("light.exposure")), "v.light.exposure"); + assert_eq!(key_of(&Binding::command_with("photo.rate", json!({"rating": 5}))), "c.photo.rate.rating-5"); + assert_eq!(key_of(&Binding::command_with("library.filter", json!({"label": null}))), "c.library.filter.label-none"); + assert_eq!(find("v.light.exposure").map(|e| e.value), Some(true)); + assert_eq!(find("c.edit.undo").map(|e| e.group), Some("Edit")); + assert_eq!(find("s.applyToSelected").map(|e| e.group), Some("Control Surface")); + assert!(find("nope").is_none()); + } + + #[test] + fn most_actions_have_icons() { + let all = entries(); + let with = all.iter().filter(|e| e.icon.is_some()).count(); + assert!(with * 2 > all.len(), "{with} of {}", all.len()); + // every group of key actions is a known category + for e in all.iter().filter(|e| !e.value) { + assert!(COMMAND_GROUPS.contains(&e.group), "{}", e.group); + } + } +} diff --git a/crates/surface/src/context.rs b/crates/surface/src/context.rs new file mode 100644 index 00000000000..32e6e73f592 --- /dev/null +++ b/crates/surface/src/context.rs @@ -0,0 +1,156 @@ +//! Contexts: what LightCraft shows, as a dotted key the profiles map to pages. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: TactileBridge switched the +//! pad and dial layout with Capture One's active cursor tool and dialogs; here the app reports its +//! state directly. +//! +//! Keys, most specific first (a key falls back to its parents, then `default`): +//! +//! | Key | When | +//! |---|---| +//! | `dialog.` | a dialog is open (`dialog.export`, `dialog.settings`, …) | +//! | `library` | the photo grid (Library) | +//! | `develop`, `develop.
` | Detail view with the Edit panel; the section last opened (`develop.light`, `develop.color`, `develop.detail`, `develop.effects`, `develop.optics`) | +//! | `crop` | Crop & Rotate | +//! | `remove` | Remove (heal / clone) | +//! | `redeye` | Red Eye | +//! | `masking`, `masking.mask`, `masking.mask.brush`, `masking.mask.gradient` | Masking; a mask selected; its brush or gradient tool | + +use serde::Serialize; + +/// The app state a context is made from (the host fills it from its own state). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AppState<'a> { + /// The open dialog, as a lowerCamel name (`export`, `settings`), if any. + pub dialog: Option<&'a str>, + /// The grid is showing (no photo open in Detail). + pub library: bool, + /// The right-hand tool panel: `edit`, `crop`, `remove`, `masking`, `redeye`, … (`None` = none). + pub panel: Option<&'a str>, + /// The Edit panel's focused section (`light`, `color`, …). + pub section: Option<&'a str>, + /// A mask is selected (Masking). + pub mask_selected: bool, + /// The active painting tool: `brush`, `linear`, `radial`. + pub tool: Option<&'a str>, +} + +/// The current context: its key and an English label for the OSD and the editor. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] +pub struct Context { + pub key: String, +} + +impl Context { + pub fn new(key: impl Into) -> Context { + Context { key: key.into() } + } +} + +/// The context key of an app state. +pub fn context_key(s: &AppState) -> String { + if let Some(d) = s.dialog.filter(|d| !d.is_empty()) { + return format!("dialog.{d}"); + } + if s.library { + return "library".into(); + } + match s.panel { + Some("crop") => "crop".into(), + Some("remove") => "remove".into(), + Some("redeye") => "redeye".into(), + Some("masking") => { + let mut k = String::from("masking"); + if s.mask_selected { + k.push_str(".mask"); + match s.tool { + Some("brush") => k.push_str(".brush"), + Some("linear" | "radial") => k.push_str(".gradient"), + _ => {} + } + } + k + } + _ => match s.section.filter(|s| !s.is_empty()) { + Some(sec) => format!("develop.{sec}"), + None => "develop".into(), + }, + } +} + +/// `key`, then each parent, then `default` (`masking.mask.brush` → `masking.mask` → `masking` → +/// `default`). +pub fn fallbacks(key: &str) -> Vec { + let mut out = Vec::new(); + let mut k = key.trim(); + while !k.is_empty() { + out.push(k.to_string()); + match k.rfind('.') { + Some(i) => k = k.get(..i).unwrap_or(""), + None => break, + } + } + if out.last().map(String::as_str) != Some("default") { + out.push("default".into()); + } + out +} + +/// Contexts the editor offers for mapping pages (key, English label), most general first. +pub const KNOWN: &[(&str, &str)] = &[ + ("default", "Anywhere"), + ("library", "Library (grid)"), + ("develop", "Edit"), + ("develop.light", "Edit: Light"), + ("develop.color", "Edit: Color"), + ("develop.effects", "Edit: Effects"), + ("develop.detail", "Edit: Detail"), + ("develop.optics", "Edit: Optics"), + ("develop.geometry", "Edit: Geometry"), + ("crop", "Crop & Rotate"), + ("remove", "Remove"), + ("redeye", "Red Eye"), + ("masking", "Masking"), + ("masking.mask", "Masking: a mask selected"), + ("masking.mask.brush", "Masking: brush"), + ("masking.mask.gradient", "Masking: gradient"), + ("dialog", "Any dialog"), + ("dialog.export", "Export dialog"), + ("dialog.import", "Import dialog"), + ("dialog.settings", "Settings"), +]; + +/// The English label of a context key (the key itself when unknown). +pub fn label(key: &str) -> &str { + KNOWN.iter().find(|(k, _)| *k == key).map_or(key, |(_, l)| l) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys_from_app_state() { + let s = AppState::default(); + assert_eq!(context_key(&s), "develop"); + assert_eq!(context_key(&AppState { library: true, ..s }), "library"); + assert_eq!(context_key(&AppState { dialog: Some("export"), library: true, ..s }), "dialog.export", "a dialog wins"); + assert_eq!(context_key(&AppState { panel: Some("edit"), section: Some("color"), ..s }), "develop.color"); + assert_eq!(context_key(&AppState { panel: Some("crop"), section: Some("color"), ..s }), "crop"); + assert_eq!(context_key(&AppState { panel: Some("masking"), ..s }), "masking"); + assert_eq!(context_key(&AppState { panel: Some("masking"), mask_selected: true, ..s }), "masking.mask"); + assert_eq!(context_key(&AppState { panel: Some("masking"), mask_selected: true, tool: Some("brush"), ..s }), "masking.mask.brush"); + assert_eq!(context_key(&AppState { panel: Some("masking"), mask_selected: true, tool: Some("radial"), ..s }), "masking.mask.gradient"); + assert_eq!(context_key(&AppState { panel: Some("masking"), tool: Some("brush"), ..s }), "masking", "no mask, no tool context"); + } + + #[test] + fn fallback_chain() { + assert_eq!(fallbacks("masking.mask.brush"), ["masking.mask.brush", "masking.mask", "masking", "default"]); + assert_eq!(fallbacks("default"), ["default"]); + assert_eq!(fallbacks(""), ["default"]); + assert_eq!(fallbacks("a..b"), ["a..b", "a.", "a", "default"]); + assert_eq!(label("crop"), "Crop & Rotate"); + assert_eq!(label("x.y"), "x.y"); + } +} diff --git a/crates/surface/src/defaults.rs b/crates/surface/src/defaults.rs new file mode 100644 index 00000000000..2bce992c147 --- /dev/null +++ b/crates/surface/src/defaults.rs @@ -0,0 +1,477 @@ +//! The built-in profiles: TactileBridge's curated layouts (Default, Wedding, Portrait, Fashion, +//! Landscape, Real Estate) for the MX Creative Keypad and Dialpad, with every action mapped to +//! LightCraft, plus the pages that follow LightCraft's tools. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: the profile names, pages and +//! their key and dial layouts are TactileBridge's (`tools/GenerateProfiles.cs`); its tool-context +//! layouts (`TactileBridgeSettings.CreateDefaultToolContexts`) shaped the tool pages. +//! +//! Each TactileBridge profile came in three Logi device variants: `…70` for the Keypad (key +//! pages), `…71` for the Dialpad (four buttons and dial pages) and `…72` for the Actions Ring +//! (a copy of the Keypad's first pages and the Dialpad's dial pages). Here the three are one +//! profile: key pages from `70`, dial pages and buttons from `71` (`72` adds nothing new). +//! One change: the Dialpad's fourth button turns the dial pages (TactileBridge left that to Logi +//! Options+); the action it had is on a key page too. + +use serde_json::json; + +use crate::binding::{Binding, Modifier}; +use crate::devices::PageGroup; +use crate::profile::{Page, Profile}; +use crate::tactilebridge::binding_of; + +/// A key page from TactileBridge action keys (key 1 … key 9). +fn keys(name: &str, tb: [&str; 9]) -> Page { + let mut p = Page { name: name.to_string(), groups: vec![PageGroup::Keys], ..Default::default() }; + for (i, k) in tb.iter().enumerate() { + if let Some(b) = binding_of(k) { + p.bindings.insert(format!("key.{}", i + 1), b); + } + } + p +} + +/// A dial page from TactileBridge dial values in its order: encoder 0 (the roller), then +/// encoder 1 (the big dial) — TactileBridge's Wedding layout keeps Exposure on the roller and +/// Kelvin on the dial. +fn dials(name: &str, roller: &str, dial: &str) -> Page { + let mut p = Page { name: name.to_string(), groups: vec![PageGroup::Dials], ..Default::default() }; + for (slot, k) in [("roller", roller), ("dial", dial)] { + if let Some(b) = binding_of(k) { + p.bindings.insert(slot.to_string(), b); + } + } + p +} + +/// A dial page from LightCraft targets. +fn lc_dials(name: &str, dial: &str, roller: &str) -> Page { + Page::new(name, &[PageGroup::Dials], [("dial", Binding::value(dial)), ("roller", Binding::value(roller))]) +} + +/// The Dialpad's buttons: three TactileBridge actions and the dial-page switch. +fn pads(p: &mut Profile, tb: [&str; 3]) { + for (i, k) in tb.iter().enumerate() { + if let Some(b) = binding_of(k) { + p.base.insert(format!("pad.{}", i + 1), b); + } + } + p.base.insert("pad.4".into(), Binding::PageNext { group: Some(PageGroup::Dials) }); +} + +fn cmd(c: &str) -> Binding { + Binding::command(c) +} +fn cmdp(c: &str, p: serde_json::Value) -> Binding { + Binding::command_with(c, p) +} +fn val(t: &str) -> Binding { + Binding::value(t) +} + +/// Pages that follow LightCraft's tools, shared by every built-in profile, with the contexts they +/// show in. +pub fn tool_pages() -> Vec<(Page, &'static [&'static str])> { + let both: &[PageGroup] = &[]; + vec![ + ( + // TactileBridge's Crop context: crop orientation, zoom, overlays; the dial straightens + Page::new( + "Crop", + both, + [ + ("key.1", cmd("crop.rotateAspect")), + ("key.2", cmd("crop.autoStraighten")), + ("key.3", cmd("crop.reset")), + ("key.4", cmd("view.zoomIn")), + ("key.5", cmd("view.zoomOut")), + ("key.6", cmd("view.zoomFit")), + ("key.7", cmd("view.cropOverlay")), + ("key.8", cmd("view.cropOverlayOrientation")), + ("key.9", cmd("tool.done")), + ("dial", val("crop.angle")), + ("roller", val("ui.zoom")), + ], + ), + &["crop"], + ), + ( + Page::new( + "Masking", + both, + [ + ("key.1", cmdp("tool.brush", json!({"new": true}))), + ("key.2", cmd("tool.linear")), + ("key.3", cmd("tool.radial")), + ("key.4", cmdp("mask.add", json!({"kind": "subject"}))), + ("key.5", cmdp("mask.add", json!({"kind": "sky"}))), + ("key.6", cmdp("mask.add", json!({"kind": "luminanceRange"}))), + ("key.7", cmd("view.maskOverlay")), + ("key.8", cmd("edit.undo")), + ("key.9", cmd("tool.done")), + ("dial", val("ui.zoom")), + ], + ), + &["masking"], + ), + ( + // a selected mask: its sliders on the keys (press one to put it on the dial) + Page::new( + "Mask", + both, + [ + ("key.1", val("mask.exposure")), + ("key.2", val("mask.contrast")), + ("key.3", val("mask.highlights")), + ("key.4", val("mask.shadows")), + ("key.5", val("mask.temp")), + ("key.6", val("mask.saturation")), + ("key.7", cmd("mask.invert")), + ("key.8", cmd("surface.maskPrevious")), + ("key.9", cmd("surface.maskNext")), + ("dial", val("mask.exposure")), + ("roller", val("mask.amount")), + ], + ), + &["masking.mask", "masking.mask.gradient"], + ), + ( + // TactileBridge's Draw Mask context: mask actions on the keys, brush size and feather + // on the dials + Page::new( + "Brush", + both, + [ + ("key.1", cmd("mask.invert")), + ("key.2", cmd("brush.erase")), + ("key.3", cmdp("tool.brush", json!({"new": true}))), + // size and feather on keys too: one hand changes them while the other paints + ("key.4", val("ui.brushSize")), + ("key.5", val("ui.brushFeather")), + ("key.6", cmd("mask.visible")), + ("key.7", val("ui.brushFlow")), + ("key.8", cmd("edit.undo")), + ("key.9", cmd("tool.done")), + ("dial", val("ui.brushSize")), + ("roller", val("ui.brushFeather")), + ], + ), + &["masking.mask.brush"], + ), + ( + // TactileBridge's Draw Healing Mask context + Page::new( + "Remove", + both, + [ + ("key.1", cmd("view.visualizeSpots")), + ("key.2", cmd("view.zoomIn")), + ("key.3", cmd("view.zoomOut")), + ("key.4", cmd("view.zoomFit")), + ("key.5", cmd("view.zoom100")), + ("key.6", cmd("spot.delete")), + ("key.7", cmd("edit.undo")), + ("key.8", cmd("edit.redo")), + ("key.9", cmd("tool.done")), + ("dial", val("ui.removeSize")), + ("roller", val("ui.removeFeather")), + ], + ), + &["remove"], + ), + ( + // TactileBridge's Import / Export / Process dialog contexts + Page::new( + "Dialog", + &[PageGroup::Keys], + [ + ("key.1", cmd("surface.dialogConfirm")), + ("key.3", cmd("surface.dialogCancel")), + ("key.4", cmd("library.selectAll")), + ("key.6", cmd("library.selectNone")), + ], + ), + &["dialog"], + ), + // the Edit panel's sections on the dials (TactileBridge's Direct Color Editor context put + // colour on the dials): ready to map to `develop.
` in Settings > Controls; not + // mapped by default, so the profile's own dial pages stay in charge while editing + (lc_dials("Light", "light.exposure", "light.contrast"), &[]), + (lc_dials("Color", "wb.temp", "wb.tint"), &[]), + (lc_dials("Effects", "effects.clarity", "effects.texture"), &[]), + (lc_dials("Detail", "detail.sharpenAmount", "detail.nrLuminance"), &[]), + (lc_dials("Optics", "optics.distortion", "optics.vignetting"), &[]), + ] +} + +/// The Actions Ring's slots in every built-in profile: undo, redo, pick, reject, previous and +/// next photo, before / after and fit (nothing that deletes or resets). +pub fn ring() -> Vec<(String, Binding)> { + [ + cmd("edit.undo"), + cmd("edit.redo"), + cmd("photo.pick"), + cmd("photo.reject"), + cmd("library.previous"), + cmd("library.next"), + cmd("view.beforeAfter"), + cmd("view.zoomFit"), + ] + .into_iter() + .enumerate() + .map(|(i, b)| (format!("ring.{}", i + 1), b)) + .collect() +} + +fn finish(mut p: Profile) -> Profile { + for (c, b) in ring() { + p.base.entry(c).or_insert(b); + } + let first_keys = p.pages_in(PageGroup::Keys).next().map(|p| p.name.clone()); + let first_dials = p.pages_in(PageGroup::Dials).next().map(|p| p.name.clone()); + p.contexts.insert("default".into(), first_keys.into_iter().chain(first_dials).collect()); + for (page, contexts) in tool_pages() { + for c in contexts { + p.contexts.entry((*c).to_string()).or_default().push(page.name.clone()); + } + // a profile's own page of the same name (Fashion's "Color" dial page) serves instead + if p.page(&page.name).is_none() { + p.pages.push(Page { auto: true, ..page }); + } + } + p.sanitize(); + p +} + +/// The built-in profiles, in TactileBridge's order. +pub fn profiles() -> Vec { + let mut out = Vec::new(); + + let mut d = Profile { name: "Default".into(), description: "Browse, rate and edit: TactileBridge's default layout".into(), ..Default::default() }; + d.pages.push(keys( + "Page 1", + [ + "PreviousImage", + "NextImage", + "ZoomToFit", + "Zoom100", + "ToggleBeforeAfter", + "CopyAdjustments", + "ApplyAdjustments", + "AutoAdjust", + "ResetAdjustments", + ], + )); + d.pages.push(keys( + "Page 2", + ["ClearRating", "Rate1Star", "Rate2Stars", "Rate3Stars", "Rate4Stars", "Rate5Stars", "ColorTagRed", "ColorTagGreen", "ColorTagBlue"], + )); + d.pages.push(keys( + "Page 3", + [ + "SelectTool", + "CropTool", + "SpotRemovalTool", + "WBPickerTool", + "DrawMaskTool", + "EraseMaskTool", + "LinearGradientTool", + "RadialGradientTool", + "LoupeTool", + ], + )); + d.pages.push(dials("Dial Page", "Exposure", "Contrast")); + // TactileBridge's Actions Ring variant turned white balance + d.pages.push(dials("White Balance", "Kelvin", "Tint")); + pads(&mut d, ["CopyAdjustments", "ApplyAdjustments", "Redo"]); + out.push(finish(d)); + + let mut w = Profile { + name: "Wedding".into(), + description: "Fast culling, white balance, exposure, copy and paste, skin retouching".into(), + ..Default::default() + }; + w.pages.push(keys( + "Cull", + ["PreviousImage", "NextImage", "ToggleBeforeAfter", "Rate1Star", "Rate3Stars", "Rate5Stars", "ColorTagGreen", "ColorTagRed", "ColorTagNone"], + )); + w.pages.push(keys( + "Edit", + ["CopyAdjustments", "ApplyAdjustments", "AutoAdjust", "WBPickerTool", "CropTool", "StraightenTool", "Undo", "Redo", "ResetAdjustments"], + )); + w.pages.push(keys( + "Retouch", + ["SpotRemovalTool", "DrawMaskTool", "EraseMaskTool", "NewEmptyLayer", "NewHealLayer", "ToggleLayerOnOff", "ZoomToFit", "Zoom100", "Process"], + )); + w.pages.push(dials("Exposure/WB", "Exposure", "Kelvin")); + w.pages.push(dials("HDR", "Highlight", "Shadow")); + pads(&mut w, ["CopyAdjustments", "ApplyAdjustments", "AutoAdjust"]); + out.push(finish(w)); + + let mut po = Profile { + name: "Portrait".into(), + description: "Skin tones, white balance, gentle adjustments, black and white".into(), + ..Default::default() + }; + po.pages.push(keys( + "Cull", + ["PreviousImage", "NextImage", "ToggleBeforeAfter", "Rate1Star", "Rate3Stars", "Rate5Stars", "ColorTagGreen", "ColorTagRed", "ColorTagNone"], + )); + po.pages.push(keys( + "Tone", + ["CopyAdjustments", "ApplyAdjustments", "AutoAdjust", "WBPickerTool", "CropTool", "RotateRight", "Undo", "Redo", "ResetAdjustments"], + )); + po.pages.push(keys( + "Skin & BW", + [ + "SpotRemovalTool", + "DrawHealTool", + "DirectColorEditor", + "DrawMaskTool", + "EraseMaskTool", + "NewEmptyLayer", + "BWEnable", + "ZoomToFit", + "Process", + ], + )); + po.pages.push(dials("Exposure/WB", "Exposure", "Kelvin")); + po.pages.push(dials("Tone (dials)", "Contrast", "Saturation")); + pads(&mut po, ["CopyAdjustments", "ApplyAdjustments", "AutoAdjust"]); + out.push(finish(po)); + + let mut f = Profile { + name: "Fashion".into(), + description: "Layer-heavy retouching, colour grading, skin tone, creative colour".into(), + ..Default::default() + }; + f.pages.push(keys( + "Cull", + ["PreviousImage", "NextImage", "ToggleBeforeAfter", "Rate1Star", "Rate3Stars", "Rate5Stars", "ColorTagGreen", "ColorTagRed", "ColorTagNone"], + )); + f.pages.push(keys( + "Retouch", + [ + "SpotRemovalTool", + "DrawHealTool", + "DrawCloneTool", + "DrawMaskTool", + "EraseMaskTool", + "NewEmptyLayer", + "NewHealLayer", + "SelectLayerUp", + "SelectLayerDown", + ], + )); + f.pages.push(keys( + "Grade", + ["Undo", "Redo", "ToggleBeforeAfter", "CropTool", "WBPickerTool", "DirectColorEditor", "CopyAdjustments", "ApplyAdjustments", "Process"], + )); + f.pages.push(dials("Exposure", "Exposure", "Contrast")); + f.pages.push(dials("Color", "Saturation", "Kelvin")); + f.pages.push(dials("Detail", "Clarity", "SharpeningAmount")); + pads(&mut f, ["SpotRemovalTool", "DrawMaskTool", "NewEmptyLayer"]); + out.push(finish(f)); + + let mut l = Profile { + name: "Landscape".into(), + description: "Highlight and shadow recovery, clarity and texture, graduated masks, vivid colour".into(), + ..Default::default() + }; + l.pages.push(keys( + "Navigate", + ["PreviousImage", "NextImage", "ZoomToFit", "ToggleBeforeAfter", "Zoom100", "Zoom200", "Rate1Star", "Rate5Stars", "ColorTagGreen"], + )); + l.pages.push(keys( + "Tone", + ["CopyAdjustments", "ApplyAdjustments", "AutoAdjust", "WBPickerTool", "CropTool", "StraightenTool", "Undo", "Redo", "ResetAdjustments"], + )); + l.pages.push(keys( + "Layers", + [ + "LinearGradientTool", + "RadialGradientTool", + "DrawMaskTool", + "EraseMaskTool", + "NewEmptyLayer", + "ToggleLayerOnOff", + "SelectLayerUp", + "SelectLayerDown", + "Process", + ], + )); + l.pages.push(dials("Exposure/WB", "Exposure", "Kelvin")); + l.pages.push(dials("HDR", "Highlight", "Shadow")); + l.pages.push(dials("Detail", "Clarity", "Structure")); + pads(&mut l, ["CopyAdjustments", "ApplyAdjustments", "AutoAdjust"]); + out.push(finish(l)); + + let mut r = Profile { + name: "Real Estate".into(), + description: "Perspective correction, white balance, highlights and shadows, batch work".into(), + ..Default::default() + }; + r.pages.push(keys( + "Navigate", + ["PreviousImage", "NextImage", "ZoomToFit", "ToggleBeforeAfter", "Rate1Star", "Rate5Stars", "ColorTagGreen", "ColorTagRed", "ColorTagNone"], + )); + r.pages.push(keys( + "Correct", + [ + "CropTool", + "StraightenTool", + "KeystoneTool", + "KeystoneVertical", + "KeystoneHorizontal", + "WBPickerTool", + "AutoAdjust", + "RotateLeft", + "RotateRight", + ], + )); + r.pages.push(keys( + "Process", + ["CopyAdjustments", "ApplyAdjustments", "ResetAdjustments", "SelectAll", "EditAllSelected", "Process", "Undo", "Redo", "ToggleExposureWarn"], + )); + r.pages.push(dials("Exposure/WB", "Exposure", "Kelvin")); + r.pages.push(dials("HDR", "Highlight", "Shadow")); + pads(&mut r, ["CopyAdjustments", "ApplyAdjustments", "AutoAdjust"]); + out.push(finish(r)); + + out +} + +/// A fine-steps modifier on a key, for profiles the user builds (offered by the editor). +pub fn fine_modifier() -> Binding { + Binding::Modifier { modifier: Modifier::Fine } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn six_profiles_every_key_page_full_every_binding_known() { + let ps = profiles(); + let names: Vec<_> = ps.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Default", "Wedding", "Portrait", "Fashion", "Landscape", "Real Estate"]); + for p in &ps { + for page in p.pages.iter().filter(|pg| pg.groups == [PageGroup::Keys] && !pg.auto) { + assert_eq!(page.bindings.len(), 9, "{} / {}: every TactileBridge key is mapped", p.name, page.name); + } + for b in p.pages.iter().flat_map(|pg| pg.bindings.values()).chain(p.base.values()) { + if let Binding::Value { target } = b { + assert!(crate::targets::target_spec(target).is_some(), "{} → {target}", p.name); + } + } + assert_eq!(p.base.len(), 12, "{}: four Dialpad buttons, eight Actions Ring slots", p.name); + assert!(p.contexts.contains_key("default") && p.contexts.contains_key("crop") && p.contexts.contains_key("masking.mask.brush")); + let mut clone = p.clone(); + clone.sanitize(); + assert_eq!(&clone, p, "built-ins are already clean"); + } + // Real Estate's Keystone keys became Upright + let re = &ps[5]; + assert_eq!(re.page("Correct").unwrap().bindings["key.3"], Binding::command("tool.guidedUpright")); + } +} diff --git a/crates/surface/src/devices.rs b/crates/surface/src/devices.rs new file mode 100644 index 00000000000..4c22fb8fc5d --- /dev/null +++ b/crates/surface/src/devices.rs @@ -0,0 +1,174 @@ +//! The controls of each supported device. +//! +//! A control is addressed by a stable string id (`key.1`, `dial`, …) in profiles, in the surface +//! protocol and in the editor. Unknown ids are accepted everywhere (a MIDI or Tangent device adds +//! its own); [`find_control`] only knows the built-in devices. + +use serde::{Deserialize, Serialize}; + +/// What kind of physical control it is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ControlKind { + /// An endless rotary encoder (dial, roller, knob). + Encoder, + /// A plain button. + Button, + /// A button with its own display (an LCD key): it shows an icon, a label and a value. + Key, +} + +/// Which page cursor resolves a control: keys follow the key page, dials (and the buttons around +/// them) the dial page, so the two can be paged separately, as the MX Creative Keypad and Dialpad +/// are. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PageGroup { + #[default] + Keys, + Dials, +} + +impl PageGroup { + pub const ALL: [PageGroup; 2] = [PageGroup::Keys, PageGroup::Dials]; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ControlDef { + pub id: &'static str, + pub kind: ControlKind, + /// English label (the editor translates it). + pub label: &'static str, + pub group: PageGroup, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DeviceDef { + /// Stable id used in the protocol (`surface.subscribe {device}`). + pub id: &'static str, + pub name: &'static str, + pub controls: &'static [ControlDef], +} + +const fn key(id: &'static str, label: &'static str) -> ControlDef { + ControlDef { id, kind: ControlKind::Key, label, group: PageGroup::Keys } +} +const fn pad(id: &'static str, label: &'static str) -> ControlDef { + ControlDef { id, kind: ControlKind::Button, label, group: PageGroup::Dials } +} +/// A slot of the Actions Ring (the on-screen ring of Logi Options+): pressed like a key. +const fn ring(id: &'static str, label: &'static str) -> ControlDef { + ControlDef { id, kind: ControlKind::Button, label, group: PageGroup::Keys } +} +const fn enc(id: &'static str, label: &'static str) -> ControlDef { + ControlDef { id, kind: ControlKind::Encoder, label, group: PageGroup::Dials } +} + +/// Logitech MX Creative Console: the Keypad (3 × 3 LCD keys; Logi device type `Loupedeck70`) and +/// the Dialpad (a dial, a roller and four buttons; `Loupedeck71`), and the on-screen Actions Ring +/// (eight slots, `ring.1`–`ring.8`; `Loupedeck72`), set on All pages (the ring has no pages). +pub static MX_CREATIVE_CONSOLE: DeviceDef = DeviceDef { + id: "mx-creative-console", + name: "Logitech MX Creative Console", + controls: &[ + key("key.1", "Key 1"), + key("key.2", "Key 2"), + key("key.3", "Key 3"), + key("key.4", "Key 4"), + key("key.5", "Key 5"), + key("key.6", "Key 6"), + key("key.7", "Key 7"), + key("key.8", "Key 8"), + key("key.9", "Key 9"), + enc("dial", "Dial"), + enc("roller", "Roller"), + pad("pad.1", "Dialpad button 1"), + pad("pad.2", "Dialpad button 2"), + pad("pad.3", "Dialpad button 3"), + pad("pad.4", "Dialpad button 4"), + ring("ring.1", "Ring slot 1"), + ring("ring.2", "Ring slot 2"), + ring("ring.3", "Ring slot 3"), + ring("ring.4", "Ring slot 4"), + ring("ring.5", "Ring slot 5"), + ring("ring.6", "Ring slot 6"), + ring("ring.7", "Ring slot 7"), + ring("ring.8", "Ring slot 8"), + ], +}; + +/// Loupedeck+: knobs, the Control Dial and buttons, without displays (`Loupedeck15`). Its controls +/// are Loupedeck's own numbers ([`crate::loupedeck`]). +pub static LOUPEDECK_PLUS: DeviceDef = DeviceDef { id: "loupedeck-plus", name: "Loupedeck+", controls: crate::loupedeck::CONTROLS }; + +/// Every built-in device. +pub fn devices() -> &'static [&'static DeviceDef] { + static ALL: [&DeviceDef; 2] = [&MX_CREATIVE_CONSOLE, &LOUPEDECK_PLUS]; + &ALL +} + +pub fn find_device(id: &str) -> Option<&'static DeviceDef> { + devices().iter().copied().find(|d| d.id == id) +} + +/// A built-in control by id. +pub fn find_control(id: &str) -> Option<&'static ControlDef> { + devices().iter().flat_map(|d| d.controls.iter()).find(|c| c.id == id) +} + +/// The page group of a control; unknown controls page with the keys unless they turn. +pub fn group_of(id: &str) -> PageGroup { + match find_control(id) { + Some(c) => c.group, + None if id.starts_with("dial") || id.starts_with("roller") || id.starts_with("enc") || id.starts_with("knob") => PageGroup::Dials, + None => PageGroup::Keys, + } +} + +/// Does the control turn (an encoder)? +pub fn is_encoder(id: &str) -> bool { + match find_control(id) { + Some(c) => c.kind == ControlKind::Encoder, + None => group_of(id) == PageGroup::Dials && !id.starts_with("pad"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn console_has_nine_keys_a_dial_a_roller_and_four_pads() { + let d = find_device("mx-creative-console").unwrap(); + assert_eq!(d.controls.iter().filter(|c| c.kind == ControlKind::Key).count(), 9); + assert_eq!(d.controls.iter().filter(|c| c.kind == ControlKind::Encoder).count(), 2); + assert_eq!(d.controls.iter().filter(|c| c.kind == ControlKind::Button).count(), 12, "four Dialpad buttons, eight ring slots"); + assert_eq!(d.controls.iter().filter(|c| c.id.starts_with("ring.")).count(), 8); + let mut ids: Vec<_> = d.controls.iter().map(|c| c.id).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), d.controls.len(), "control ids are unique"); + } + + #[test] + fn loupedeck_plus_knobs_turn_and_its_buttons_press() { + let d = find_device("loupedeck-plus").unwrap(); + assert!(is_encoder("ld.r33") && is_encoder("ld.r48") && !is_encoder("ld.b95")); + assert_eq!(group_of("ld.b95"), PageGroup::Dials); + let mut ids: Vec<_> = d.controls.iter().map(|c| c.id).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), d.controls.len(), "control ids are unique"); + } + + #[test] + fn groups_and_encoders() { + assert_eq!(group_of("key.4"), PageGroup::Keys); + assert_eq!(group_of("dial"), PageGroup::Dials); + assert_eq!(group_of("pad.2"), PageGroup::Dials); + assert_eq!(group_of("knob.7"), PageGroup::Dials); + assert_eq!(group_of("midi.note.36"), PageGroup::Keys); + assert!(is_encoder("dial") && is_encoder("roller") && is_encoder("knob.3")); + assert!(!is_encoder("key.1") && !is_encoder("pad.1")); + } +} diff --git a/crates/surface/src/icon_table.rs b/crates/surface/src/icon_table.rs new file mode 100644 index 00000000000..acb955384c6 --- /dev/null +++ b/crates/surface/src/icon_table.rs @@ -0,0 +1,354 @@ +// Generated from assets/surface-icons (the TactileBridge icon pack). Keep sorted by name. +// Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT. + +/// (name, SVG) of every icon, sorted by name. +pub(crate) static ICONS: &[(&str, &str)] = &[ + ("add-color-readout", include_str!("../../../assets/surface-icons/add-color-readout.svg")), + ("aperture-down", include_str!("../../../assets/surface-icons/aperture-down.svg")), + ("aperture-up", include_str!("../../../assets/surface-icons/aperture-up.svg")), + ("apply-adjustments", include_str!("../../../assets/surface-icons/apply-adjustments.svg")), + ("apply-normalization", include_str!("../../../assets/surface-icons/apply-normalization.svg")), + ("auto-adjust", include_str!("../../../assets/surface-icons/auto-adjust.svg")), + ("auto-focus", include_str!("../../../assets/surface-icons/auto-focus.svg")), + ("auto-focus-fine", include_str!("../../../assets/surface-icons/auto-focus-fine.svg")), + ("auto-sync", include_str!("../../../assets/surface-icons/auto-sync.svg")), + ("black", include_str!("../../../assets/surface-icons/black.svg")), + ("blur-brush", include_str!("../../../assets/surface-icons/blur-brush.svg")), + ("brightness", include_str!("../../../assets/surface-icons/brightness.svg")), + ("brush-erase", include_str!("../../../assets/surface-icons/brush-erase.svg")), + ("brush-flow", include_str!("../../../assets/surface-icons/brush-flow.svg")), + ("brush-hardness", include_str!("../../../assets/surface-icons/brush-hardness.svg")), + ("brush-new", include_str!("../../../assets/surface-icons/brush-new.svg")), + ("brush-opacity", include_str!("../../../assets/surface-icons/brush-opacity.svg")), + ("brush-size", include_str!("../../../assets/surface-icons/brush-size.svg")), + ("burn", include_str!("../../../assets/surface-icons/burn.svg")), + ("bw-blue", include_str!("../../../assets/surface-icons/bw-blue.svg")), + ("bw-cyan", include_str!("../../../assets/surface-icons/bw-cyan.svg")), + ("bw-enable", include_str!("../../../assets/surface-icons/bw-enable.svg")), + ("bw-green", include_str!("../../../assets/surface-icons/bw-green.svg")), + ("bw-highlights-hue", include_str!("../../../assets/surface-icons/bw-highlights-hue.svg")), + ("bw-highlights-sat", include_str!("../../../assets/surface-icons/bw-highlights-sat.svg")), + ("bw-magenta", include_str!("../../../assets/surface-icons/bw-magenta.svg")), + ("bw-orange", include_str!("../../../assets/surface-icons/bw-orange.svg")), + ("bw-red", include_str!("../../../assets/surface-icons/bw-red.svg")), + ("bw-shadows-hue", include_str!("../../../assets/surface-icons/bw-shadows-hue.svg")), + ("bw-shadows-sat", include_str!("../../../assets/surface-icons/bw-shadows-sat.svg")), + ("bw-yellow", include_str!("../../../assets/surface-icons/bw-yellow.svg")), + ("capture", include_str!("../../../assets/surface-icons/capture.svg")), + ("ce-blue-hue", include_str!("../../../assets/surface-icons/ce-blue-hue.svg")), + ("ce-blue-light", include_str!("../../../assets/surface-icons/ce-blue-light.svg")), + ("ce-blue-sat", include_str!("../../../assets/surface-icons/ce-blue-sat.svg")), + ("ce-cyan-hue", include_str!("../../../assets/surface-icons/ce-cyan-hue.svg")), + ("ce-cyan-light", include_str!("../../../assets/surface-icons/ce-cyan-light.svg")), + ("ce-cyan-sat", include_str!("../../../assets/surface-icons/ce-cyan-sat.svg")), + ("ce-green-hue", include_str!("../../../assets/surface-icons/ce-green-hue.svg")), + ("ce-green-light", include_str!("../../../assets/surface-icons/ce-green-light.svg")), + ("ce-green-sat", include_str!("../../../assets/surface-icons/ce-green-sat.svg")), + ("ce-magenta-hue", include_str!("../../../assets/surface-icons/ce-magenta-hue.svg")), + ("ce-magenta-light", include_str!("../../../assets/surface-icons/ce-magenta-light.svg")), + ("ce-magenta-sat", include_str!("../../../assets/surface-icons/ce-magenta-sat.svg")), + ("ce-orange-hue", include_str!("../../../assets/surface-icons/ce-orange-hue.svg")), + ("ce-orange-light", include_str!("../../../assets/surface-icons/ce-orange-light.svg")), + ("ce-orange-sat", include_str!("../../../assets/surface-icons/ce-orange-sat.svg")), + ("ce-purple-hue", include_str!("../../../assets/surface-icons/ce-purple-hue.svg")), + ("ce-purple-light", include_str!("../../../assets/surface-icons/ce-purple-light.svg")), + ("ce-purple-sat", include_str!("../../../assets/surface-icons/ce-purple-sat.svg")), + ("ce-red-hue", include_str!("../../../assets/surface-icons/ce-red-hue.svg")), + ("ce-red-light", include_str!("../../../assets/surface-icons/ce-red-light.svg")), + ("ce-red-sat", include_str!("../../../assets/surface-icons/ce-red-sat.svg")), + ("ce-yellow-hue", include_str!("../../../assets/surface-icons/ce-yellow-hue.svg")), + ("ce-yellow-light", include_str!("../../../assets/surface-icons/ce-yellow-light.svg")), + ("ce-yellow-sat", include_str!("../../../assets/surface-icons/ce-yellow-sat.svg")), + ("clarity", include_str!("../../../assets/surface-icons/clarity.svg")), + ("clear-compare-variant", include_str!("../../../assets/surface-icons/clear-compare-variant.svg")), + ("clear-mask", include_str!("../../../assets/surface-icons/clear-mask.svg")), + ("clear-rating", include_str!("../../../assets/surface-icons/clear-rating.svg")), + ("clone-brush", include_str!("../../../assets/surface-icons/clone-brush.svg")), + ("clone-variant", include_str!("../../../assets/surface-icons/clone-variant.svg")), + ("color-burn", include_str!("../../../assets/surface-icons/color-burn.svg")), + ("color-dodge", include_str!("../../../assets/surface-icons/color-dodge.svg")), + ("color-picker-tool", include_str!("../../../assets/surface-icons/color-picker-tool.svg")), + ("color-tag-blue", include_str!("../../../assets/surface-icons/color-tag-blue.svg")), + ("color-tag-green", include_str!("../../../assets/surface-icons/color-tag-green.svg")), + ("color-tag-none", include_str!("../../../assets/surface-icons/color-tag-none.svg")), + ("color-tag-orange", include_str!("../../../assets/surface-icons/color-tag-orange.svg")), + ("color-tag-pink", include_str!("../../../assets/surface-icons/color-tag-pink.svg")), + ("color-tag-purple", include_str!("../../../assets/surface-icons/color-tag-purple.svg")), + ("color-tag-red", include_str!("../../../assets/surface-icons/color-tag-red.svg")), + ("color-tag-yellow", include_str!("../../../assets/surface-icons/color-tag-yellow.svg")), + ("composition-mode", include_str!("../../../assets/surface-icons/composition-mode.svg")), + ("contrast", include_str!("../../../assets/surface-icons/contrast.svg")), + ("contrast-brush", include_str!("../../../assets/surface-icons/contrast-brush.svg")), + ("copy-adjustments", include_str!("../../../assets/surface-icons/copy-adjustments.svg")), + ("copy-and-apply-adj", include_str!("../../../assets/surface-icons/copy-and-apply-adj.svg")), + ("crop-tool", include_str!("../../../assets/surface-icons/crop-tool.svg")), + ("darken", include_str!("../../../assets/surface-icons/darken.svg")), + ("decrease-zoom", include_str!("../../../assets/surface-icons/decrease-zoom.svg")), + ("defringe", include_str!("../../../assets/surface-icons/defringe.svg")), + ("delete", include_str!("../../../assets/surface-icons/delete.svg")), + ("delete-color-readout", include_str!("../../../assets/surface-icons/delete-color-readout.svg")), + ("demote-variant", include_str!("../../../assets/surface-icons/demote-variant.svg")), + ("desaturate-brush", include_str!("../../../assets/surface-icons/desaturate-brush.svg")), + ("deselect-all", include_str!("../../../assets/surface-icons/deselect-all.svg")), + ("deselect-primary", include_str!("../../../assets/surface-icons/deselect-primary.svg")), + ("direct-color-editor", include_str!("../../../assets/surface-icons/direct-color-editor.svg")), + ("distortion", include_str!("../../../assets/surface-icons/distortion.svg")), + ("dodge", include_str!("../../../assets/surface-icons/dodge.svg")), + ("draw-clone-tool", include_str!("../../../assets/surface-icons/draw-clone-tool.svg")), + ("draw-heal-tool", include_str!("../../../assets/surface-icons/draw-heal-tool.svg")), + ("draw-mask-tool", include_str!("../../../assets/surface-icons/draw-mask-tool.svg")), + ("edit-all-selected", include_str!("../../../assets/surface-icons/edit-all-selected.svg")), + ("erase-mask-tool", include_str!("../../../assets/surface-icons/erase-mask-tool.svg")), + ("export-originals", include_str!("../../../assets/surface-icons/export-originals.svg")), + ("export-variants", include_str!("../../../assets/surface-icons/export-variants.svg")), + ("exposure", include_str!("../../../assets/surface-icons/exposure.svg")), + ("exposure-bias-down", include_str!("../../../assets/surface-icons/exposure-bias-down.svg")), + ("exposure-bias-up", include_str!("../../../assets/surface-icons/exposure-bias-up.svg")), + ("exposure-brush", include_str!("../../../assets/surface-icons/exposure-brush.svg")), + ("exposure-meter", include_str!("../../../assets/surface-icons/exposure-meter.svg")), + ("feather-mask", include_str!("../../../assets/surface-icons/feather-mask.svg")), + ("fill-mask", include_str!("../../../assets/surface-icons/fill-mask.svg")), + ("filter-1-star", include_str!("../../../assets/surface-icons/filter-1-star.svg")), + ("filter-2-stars", include_str!("../../../assets/surface-icons/filter-2-stars.svg")), + ("filter-3-stars", include_str!("../../../assets/surface-icons/filter-3-stars.svg")), + ("filter-4-stars", include_str!("../../../assets/surface-icons/filter-4-stars.svg")), + ("filter-5-stars", include_str!("../../../assets/surface-icons/filter-5-stars.svg")), + ("filter-approved", include_str!("../../../assets/surface-icons/filter-approved.svg")), + ("filter-color-tag", include_str!("../../../assets/surface-icons/filter-color-tag.svg")), + ("filter-flag", include_str!("../../../assets/surface-icons/filter-flag.svg")), + ("filter-green", include_str!("../../../assets/surface-icons/filter-green.svg")), + ("filter-no-flag", include_str!("../../../assets/surface-icons/filter-no-flag.svg")), + ("filter-purple", include_str!("../../../assets/surface-icons/filter-purple.svg")), + ("filter-rating-1-star", include_str!("../../../assets/surface-icons/filter-rating-1-star.svg")), + ("filter-rating-2-stars", include_str!("../../../assets/surface-icons/filter-rating-2-stars.svg")), + ("filter-rating-3-stars", include_str!("../../../assets/surface-icons/filter-rating-3-stars.svg")), + ("filter-rating-4-stars", include_str!("../../../assets/surface-icons/filter-rating-4-stars.svg")), + ("filter-rating-5-stars", include_str!("../../../assets/surface-icons/filter-rating-5-stars.svg")), + ("filter-rating-none", include_str!("../../../assets/surface-icons/filter-rating-none.svg")), + ("filter-red", include_str!("../../../assets/surface-icons/filter-red.svg")), + ("filter-rejected", include_str!("../../../assets/surface-icons/filter-rejected.svg")), + ("filter-tag-blue", include_str!("../../../assets/surface-icons/filter-tag-blue.svg")), + ("filter-tag-green", include_str!("../../../assets/surface-icons/filter-tag-green.svg")), + ("filter-tag-none", include_str!("../../../assets/surface-icons/filter-tag-none.svg")), + ("filter-tag-orange", include_str!("../../../assets/surface-icons/filter-tag-orange.svg")), + ("filter-tag-pink", include_str!("../../../assets/surface-icons/filter-tag-pink.svg")), + ("filter-tag-purple", include_str!("../../../assets/surface-icons/filter-tag-purple.svg")), + ("filter-tag-red", include_str!("../../../assets/surface-icons/filter-tag-red.svg")), + ("filter-tag-yellow", include_str!("../../../assets/surface-icons/filter-tag-yellow.svg")), + ("filter-yellow", include_str!("../../../assets/surface-icons/filter-yellow.svg")), + ("first-image", include_str!("../../../assets/surface-icons/first-image.svg")), + ("focus-assist", include_str!("../../../assets/surface-icons/focus-assist.svg")), + ("focus-meter-tool", include_str!("../../../assets/surface-icons/focus-meter-tool.svg")), + ("focus-point-tool", include_str!("../../../assets/surface-icons/focus-point-tool.svg")), + ("full-screen", include_str!("../../../assets/surface-icons/full-screen.svg")), + ("grain-granularity", include_str!("../../../assets/surface-icons/grain-granularity.svg")), + ("grain-impact", include_str!("../../../assets/surface-icons/grain-impact.svg")), + ("hard-light", include_str!("../../../assets/surface-icons/hard-light.svg")), + ("heal-brush", include_str!("../../../assets/surface-icons/heal-brush.svg")), + ("highlight", include_str!("../../../assets/surface-icons/highlight.svg")), + ("highlight-brush", include_str!("../../../assets/surface-icons/highlight-brush.svg")), + ("highlight-lightness", include_str!("../../../assets/surface-icons/highlight-lightness.svg")), + ("highlight-tone-x", include_str!("../../../assets/surface-icons/highlight-tone-x.svg")), + ("highlight-tone-y", include_str!("../../../assets/surface-icons/highlight-tone-y.svg")), + ("histogram-view", include_str!("../../../assets/surface-icons/histogram-view.svg")), + ("import-images", include_str!("../../../assets/surface-icons/import-images.svg")), + ("increase-zoom", include_str!("../../../assets/surface-icons/increase-zoom.svg")), + ("invert-mask", include_str!("../../../assets/surface-icons/invert-mask.svg")), + ("invert-selection", include_str!("../../../assets/surface-icons/invert-selection.svg")), + ("iso-down", include_str!("../../../assets/surface-icons/iso-down.svg")), + ("iso-up", include_str!("../../../assets/surface-icons/iso-up.svg")), + ("kelvin", include_str!("../../../assets/surface-icons/kelvin.svg")), + ("keystone-horizontal", include_str!("../../../assets/surface-icons/keystone-horizontal.svg")), + ("keystone-tool", include_str!("../../../assets/surface-icons/keystone-tool.svg")), + ("keystone-vertical", include_str!("../../../assets/surface-icons/keystone-vertical.svg")), + ("last-image", include_str!("../../../assets/surface-icons/last-image.svg")), + ("layer-opacity", include_str!("../../../assets/surface-icons/layer-opacity.svg")), + ("light-falloff", include_str!("../../../assets/surface-icons/light-falloff.svg")), + ("lighten", include_str!("../../../assets/surface-icons/lighten.svg")), + ("linear-gradient-tool", include_str!("../../../assets/surface-icons/linear-gradient-tool.svg")), + ("live-view", include_str!("../../../assets/surface-icons/live-view.svg")), + ("loupe-tool", include_str!("../../../assets/surface-icons/loupe-tool.svg")), + ("luma-range", include_str!("../../../assets/surface-icons/luma-range.svg")), + ("mask-invert", include_str!("../../../assets/surface-icons/mask-invert.svg")), + ("mask-next", include_str!("../../../assets/surface-icons/mask-next.svg")), + ("mask-previous", include_str!("../../../assets/surface-icons/mask-previous.svg")), + ("mask-visible", include_str!("../../../assets/surface-icons/mask-visible.svg")), + ("master-tone-x", include_str!("../../../assets/surface-icons/master-tone-x.svg")), + ("master-tone-y", include_str!("../../../assets/surface-icons/master-tone-y.svg")), + ("midtone-lightness", include_str!("../../../assets/surface-icons/midtone-lightness.svg")), + ("midtone-tone-x", include_str!("../../../assets/surface-icons/midtone-tone-x.svg")), + ("midtone-tone-y", include_str!("../../../assets/surface-icons/midtone-tone-y.svg")), + ("moire-amount", include_str!("../../../assets/surface-icons/moire-amount.svg")), + ("moire-pattern", include_str!("../../../assets/surface-icons/moire-pattern.svg")), + ("move-to-trash", include_str!("../../../assets/surface-icons/move-to-trash.svg")), + ("move-tool", include_str!("../../../assets/surface-icons/move-tool.svg")), + ("multiply", include_str!("../../../assets/surface-icons/multiply.svg")), + ("new-clone-layer", include_str!("../../../assets/surface-icons/new-clone-layer.svg")), + ("new-empty-layer", include_str!("../../../assets/surface-icons/new-empty-layer.svg")), + ("new-filled-layer", include_str!("../../../assets/surface-icons/new-filled-layer.svg")), + ("new-heal-layer", include_str!("../../../assets/surface-icons/new-heal-layer.svg")), + ("new-variant", include_str!("../../../assets/surface-icons/new-variant.svg")), + ("next-collection", include_str!("../../../assets/surface-icons/next-collection.svg")), + ("next-group", include_str!("../../../assets/surface-icons/next-group.svg")), + ("next-image", include_str!("../../../assets/surface-icons/next-image.svg")), + ("next-image-import", include_str!("../../../assets/surface-icons/next-image-import.svg")), + ("next-set", include_str!("../../../assets/surface-icons/next-set.svg")), + ("nr-color", include_str!("../../../assets/surface-icons/nr-color.svg")), + ("nr-detail", include_str!("../../../assets/surface-icons/nr-detail.svg")), + ("nr-luminance", include_str!("../../../assets/surface-icons/nr-luminance.svg")), + ("nr-single-pixel", include_str!("../../../assets/surface-icons/nr-single-pixel.svg")), + ("overlay", include_str!("../../../assets/surface-icons/overlay.svg")), + ("overlay-horizontal", include_str!("../../../assets/surface-icons/overlay-horizontal.svg")), + ("overlay-opacity", include_str!("../../../assets/surface-icons/overlay-opacity.svg")), + ("overlay-scale", include_str!("../../../assets/surface-icons/overlay-scale.svg")), + ("overlay-tool", include_str!("../../../assets/surface-icons/overlay-tool.svg")), + ("overlay-vertical", include_str!("../../../assets/surface-icons/overlay-vertical.svg")), + ("pan-tool", include_str!("../../../assets/surface-icons/pan-tool.svg")), + ("pen-black", include_str!("../../../assets/surface-icons/pen-black.svg")), + ("pen-blue", include_str!("../../../assets/surface-icons/pen-blue.svg")), + ("pen-green", include_str!("../../../assets/surface-icons/pen-green.svg")), + ("pen-red", include_str!("../../../assets/surface-icons/pen-red.svg")), + ("pen-size", include_str!("../../../assets/surface-icons/pen-size.svg")), + ("pen-white", include_str!("../../../assets/surface-icons/pen-white.svg")), + ("pen-yellow", include_str!("../../../assets/surface-icons/pen-yellow.svg")), + ("pick-color-correction", include_str!("../../../assets/surface-icons/pick-color-correction.svg")), + ("pick-curve-point", include_str!("../../../assets/surface-icons/pick-curve-point.svg")), + ("pick-focus-point", include_str!("../../../assets/surface-icons/pick-focus-point.svg")), + ("pick-highlight-level", include_str!("../../../assets/surface-icons/pick-highlight-level.svg")), + ("pick-luma-curve", include_str!("../../../assets/surface-icons/pick-luma-curve.svg")), + ("pick-norm-target", include_str!("../../../assets/surface-icons/pick-norm-target.svg")), + ("pick-shadow-level", include_str!("../../../assets/surface-icons/pick-shadow-level.svg")), + ("pick-skin-color", include_str!("../../../assets/surface-icons/pick-skin-color.svg")), + ("pick-variant", include_str!("../../../assets/surface-icons/pick-variant.svg")), + ("previous-collection", include_str!("../../../assets/surface-icons/previous-collection.svg")), + ("previous-group", include_str!("../../../assets/surface-icons/previous-group.svg")), + ("previous-image", include_str!("../../../assets/surface-icons/previous-image.svg")), + ("previous-image-import", include_str!("../../../assets/surface-icons/previous-image-import.svg")), + ("previous-set", include_str!("../../../assets/surface-icons/previous-set.svg")), + ("print", include_str!("../../../assets/surface-icons/print.svg")), + ("process", include_str!("../../../assets/surface-icons/process.svg")), + ("promote-variant", include_str!("../../../assets/surface-icons/promote-variant.svg")), + ("radial-gradient-tool", include_str!("../../../assets/surface-icons/radial-gradient-tool.svg")), + ("rasterize-mask", include_str!("../../../assets/surface-icons/rasterize-mask.svg")), + ("rate-1-star", include_str!("../../../assets/surface-icons/rate-1-star.svg")), + ("rate-2-star", include_str!("../../../assets/surface-icons/rate-2-star.svg")), + ("rate-2-stars", include_str!("../../../assets/surface-icons/rate-2-stars.svg")), + ("rate-3-star", include_str!("../../../assets/surface-icons/rate-3-star.svg")), + ("rate-3-stars", include_str!("../../../assets/surface-icons/rate-3-stars.svg")), + ("rate-4-star", include_str!("../../../assets/surface-icons/rate-4-star.svg")), + ("rate-4-stars", include_str!("../../../assets/surface-icons/rate-4-stars.svg")), + ("rate-5-star", include_str!("../../../assets/surface-icons/rate-5-star.svg")), + ("rate-5-stars", include_str!("../../../assets/surface-icons/rate-5-stars.svg")), + ("recipe-proofing", include_str!("../../../assets/surface-icons/recipe-proofing.svg")), + ("redo", include_str!("../../../assets/surface-icons/redo.svg")), + ("refine-mask", include_str!("../../../assets/surface-icons/refine-mask.svg")), + ("regenerate-previews", include_str!("../../../assets/surface-icons/regenerate-previews.svg")), + ("remove-layer", include_str!("../../../assets/surface-icons/remove-layer.svg")), + ("rename", include_str!("../../../assets/surface-icons/rename.svg")), + ("reset-adjustments", include_str!("../../../assets/surface-icons/reset-adjustments.svg")), + ("reset-develop", include_str!("../../../assets/surface-icons/reset-develop.svg")), + ("rotate-freehand-tool", include_str!("../../../assets/surface-icons/rotate-freehand-tool.svg")), + ("rotate-left", include_str!("../../../assets/surface-icons/rotate-left.svg")), + ("rotate-photo-left", include_str!("../../../assets/surface-icons/rotate-photo-left.svg")), + ("rotate-photo-right", include_str!("../../../assets/surface-icons/rotate-photo-right.svg")), + ("rotate-right", include_str!("../../../assets/surface-icons/rotate-right.svg")), + ("rotation-tool", include_str!("../../../assets/surface-icons/rotation-tool.svg")), + ("saturation", include_str!("../../../assets/surface-icons/saturation.svg")), + ("saturation-brush", include_str!("../../../assets/surface-icons/saturation-brush.svg")), + ("select-1-star", include_str!("../../../assets/surface-icons/select-1-star.svg")), + ("select-2-stars", include_str!("../../../assets/surface-icons/select-2-stars.svg")), + ("select-3-stars", include_str!("../../../assets/surface-icons/select-3-stars.svg")), + ("select-4-stars", include_str!("../../../assets/surface-icons/select-4-stars.svg")), + ("select-5-stars", include_str!("../../../assets/surface-icons/select-5-stars.svg")), + ("select-all", include_str!("../../../assets/surface-icons/select-all.svg")), + ("select-all-photos", include_str!("../../../assets/surface-icons/select-all-photos.svg")), + ("select-background", include_str!("../../../assets/surface-icons/select-background.svg")), + ("select-brush", include_str!("../../../assets/surface-icons/select-brush.svg")), + ("select-by-color", include_str!("../../../assets/surface-icons/select-by-color.svg")), + ("select-by-shape", include_str!("../../../assets/surface-icons/select-by-shape.svg")), + ("select-by-tone", include_str!("../../../assets/surface-icons/select-by-tone.svg")), + ("select-eraser", include_str!("../../../assets/surface-icons/select-eraser.svg")), + ("select-freehand", include_str!("../../../assets/surface-icons/select-freehand.svg")), + ("select-layer-down", include_str!("../../../assets/surface-icons/select-layer-down.svg")), + ("select-layer-up", include_str!("../../../assets/surface-icons/select-layer-up.svg")), + ("select-magic-wand", include_str!("../../../assets/surface-icons/select-magic-wand.svg")), + ("select-no-photos", include_str!("../../../assets/surface-icons/select-no-photos.svg")), + ("select-pen", include_str!("../../../assets/surface-icons/select-pen.svg")), + ("select-primary-only", include_str!("../../../assets/surface-icons/select-primary-only.svg")), + ("select-same-color-tag", include_str!("../../../assets/surface-icons/select-same-color-tag.svg")), + ("select-same-sequence-id", include_str!("../../../assets/surface-icons/select-same-sequence-id.svg")), + ("select-same-variant-pos", include_str!("../../../assets/surface-icons/select-same-variant-pos.svg")), + ("select-smooth", include_str!("../../../assets/surface-icons/select-smooth.svg")), + ("select-subject", include_str!("../../../assets/surface-icons/select-subject.svg")), + ("select-tag-blue", include_str!("../../../assets/surface-icons/select-tag-blue.svg")), + ("select-tag-green", include_str!("../../../assets/surface-icons/select-tag-green.svg")), + ("select-tag-none", include_str!("../../../assets/surface-icons/select-tag-none.svg")), + ("select-tag-orange", include_str!("../../../assets/surface-icons/select-tag-orange.svg")), + ("select-tag-pink", include_str!("../../../assets/surface-icons/select-tag-pink.svg")), + ("select-tag-purple", include_str!("../../../assets/surface-icons/select-tag-purple.svg")), + ("select-tag-red", include_str!("../../../assets/surface-icons/select-tag-red.svg")), + ("select-tag-yellow", include_str!("../../../assets/surface-icons/select-tag-yellow.svg")), + ("select-tool", include_str!("../../../assets/surface-icons/select-tool.svg")), + ("select-unrated", include_str!("../../../assets/surface-icons/select-unrated.svg")), + ("set-compare-variant", include_str!("../../../assets/surface-icons/set-compare-variant.svg")), + ("shadow", include_str!("../../../assets/surface-icons/shadow.svg")), + ("shadow-brush", include_str!("../../../assets/surface-icons/shadow-brush.svg")), + ("shadow-lightness", include_str!("../../../assets/surface-icons/shadow-lightness.svg")), + ("shadow-tone-x", include_str!("../../../assets/surface-icons/shadow-tone-x.svg")), + ("shadow-tone-y", include_str!("../../../assets/surface-icons/shadow-tone-y.svg")), + ("sharpen-brush", include_str!("../../../assets/surface-icons/sharpen-brush.svg")), + ("sharpening-amount", include_str!("../../../assets/surface-icons/sharpening-amount.svg")), + ("sharpening-halo", include_str!("../../../assets/surface-icons/sharpening-halo.svg")), + ("sharpening-radius", include_str!("../../../assets/surface-icons/sharpening-radius.svg")), + ("sharpening-threshold", include_str!("../../../assets/surface-icons/sharpening-threshold.svg")), + ("sharpness-falloff", include_str!("../../../assets/surface-icons/sharpness-falloff.svg")), + ("show-filmstrip", include_str!("../../../assets/surface-icons/show-filmstrip.svg")), + ("show-grid", include_str!("../../../assets/surface-icons/show-grid.svg")), + ("show-guides", include_str!("../../../assets/surface-icons/show-guides.svg")), + ("show-hide-browser", include_str!("../../../assets/surface-icons/show-hide-browser.svg")), + ("show-hide-viewer", include_str!("../../../assets/surface-icons/show-hide-viewer.svg")), + ("show-histogram", include_str!("../../../assets/surface-icons/show-histogram.svg")), + ("show-in-file-system", include_str!("../../../assets/surface-icons/show-in-file-system.svg")), + ("show-in-library", include_str!("../../../assets/surface-icons/show-in-library.svg")), + ("show-metadata", include_str!("../../../assets/surface-icons/show-metadata.svg")), + ("shutter-speed-down", include_str!("../../../assets/surface-icons/shutter-speed-down.svg")), + ("shutter-speed-up", include_str!("../../../assets/surface-icons/shutter-speed-up.svg")), + ("slide-show", include_str!("../../../assets/surface-icons/slide-show.svg")), + ("snap-to-90", include_str!("../../../assets/surface-icons/snap-to-90.svg")), + ("soft-light", include_str!("../../../assets/surface-icons/soft-light.svg")), + ("spot-radius", include_str!("../../../assets/surface-icons/spot-radius.svg")), + ("spot-removal-tool", include_str!("../../../assets/surface-icons/spot-removal-tool.svg")), + ("straighten-tool", include_str!("../../../assets/surface-icons/straighten-tool.svg")), + ("structure", include_str!("../../../assets/surface-icons/structure.svg")), + ("switch-crop-orientation", include_str!("../../../assets/surface-icons/switch-crop-orientation.svg")), + ("tint", include_str!("../../../assets/surface-icons/tint.svg")), + ("toggle-before-after", include_str!("../../../assets/surface-icons/toggle-before-after.svg")), + ("toggle-exposure-warn", include_str!("../../../assets/surface-icons/toggle-exposure-warn.svg")), + ("toggle-focus-mask", include_str!("../../../assets/surface-icons/toggle-focus-mask.svg")), + ("toggle-grading", include_str!("../../../assets/surface-icons/toggle-grading.svg")), + ("toggle-layer-on-off", include_str!("../../../assets/surface-icons/toggle-layer-on-off.svg")), + ("toggle-multi-view", include_str!("../../../assets/surface-icons/toggle-multi-view.svg")), + ("toggle-overlay", include_str!("../../../assets/surface-icons/toggle-overlay.svg")), + ("toggle-select-image", include_str!("../../../assets/surface-icons/toggle-select-image.svg")), + ("toggle-selection-points", include_str!("../../../assets/surface-icons/toggle-selection-points.svg")), + ("toggle-tools", include_str!("../../../assets/surface-icons/toggle-tools.svg")), + ("tone-curve", include_str!("../../../assets/surface-icons/tone-curve.svg")), + ("undo", include_str!("../../../assets/surface-icons/undo.svg")), + ("uniform-light", include_str!("../../../assets/surface-icons/uniform-light.svg")), + ("vignetting", include_str!("../../../assets/surface-icons/vignetting.svg")), + ("watermark-tool", include_str!("../../../assets/surface-icons/watermark-tool.svg")), + ("wb-picker-tool", include_str!("../../../assets/surface-icons/wb-picker-tool.svg")), + ("white", include_str!("../../../assets/surface-icons/white.svg")), + ("white-balance", include_str!("../../../assets/surface-icons/white-balance.svg")), + ("zoom", include_str!("../../../assets/surface-icons/zoom.svg")), + ("zoom-100", include_str!("../../../assets/surface-icons/zoom-100.svg")), + ("zoom-200", include_str!("../../../assets/surface-icons/zoom-200.svg")), + ("zoom-400", include_str!("../../../assets/surface-icons/zoom-400.svg")), + ("zoom-actual-size", include_str!("../../../assets/surface-icons/zoom-actual-size.svg")), + ("zoom-fit-view", include_str!("../../../assets/surface-icons/zoom-fit-view.svg")), + ("zoom-in", include_str!("../../../assets/surface-icons/zoom-in.svg")), + ("zoom-in-tool", include_str!("../../../assets/surface-icons/zoom-in-tool.svg")), + ("zoom-out", include_str!("../../../assets/surface-icons/zoom-out.svg")), + ("zoom-out-tool", include_str!("../../../assets/surface-icons/zoom-out-tool.svg")), + ("zoom-to-fit", include_str!("../../../assets/surface-icons/zoom-to-fit.svg")), +]; diff --git a/crates/surface/src/icons.rs b/crates/surface/src/icons.rs new file mode 100644 index 00000000000..53f124febfc --- /dev/null +++ b/crates/surface/src/icons.rs @@ -0,0 +1,356 @@ +//! The icon pack shown on LCD keys and in the on-screen readout, and short key labels. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: the icons are TactileBridge's +//! hand-drawn pack (`assets/surface-icons`, renamed to kebab-case), the key labels its +//! `deploy_captureone_plugin.ps1` labels. +//! +//! The SVGs are compiled into native builds only (the web build has no surfaces). + +use serde_json::Value; + +use crate::binding::{Binding, Modifier}; +use crate::tactilebridge::{ADJUSTMENTS, COMMANDS, binding_of}; + +#[cfg(not(target_arch = "wasm32"))] +#[path = "icon_table.rs"] +mod table; + +#[cfg(not(target_arch = "wasm32"))] +fn icons() -> &'static [(&'static str, &'static str)] { + table::ICONS +} + +#[cfg(target_arch = "wasm32")] +fn icons() -> &'static [(&'static str, &'static str)] { + &[] +} + +/// The SVG of an icon. +pub fn svg(name: &str) -> Option<&'static str> { + let all = icons(); + all.binary_search_by(|(n, _)| (*n).cmp(name)).ok().and_then(|i| all.get(i)).map(|(_, s)| *s) +} + +/// Every icon name. +pub fn names() -> impl Iterator { + icons().iter().map(|(n, _)| *n) +} + +/// `Rate5Stars` → `rate-5-stars`, `BWRed` → `bw-red` (the icon file names). +pub fn kebab(key: &str) -> String { + let chars: Vec = key.chars().collect(); + let mut out = String::new(); + for (i, c) in chars.iter().enumerate() { + let prev = i.checked_sub(1).and_then(|j| chars.get(j)).copied(); + let next = chars.get(i + 1).copied(); + let boundary = match prev { + None => false, + Some(p) => { + (c.is_ascii_uppercase() && (p.is_ascii_lowercase() || p.is_ascii_digit())) + || (c.is_ascii_uppercase() && p.is_ascii_uppercase() && next.is_some_and(|n| n.is_ascii_lowercase())) + || (c.is_ascii_digit() && p.is_ascii_alphabetic()) + } + }; + if boundary { + out.push('-'); + } + out.extend(c.to_lowercase()); + } + out +} + +/// The TactileBridge key a binding came from (the first that maps to it). +fn tb_key(b: &Binding) -> Option<&'static str> { + let keys: &[&'static str] = if matches!(b, Binding::Value { .. }) { ADJUSTMENTS } else { COMMANDS }; + keys.iter().copied().find(|k| binding_of(k).as_ref() == Some(b)) +} + +/// The icon of a binding, if the pack has one. +pub fn icon_for(b: &Binding) -> Option<&'static str> { + if let Some(name) = drawn_icon(b) { + return svg_name(name); + } + let name: String = match b { + Binding::Value { target } => { + if let Some(k) = tb_key(b) { + kebab(k) + } else if let Some(field) = target.strip_prefix("mask.") { + // a mask slider shows its global slider's icon + let global = match field { + "exposure" | "contrast" | "highlights" | "shadows" | "whites" | "blacks" => format!("light.{field}"), + "temp" => "wb.temp".into(), + "tint" => "wb.tint".into(), + "clarity" | "texture" => format!("effects.{field}"), + "saturation" => "color.saturation".into(), + "amount" => return svg_name("layer-opacity"), + _ => return None, + }; + return icon_for(&Binding::value(&global)); + } else { + match target.as_str() { + "ui.brushFeather" => "brush-hardness".into(), + "ui.removeFeather" | "ui.removeOpacity" => "spot-radius".into(), + "crop.angle" => "straighten-tool".into(), + "color.vibrance" => "saturation".into(), + "effects.dehaze" => "clarity".into(), + _ => return None, + } + } + } + Binding::Command { .. } => match tb_key(b) { + Some(k) => kebab(k), + None => match b { + Binding::Command { command, .. } => match command.as_str() { + "photo.flag" | "photo.pick" => "pick-variant".into(), + "photo.reject" => "filter-rejected".into(), + "tool.done" => "pick-variant".into(), + "tool.brush" => "draw-mask-tool".into(), + "crop.autoStraighten" => "straighten-tool".into(), + "crop.reset" => "reset-adjustments".into(), + "view.cropOverlayOrientation" => "switch-crop-orientation".into(), + "view.maskOverlay" => "toggle-overlay".into(), + "view.visualizeSpots" => "toggle-focus-mask".into(), + "spot.delete" => "remove-layer".into(), + "mask.visible" => "toggle-layer-on-off".into(), + "mask.add" => "new-empty-layer".into(), + "surface.dialogConfirm" => "pick-variant".into(), + "surface.dialogCancel" => "deselect-all".into(), + _ => return None, + }, + _ => return None, + }, + }, + Binding::PageNext { .. } => "next-set".into(), + Binding::PagePrevious { .. } => "previous-set".into(), + Binding::Page { .. } | Binding::Profile { .. } | Binding::ProfileNext => "toggle-tools".into(), + Binding::Reset => "reset-adjustments".into(), + Binding::ApplyToSelected => "auto-sync".into(), + Binding::FollowContext => "toggle-tools".into(), + Binding::Modifier { modifier: Modifier::Fine } => "decrease-zoom".into(), + Binding::Modifier { modifier: Modifier::Coarse } => "increase-zoom".into(), + }; + svg_name(&name) +} + +/// Functions that shared one of the pack's generic icons get their own: icons drawn for +/// LightCraft in the pack's style (the pack's originals stay as they are). +fn drawn_icon(b: &Binding) -> Option<&'static str> { + let Binding::Command { command, params } = b else { return None }; + Some(match command.as_str() { + "mask.invert" => "mask-invert", + "brush.erase" => "brush-erase", + "tool.brush" if params.get("new").and_then(Value::as_bool) == Some(true) => "brush-new", + "surface.maskPrevious" => "mask-previous", + "surface.maskNext" => "mask-next", + "mask.visible" => "mask-visible", + "view.zoomFit" => "zoom-fit-view", + "view.zoom100" => "zoom-actual-size", + "library.selectAll" => "select-all-photos", + "library.selectNone" => "select-no-photos", + "photo.rotateLeft" => "rotate-photo-left", + "photo.rotateRight" => "rotate-photo-right", + "develop.reset" => "reset-develop", + _ => return None, + }) +} + +fn svg_name(name: &str) -> Option<&'static str> { + // the static name, so callers can keep it + let all = icons(); + all.binary_search_by(|(n, _)| (*n).cmp(name)).ok().and_then(|i| all.get(i)).map(|(n, _)| *n) +} + +/// TactileBridge's short labels for keys whose split name is too long for a key. +fn tb_label(key: &str) -> Option<&'static str> { + Some(match key { + "Zoom100" => "Zoom 100%", + "Zoom200" => "Zoom 200%", + "Zoom400" => "Zoom 400%", + "ZoomToFit" => "Zoom To Fit", + "ToggleBeforeAfter" => "Before / After", + "ToggleExposureWarn" => "Clipping", + "ToggleLayerOnOff" => "Mask On/Off", + "ToggleSelectionPoints" => "Mask Pins", + "ResetAdjustments" => "Reset", + "ApplyAdjustments" => "Paste", + "CopyAdjustments" => "Copy", + "CopyAndApplyAdj" => "Sync", + "AutoAdjust" => "Auto", + "WBPickerTool" => "WB Picker", + "SpotRemovalTool" => "Remove", + "LinearGradientTool" => "Linear Grad", + "RadialGradientTool" => "Radial Grad", + "DrawMaskTool" => "Brush", + "EraseMaskTool" => "Erase", + "CropTool" => "Crop", + "MoveToTrash" | "Delete" => "Delete", + "ClearRating" => "No Rating", + "Rate1Star" => "1 Star", + "Rate2Stars" => "2 Stars", + "Rate3Stars" => "3 Stars", + "Rate4Stars" => "4 Stars", + "Rate5Stars" => "5 Stars", + "ColorTagNone" => "No Label", + "ColorTagRed" => "Red", + "ColorTagYellow" => "Yellow", + "ColorTagGreen" => "Green", + "ColorTagBlue" => "Blue", + "ColorTagPurple" => "Purple", + "PreviousImage" => "Previous", + "NextImage" => "Next", + "BWEnable" => "B&W", + "NewEmptyLayer" => "New Mask", + "SelectLayerUp" => "Previous Mask", + "SelectLayerDown" => "Next Mask", + "Process" => "Export", + "EditAllSelected" => "Auto Sync", + "DirectColorEditor" => "Color", + "LoupeTool" => "Zoom 1:1", + "SwitchCropOrientation" => "Crop Orient.", + "AutoSync" => "Apply to All", + _ => return None, + }) +} + +/// `RotateLeft` → `Rotate Left`. +fn split_words(key: &str) -> String { + kebab(key) + .split('-') + .filter(|w| !w.is_empty()) + .map(|w| { + let mut c = w.chars(); + c.next().map(|f| f.to_ascii_uppercase().to_string() + c.as_str()).unwrap_or_default() + }) + .collect::>() + .join(" ") +} + +/// A short English key label for a command (the host prefers the registry's label when this +/// only repeats the id). +pub fn command_label(command: &str, params: &Value) -> String { + let b = Binding::Command { command: command.to_string(), params: params.clone() }; + // LightCraft's own words: a curated short label, else the command's own label (the host + // looks it up; never a TactileBridge / Capture One action name) + if let Some(l) = tb_key(&b).and_then(tb_label) { + return l.to_string(); + } + let stars = |n: u64| if n == 1 { "1 Star".to_string() } else { format!("{n} Stars") }; + let label_name = |l: &str| split_words(l); + match command { + "library.filter" => match (params.get("rating").and_then(Value::as_u64), params.get("label")) { + (Some(0), _) => "Show Unrated".into(), + (Some(n), _) => format!("Show {}+", stars(n)), + (None, Some(Value::String(l))) => format!("Show {}", label_name(l)), + (None, Some(Value::Null)) => "Any Label".into(), + _ => command.to_string(), + }, + "library.selectBy" => match (params.get("rating").and_then(Value::as_u64), params.get("label").and_then(Value::as_str)) { + (Some(0), _) => "Select Unrated".into(), + (Some(n), _) => format!("Select {}", stars(n)), + (None, Some("none")) => "Select No Label".into(), + (None, Some(l)) => format!("Select {}", label_name(l)), + _ => command.to_string(), + }, + "tool.guidedUpright" => "Guided Upright".into(), + "develop.resetControl" if params.get("control").and_then(Value::as_str) == Some("crop.angle") => "Reset Straighten".into(), + "mask.select" if params.get("id").is_some_and(Value::is_null) => "No Mask".into(), + "geometry.upright" => match params.get("mode").and_then(Value::as_str) { + Some("vertical") => "Upright: Vertical".into(), + Some("level") => "Upright: Level".into(), + Some("full") => "Upright: Full".into(), + Some("auto") => "Upright: Auto".into(), + Some(m) => format!("Upright: {}", split_words(m)), + None => "Upright".into(), + }, + "tool.done" => "Done".into(), + "surface.dialogConfirm" => "OK".into(), + "surface.dialogCancel" => "Cancel".into(), + "surface.maskPrevious" => "Previous Mask".into(), + "surface.maskNext" => "Next Mask".into(), + "brush.erase" => "Erase".into(), + "mask.add" => match params.get("kind").and_then(Value::as_str) { + Some("subject") => "Subject".into(), + Some("sky") => "Sky".into(), + Some("luminanceRange") => "Luminance".into(), + Some(k) => split_words(k), + None => "New Mask".into(), + }, + "tool.brush" if params.get("op").and_then(Value::as_str) == Some("subtract") => "Erase".into(), + "tool.brush" if params.get("new").and_then(Value::as_bool) == Some(true) => "New Brush".into(), + _ => command.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn mask_and_brush_keys_have_their_own_icons() { + let brush = Binding::command("tool.brush"); + let new_brush = Binding::Command { command: "tool.brush".into(), params: json!({"new": true}) }; + let picked: Vec<_> = [ + Binding::command("mask.invert"), + Binding::command("brush.erase"), + new_brush, + Binding::command("surface.maskPrevious"), + Binding::command("surface.maskNext"), + Binding::command("mask.visible"), + ] + .iter() + .map(icon_for) + .collect(); + assert!(picked.iter().all(Option::is_some), "{picked:?}"); + let mut distinct = picked.clone(); + distinct.sort(); + distinct.dedup(); + assert_eq!(distinct.len(), picked.len(), "{picked:?}"); + // the plain brush keeps the pack's own drawing + assert_eq!(icon_for(&brush), Some("draw-mask-tool")); + } + + #[test] + fn kebab_matches_the_file_names() { + assert_eq!(kebab("Rate5Stars"), "rate-5-stars"); + assert_eq!(kebab("BWRed"), "bw-red"); + assert_eq!(kebab("NRLuminance"), "nr-luminance"); + assert_eq!(kebab("Zoom100"), "zoom-100"); + assert_eq!(kebab("CEBlueHue"), "ce-blue-hue"); + assert_eq!(kebab("SnapTo90"), "snap-to-90"); + assert_eq!(kebab("ISOUp"), "iso-up"); + assert_eq!(kebab(""), ""); + } + + #[test] + fn the_pack_is_embedded_sorted_and_found() { + let all: Vec<_> = names().collect(); + assert!(all.len() > 300, "{}", all.len()); + assert!(all.windows(2).all(|w| w[0] < w[1]), "sorted for binary search"); + assert!(svg("exposure").is_some_and(|s| s.contains(" Option; + /// A short, translated label for a binding. + fn label(&self, binding: &Binding) -> String; + /// On / off for bindings that toggle something (Auto Sync, Before/After…), if known. + fn state(&self, binding: &Binding) -> Option; + /// Translate an English UI string. + fn tr(&self, english: &str) -> String; +} + +/// One key or button. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct KeyView { + pub control: String, + /// The binding (`null`: the key does nothing on this page). + pub binding: Option, + pub label: String, + /// An icon name (`surface.icons` returns its SVG). + pub icon: Option<&'static str>, + /// The value of a value key (`+0.35`), when values are shown. + pub value: Option, + /// Lit: the dial moves this key's value, the modifier is held, the toggle is on. + pub active: bool, + /// How it is lit: `focus` (its value is on the dial), `held` (a modifier or a momentary + /// command while its key is down), `on` (a mode or toggle that is on); none when not lit. + /// Surfaces draw focus and the other two differently. + pub state: Option<&'static str>, +} + +/// One encoder. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DialView { + pub control: String, + pub binding: Option, + pub label: String, + pub icon: Option<&'static str>, + pub value: Option, + /// Where the value sits between its ends, 0…1. + pub position: Option, +} + +/// A key page as a device with hardware page buttons shows it (its page `n`). +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct KeyPageView { + pub name: String, + pub keys: Vec, +} + +/// Everything a surface shows. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DeviceLayout { + pub device: &'static str, + pub profile: String, + pub context: String, + /// The current page of the key group and the dial group. + pub key_page: Option, + pub dial_page: Option, + /// The keys of the current key page. + pub keys: Vec, + /// Key pages 1…n for devices that page their keys themselves; while a context page is + /// active, every one of them shows it. + pub key_pages: Vec, + /// Plain buttons (the Dialpad's four). + pub buttons: Vec, + pub dials: Vec, + /// The value the dial moves instead of its own, if a key put one there. + pub focus: Option, + pub apply_to_selected: bool, + pub follow_context: bool, + /// `#RRGGBB`. + pub background: String, + pub foreground: String, + pub show_values: bool, + pub haptics: bool, +} + +/// Device pages offered by keypads that page in hardware (the Logi profile has this many). +pub const DEVICE_KEY_PAGES: usize = 3; + +fn key_view(r: &Runtime, host: &dyn Host, control: &str, binding: Option) -> KeyView { + let show = r.settings().look.show_values; + let (label, icon, value, state) = match &binding { + None => (String::new(), None, None, None), + Some(b) => { + let value = match b { + Binding::Value { target } if show => target_spec(target).and_then(|s| host.value(target).map(|v| s.format(v))), + _ => None, + }; + let state = match b { + Binding::Value { target } => (r.focus() == Some(target.as_str())).then_some("focus"), + Binding::Modifier { .. } => r.held_on(control).is_some().then_some("held"), + Binding::Command { command, .. } if crate::runtime::MOMENTARY.contains(&command.as_str()) => { + r.momentary_on(control).then_some("held") + } + Binding::ApplyToSelected => r.settings().apply_to_selected.then_some("on"), + Binding::FollowContext => r.settings().follow_context.then_some("on"), + _ => host.state(b).unwrap_or(false).then_some("on"), + }; + (host.label(b), crate::icons::icon_for(b), value, state) + } + }; + KeyView { control: control.to_string(), binding, label, icon, value, active: state.is_some(), state } +} + +/// The layout of `device` now. +pub fn build(r: &Runtime, device: &DeviceDef, host: &dyn Host) -> DeviceLayout { + let look = &r.settings().look; + let mut keys = Vec::new(); + let mut buttons = Vec::new(); + let mut dials = Vec::new(); + let key_controls: Vec<&str> = device.controls.iter().filter(|c| c.kind == ControlKind::Key).map(|c| c.id).collect(); + for c in device.controls { + let b = r.binding(c.id, None); + match c.kind { + ControlKind::Key => keys.push(key_view(r, host, c.id, b)), + ControlKind::Button => buttons.push(key_view(r, host, c.id, b)), + ControlKind::Encoder => { + let (label, icon, value, position) = match &b { + Some(bound @ Binding::Value { target }) => { + let spec = target_spec(target); + let v = host.value(target); + let value = if look.show_values { spec.as_ref().zip(v).map(|(s, v)| s.format(v)) } else { None }; + (host.label(bound), crate::icons::icon_for(bound), value, spec.zip(v).map(|(s, v)| s.position(v))) + } + Some(other) => (host.label(other), crate::icons::icon_for(other), None, None), + None => (String::new(), None, None, None), + }; + dials.push(DialView { control: c.id.to_string(), binding: b, label, icon, value, position }); + } + } + } + let key_pages = (1..=r.key_page_count().max(DEVICE_KEY_PAGES)) + .map(|n| { + let page = r.device_key_page(n); + KeyPageView { + name: page.map(|p| p.name.clone()).unwrap_or_default(), + keys: key_controls.iter().map(|c| key_view(r, host, c, r.binding(c, Some(n)))).collect(), + } + }) + .collect(); + DeviceLayout { + device: device.id, + profile: r.settings().profile.clone(), + context: r.context().to_string(), + key_page: r.pages().get(&PageGroup::Keys).cloned(), + dial_page: r.pages().get(&PageGroup::Dials).cloned(), + keys, + key_pages, + buttons, + dials, + focus: r.focus().map(str::to_string), + apply_to_selected: r.settings().apply_to_selected, + follow_context: r.settings().follow_context, + background: look.background.clone(), + foreground: look.foreground.clone(), + show_values: look.show_values, + haptics: look.haptics, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::devices::MX_CREATIVE_CONSOLE; + use crate::settings::SurfaceSettings; + + struct H; + impl Host for H { + fn value(&self, target: &str) -> Option { + (target == "light.exposure").then_some(0.5) + } + fn label(&self, b: &Binding) -> String { + b.describe() + } + fn state(&self, _: &Binding) -> Option { + None + } + fn tr(&self, english: &str) -> String { + english.into() + } + } + + #[test] + fn default_profile_layout() { + let r = Runtime::new(SurfaceSettings::default()); + let l = build(&r, &MX_CREATIVE_CONSOLE, &H); + assert_eq!(l.keys.len(), 9); + assert_eq!(l.buttons.len(), 12, "four Dialpad buttons, eight Actions Ring slots"); + assert_eq!(l.dials.len(), 2); + assert_eq!(l.key_pages.len(), DEVICE_KEY_PAGES); + assert_eq!(l.key_pages.iter().map(|p| p.name.as_str()).collect::>(), ["Page 1", "Page 2", "Page 3"]); + // TactileBridge's default: Exposure on the roller (encoder 0), Contrast on the big dial + let roller = l.dials.iter().find(|d| d.control == "roller").unwrap(); + assert_eq!((roller.label.as_str(), roller.value.as_deref(), roller.position), ("Exposure", Some("+0.50"), Some(0.55))); + assert_eq!(l.keys[0].icon, Some("previous-image")); + assert_eq!(l.buttons[3].binding, Some(Binding::PageNext { group: Some(PageGroup::Dials) })); + let json = serde_json::to_value(&l).unwrap(); + assert_eq!(json["dials"][1]["binding"]["target"], "light.exposure"); + } +} diff --git a/crates/surface/src/lib.rs b/crates/surface/src/lib.rs new file mode 100644 index 00000000000..f5f60827faa --- /dev/null +++ b/crates/surface/src/lib.rs @@ -0,0 +1,49 @@ +//! Control surfaces: hardware dials, keys and buttons that drive LightCraft. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT. +//! +//! This crate is the engine behind Settings ▸ Controls and the `surface.*` control-channel methods +//! (`docs/control-surfaces.md`). It has no UI and no I/O: the host (the egui app) feeds it input +//! events and the current [`Context`], runs the [`Effect`]s it returns through the command +//! registry, and pushes its [`layout::DeviceLayout`] to connected surfaces. +//! +//! - [`devices`]: the controls of each supported device (the Logitech MX Creative Console first; +//! MIDI and Tangent panels plug in as more device definitions). +//! - [`binding`], [`profile`]: what a control does — a develop value, a command, a page switch, a +//! modifier — grouped into pages and profiles, with pages that follow the app's context. +//! - [`targets`]: the values a dial can move (develop sliders, mask sliders, brush and view values). +//! - [`motion`]: ticks to value deltas — speed, acceleration curve, fine/coarse modifiers, invert. +//! - [`runtime`]: the live engine — coalescing, one undo step per dial gesture, dial focus, pages. +//! - [`settings`]: everything the user tunes, stored as `control-surfaces.json`. +//! - [`loupedeck`]: the Loupedeck+ console's controls, their defaults, and importing a Loupedeck +//! profile's layout. +//! - [`tactilebridge`]: imports a TactileBridge `settings.json` and its Logi profiles (`.lp5`). +//! - [`catalog`]: every action in categories (the editor's picker; plugins list them in their app). +//! - [`protocol`]: pairing tokens and the message shapes of the surface protocol. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod binding; +pub mod catalog; +pub mod context; +pub mod defaults; +pub mod devices; +pub mod icons; +pub mod layout; +pub mod loupedeck; +pub mod motion; +pub mod profile; +pub mod protocol; +pub mod runtime; +pub mod settings; +pub mod tactilebridge; +pub mod targets; +pub mod zip; + +pub use binding::{Binding, Modifier}; +pub use context::Context; +pub use devices::{ControlDef, ControlKind, DeviceDef, PageGroup}; +pub use profile::{Page, Profile}; +pub use runtime::{Effect, Input, Runtime}; +pub use settings::SurfaceSettings; +pub use targets::{TargetKind, TargetSpec}; diff --git a/crates/surface/src/loupedeck.rs b/crates/surface/src/loupedeck.rs new file mode 100644 index 00000000000..c1b08c33796 --- /dev/null +++ b/crates/surface/src/loupedeck.rs @@ -0,0 +1,605 @@ +//! The Loupedeck+ (Loupedeck's photo-editing console: knobs, a control dial and buttons, no +//! displays) and importing a Loupedeck profile made for another photo editor. +//! +//! Loupedeck's own software numbers the console's controls; its profiles (`ProfileInfo.json`, +//! or an exported `.lp5` holding one) list, per mode and workspace, the action of each press and +//! each turn by that number. LightCraft's controls are those numbers: `ld.r` turns, `ld.b` +//! presses. The LightCraft plugin forwards them; the console needs no setup in LightCraft — every +//! control has a default here, after the labels printed on the console — and an imported profile +//! replaces those defaults with the user's own layout (only the mapping is read: no icons or +//! images come along). + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; + +use crate::binding::Binding; +use crate::devices::{ControlDef, ControlKind, PageGroup}; +use crate::tactilebridge::{Mapped, Report, ReportLine}; + +/// The id of a turn (`ld.r33`) or a press (`ld.b95`). +pub fn rotate_id(n: usize) -> String { + format!("ld.r{n}") +} +pub fn press_id(n: usize) -> String { + format!("ld.b{n}") +} + +const fn knob(id: &'static str, label: &'static str) -> ControlDef { + ControlDef { id, kind: ControlKind::Encoder, label, group: PageGroup::Dials } +} +const fn button(id: &'static str, label: &'static str) -> ControlDef { + ControlDef { id, kind: ControlKind::Button, label, group: PageGroup::Dials } +} + +/// The Loupedeck+'s controls, named as printed on the console. P1–P8 send 1–8, 9–16 or 17–24 by +/// the Hue / Sat / Lum buttons, as in Loupedeck's own profiles. +pub const CONTROLS: &[ControlDef] = &[ + knob("ld.r1", "P1 (Hue)"), + knob("ld.r2", "P2 (Hue)"), + knob("ld.r3", "P3 (Hue)"), + knob("ld.r4", "P4 (Hue)"), + knob("ld.r5", "P5 (Hue)"), + knob("ld.r6", "P6 (Hue)"), + knob("ld.r7", "P7 (Hue)"), + knob("ld.r8", "P8 (Hue)"), + knob("ld.r9", "P1 (Sat)"), + knob("ld.r10", "P2 (Sat)"), + knob("ld.r11", "P3 (Sat)"), + knob("ld.r12", "P4 (Sat)"), + knob("ld.r13", "P5 (Sat)"), + knob("ld.r14", "P6 (Sat)"), + knob("ld.r15", "P7 (Sat)"), + knob("ld.r16", "P8 (Sat)"), + knob("ld.r17", "P1 (Lum)"), + knob("ld.r18", "P2 (Lum)"), + knob("ld.r19", "P3 (Lum)"), + knob("ld.r20", "P4 (Lum)"), + knob("ld.r21", "P5 (Lum)"), + knob("ld.r22", "P6 (Lum)"), + knob("ld.r23", "P7 (Lum)"), + knob("ld.r24", "P8 (Lum)"), + knob("ld.r25", "P1 (B&W)"), + knob("ld.r26", "P2 (B&W)"), + knob("ld.r27", "P3 (B&W)"), + knob("ld.r28", "P4 (B&W)"), + knob("ld.r29", "P5 (B&W)"), + knob("ld.r30", "P6 (B&W)"), + knob("ld.r31", "P7 (B&W)"), + knob("ld.r32", "P8 (B&W)"), + knob("ld.r33", "Exposure"), + knob("ld.r34", "Blacks"), + knob("ld.r35", "Whites"), + knob("ld.r36", "Saturation"), + knob("ld.r37", "Vibrance"), + knob("ld.r38", "Temperature"), + knob("ld.r39", "Tint"), + knob("ld.r40", "Highlights"), + knob("ld.r41", "D1"), + knob("ld.r42", "D2"), + knob("ld.r44", "Shadows"), + knob("ld.r45", "Clarity"), + knob("ld.r46", "Contrast"), + knob("ld.r47", "Knob 47"), + knob("ld.r48", "Control Dial"), + button("ld.b33", "Exposure (press)"), + button("ld.b34", "Blacks (press)"), + button("ld.b35", "Whites (press)"), + button("ld.b36", "Saturation (press)"), + button("ld.b37", "Vibrance (press)"), + button("ld.b38", "Temperature (press)"), + button("ld.b39", "Tint (press)"), + button("ld.b40", "Highlights (press)"), + button("ld.b41", "D1 (press)"), + button("ld.b42", "D2 (press)"), + button("ld.b44", "Shadows (press)"), + button("ld.b45", "Clarity (press)"), + button("ld.b46", "Contrast (press)"), + button("ld.b47", "Knob 47 (press)"), + button("ld.b48", "Control Dial (press)"), + button("ld.b49", "C1"), + button("ld.b50", "C2"), + button("ld.b51", "C3"), + button("ld.b52", "C4"), + button("ld.b53", "C5"), + button("ld.b54", "C6"), + button("ld.b66", "Star rating 1"), + button("ld.b67", "Star rating 2"), + button("ld.b68", "Star rating 3"), + button("ld.b69", "Star rating 4"), + button("ld.b70", "Star rating 5"), + button("ld.b71", "Fn + Star rating 1"), + button("ld.b72", "Fn + Star rating 2"), + button("ld.b73", "Fn + Star rating 3"), + button("ld.b74", "Fn + Star rating 4"), + button("ld.b75", "Fn + Star rating 5"), + button("ld.b76", "Button 76"), + button("ld.b77", "Button 77"), + button("ld.b78", "Left arrow"), + button("ld.b79", "Right arrow"), + button("ld.b80", "P1 (press)"), + button("ld.b81", "P2 (press)"), + button("ld.b82", "P3 (press)"), + button("ld.b83", "P4 (press)"), + button("ld.b84", "P5 (press)"), + button("ld.b85", "P6 (press)"), + button("ld.b86", "P7 (press)"), + button("ld.b87", "P8 (press)"), + button("ld.b88", "Export"), + button("ld.b89", "Button 89"), + button("ld.b90", "Button 90"), + button("ld.b91", "Pick"), + button("ld.b92", "Copy"), + button("ld.b93", "Paste"), + button("ld.b94", "Button 94"), + button("ld.b95", "Undo"), + button("ld.b96", "Redo"), + button("ld.b97", "Screen Mode"), + button("ld.b98", "Hue"), + button("ld.b99", "Sat"), + button("ld.b100", "Lum"), + button("ld.b101", "Col/BW"), + button("ld.b102", "Before/After"), + button("ld.b103", "Button 103"), + button("ld.b104", "Button 104"), + button("ld.b110", "Custom Mode"), + button("ld.b114", "L1"), + button("ld.b115", "L2"), + button("ld.b116", "L3"), +]; + +/// The action names of Loupedeck's own default layout for the console (after which its knobs and +/// buttons are labelled): (control, action). +const DEFAULTS: &[(&str, &str)] = &[ + ("ld.r33", "Exposure"), + ("ld.r34", "Blacks"), + ("ld.r35", "Whites"), + ("ld.r36", "Saturation"), + ("ld.r37", "Vibrance"), + ("ld.r38", "Temperature"), + ("ld.r39", "Tint"), + ("ld.r40", "Highlights"), + ("ld.r41", "Dehaze"), + ("ld.r42", "Sharpness"), + ("ld.r44", "Shadows"), + ("ld.r45", "Clarity"), + ("ld.r46", "Contrast"), + ("ld.r47", "Dehaze"), + ("ld.r48", "ActivateCropToolByRotation"), + ("ld.b48", "ActivateCropTool"), + ("ld.b49", "TogglePickFlag"), + ("ld.b50", "ToggleRejectFlag"), + ("ld.b51", "AutoSettings"), + ("ld.b52", "AutoWhiteBalance"), + ("ld.b53", "ToggleZoomView"), + ("ld.b66", "RatingStar1"), + ("ld.b67", "RatingStar2"), + ("ld.b68", "RatingStar3"), + ("ld.b69", "RatingStar4"), + ("ld.b70", "RatingStar5"), + ("ld.b71", "RatingColor1"), + ("ld.b72", "RatingColor2"), + ("ld.b73", "RatingColor3"), + ("ld.b74", "RatingColor4"), + ("ld.b75", "RatingColor5"), + ("ld.b78", "MoveToPreviousPhoto"), + ("ld.b79", "MoveToNextPhoto"), + ("ld.b88", "OpenExportDialog"), + ("ld.b89", "ToggleZoomView"), + ("ld.b90", "ToggleZoomView"), + ("ld.b91", "TogglePickFlag"), + ("ld.b92", "CopyAllSettings"), + ("ld.b93", "PasteAllSettings"), + ("ld.b94", "ActivateDevelopTool___localized"), + ("ld.b95", "Undo"), + ("ld.b96", "Redo"), + ("ld.b97", "FullScreen"), + ("ld.b101", "ToggleColorMode"), + ("ld.b102", "ToggleBeforeAfter"), + ("ld.b103", "AutoSettings"), + ("ld.b104", "AutoWhiteBalance"), + ("ld.b114", "ActivateDevelopTool___localized"), + ("ld.b115", "ActivateDevelopTool___circularGradient"), + ("ld.b116", "ActivateDevelopTool___gradient"), +]; + +const BANDS: [&str; 8] = ["Red", "Orange", "Yellow", "Green", "Aqua", "Blue", "Purple", "Magenta"]; + +/// What a control does when nothing (no profile, no import) binds it: Loupedeck's own default +/// layout, so the console works as labelled with no setup. P1–P8 move the colour mixer. +pub fn default_binding(control: &str) -> Option { + if let Some(n) = control.strip_prefix("ld.r").and_then(|n| n.parse::().ok()) + && (1..=32).contains(&n) + { + let band = BANDS.get((n - 1) % 8)?.to_ascii_lowercase(); + return Some(Binding::value(&match (n - 1) / 8 { + 0 => format!("mixer.{band}.hue"), + 1 => format!("mixer.{band}.sat"), + 2 => format!("mixer.{band}.lum"), + _ => format!("bw.{band}"), + })); + } + let (_, action) = DEFAULTS.iter().find(|(c, _)| *c == control)?; + match map_action(action, &|_| None) { + Mapped::To(b, _) => Some(b), + Mapped::Dropped(_) => None, + } +} + +fn c(command: &str) -> Mapped { + Mapped::To(Binding::command(command), None) +} +fn cp(command: &str, params: Value) -> Mapped { + Mapped::To(Binding::command_with(command, params), None) +} +fn cn(command: &str, note: &'static str) -> Mapped { + Mapped::To(Binding::command(command), Some(note)) +} + +const MACRO: &str = "Loupedeck macros don't come along: set the control in LightCraft"; +const OTHER_APP: &str = "it works on another app"; + +/// A develop value (`Exposure`, `HueAdjustmentRed`, `LocalizedTemperature` …) by its action +/// name: (value id, note). +fn value_of(name: &str) -> Option<(String, Option<&'static str>)> { + let plain = |s: &str| Some((s.to_string(), None)); + for (prefix, field) in [("HueAdjustment", "hue"), ("SaturationAdjustment", "sat"), ("LuminanceAdjustment", "lum")] { + if let Some(band) = name.strip_prefix(prefix).filter(|b| BANDS.contains(b)) { + return plain(&format!("mixer.{}.{field}", band.to_ascii_lowercase())); + } + } + if let Some(band) = name.strip_prefix("GrayMixer").filter(|b| BANDS.contains(b)) { + return plain(&format!("bw.{}", band.to_ascii_lowercase())); + } + if let Some(local) = name.strip_prefix("Localized") { + let field = match local { + "Exposure" => "exposure", + "Contrast" => "contrast", + "Highlights" => "highlights", + "Shadows" => "shadows", + "Whites" => "whites", + "Blacks" => "blacks", + "Temperature" => "temp", + "Tint" => "tint", + "Clarity" => "clarity", + "Texture" => "texture", + "Dehaze" => "dehaze", + "Saturation" => "saturation", + "Defringe" => "defringe", + "Moire" => "moire", + "LuminanceNoise" => "noise", + "Sharpness" => "sharpness", + "Hue" => "hue", + _ => return None, + }; + return plain(&format!("mask.{field}")); + } + // a value turned with its clipping view (Alt held) is the value itself + let base = name.strip_suffix("Clipping").unwrap_or(name); + let id = match base { + "Exposure" => "light.exposure", + "Contrast" => "light.contrast", + "Highlights" => "light.highlights", + "Shadows" => "light.shadows", + "Whites" => "light.whites", + "Blacks" => "light.blacks", + "Temperature" => "wb.temp", + "Tint" => "wb.tint", + "Vibrance" => "color.vibrance", + "Saturation" => "color.saturation", + "Clarity" => "effects.clarity", + "Texture" => "effects.texture", + "Dehaze" => "effects.dehaze", + "Sharpness" => "detail.sharpenAmount", + "SharpenRadius" => "detail.sharpenRadius", + "SharpenDetail" => "detail.sharpenDetail", + "SharpenEdgeMasking" => "detail.sharpenMasking", + "LuminanceSmoothing" => "detail.nrLuminance", + "LuminanceNoiseReductionDetail" => "detail.nrDetail", + "LuminanceNoiseReductionContrast" => "detail.nrContrast", + "ColorNoiseReduction" => "detail.nrColor", + "ColorNoiseReductionDetail" => "detail.nrColorDetail", + "ColorNoiseReductionSmoothness" => "detail.nrColorSmoothness", + "PostCropVignetteAmount" => "vignette.amount", + "PostCropVignetteMidpoint" => "vignette.midpoint", + "PostCropVignetteFeather" => "vignette.feather", + "PostCropVignetteRoundness" => "vignette.roundness", + "PostCropVignetteHighlightContrast" => "vignette.highlights", + "ParametricHighlights" => "curve.highlights", + "ParametricLights" => "curve.lights", + "ParametricDarks" => "curve.darks", + "ParametricShadows" => "curve.shadows", + "ParametricShadowSplit" => "curve.splitShadows", + "ParametricMidtoneSplit" => "curve.splitMid", + "ParametricHighlightSplit" => "curve.splitHighlights", + "SplitToningHighlightHue" => "grading.highlights.hue", + "SplitToningHighlightSaturation" => "grading.highlights.sat", + "SplitToningShadowHue" => "grading.shadows.hue", + "SplitToningShadowSaturation" => "grading.shadows.sat", + "SplitToningBalance" => "grading.balance", + "RedHue" => "calibration.redHue", + "RedSaturation" => "calibration.redSat", + "GreenHue" => "calibration.greenHue", + "GreenSaturation" => "calibration.greenSat", + "BlueHue" => "calibration.blueHue", + "BlueSaturation" => "calibration.blueSat", + "ShadowTint" => "calibration.shadowsTint", + "AdjustmentBrushSize" => "ui.brushSize", + "AdjustmentBrushFeatherSize" => "ui.brushFeather", + "AdjustmentBrushFlow" => "ui.brushFlow", + "RotateCropArea" | "RotateCropAreaSome" | "ActivateCropToolByRotation" | "Straighten" => { + return Some(("crop.angle".into(), Some("straightens the photo"))); + } + _ => return None, + }; + let note = if base != name { Some("the clipping view isn't shown while turning") } else { None }; + Some((id.into(), note)) +} + +/// A Loupedeck photo-editor action (`Exposure`, `RatingStar3`, `ApplyDevelopPreset___Group|Name`, +/// `@Macro___` …) as a LightCraft binding. `preset` finds a LightCraft preset id by the +/// preset's name. +pub fn map_action(action: &str, preset: &dyn Fn(&str) -> Option) -> Mapped { + let (name, param) = match action.split_once("___") { + Some((n, p)) => (n, Some(p)), + None => (action, None), + }; + if let Some((id, note)) = value_of(name) { + return Mapped::To(Binding::value(&id), note); + } + if let Some(value) = name.strip_prefix("Reset").and_then(value_of).map(|(id, _)| id) { + if value.starts_with("ui.") || value.starts_with("mask.") || value == "crop.angle" { + return Mapped::Dropped("LightCraft resets a value when its knob is pressed"); + } + return Mapped::To(Binding::command_with("develop.resetControl", json!({"control": value})), None); + } + let digit = |s: &str| s.chars().next().and_then(|d| d.to_digit(10)); + if let Some(n) = name.strip_prefix("RatingStar").and_then(digit) { + return cp("photo.rate", json!({"rating": n})); + } + if let Some(n) = name.strip_prefix("RatingFilter").and_then(digit) { + return cp("library.filter", json!({"rating": n, "ratingOp": "atLeast"})); + } + const LABELS: [&str; 5] = ["red", "yellow", "green", "blue", "purple"]; + let label = |s: &str| digit(s).and_then(|n| LABELS.get((n as usize).wrapping_sub(1)).copied()); + if let Some(l) = name.strip_prefix("RatingColor").and_then(label) { + return cp("photo.label", json!({"label": l})); + } + if let Some(l) = name.strip_prefix("ColorFilter").and_then(label) { + return cp("library.filter", json!({"label": l})); + } + match name { + "Undo" => c("edit.undo"), + "Redo" => c("edit.redo"), + "CopyAllSettings" | "CopySettings" => c("develop.copy"), + "PasteAllSettings" | "PasteSettings" => c("develop.paste"), + "PasteFromPrevious" => c("develop.pastePrevious"), + "SyncSettings" => cn("develop.sync", "copies the active photo's settings to the other selected photos"), + "AutoSettings" => c("develop.auto"), + "AutoWhiteBalance" => cp("develop.wb", json!({"mode": "auto"})), + "ResetAllAdjustments" => c("develop.reset"), + "ResetCrop" => c("crop.reset"), + "TogglePickFlag" => c("photo.pick"), + "ToggleRejectFlag" => c("photo.reject"), + "FlagFilter" => match param { + Some("flagged") => cp("library.filter", json!({"flag": "pick"})), + Some("rejected") => cp("library.filter", json!({"flag": "reject"})), + Some("unflagged") => cp("library.filter", json!({"flag": "none"})), + _ => Mapped::Dropped("an unknown flag filter"), + }, + "MoveToNextPhoto" | "SelectRight" | "MoveRight" => c("library.next"), + "MoveToPreviousPhoto" | "SelectLeft" | "MoveLeft" => c("library.previous"), + "SelectAll" => c("library.selectAll"), + "DeselectOtherPhotos" | "SelectNone" => c("library.selectNone"), + "ToggleZoomView" => c("view.zoomToggle"), + "ZoomIn" => c("view.zoomIn"), + "ZoomOut" => c("view.zoomOut"), + "FullScreen" => c("view.fullScreenPreview"), + "ToggleBeforeAfter" => c("view.beforeAfter"), + "ShowClipping" => c("view.clipping"), + "TogglePanels" => cn("panel.edit", "opens or closes the Edit panel"), + "ToggleDevelopLibraryModules" => cn("view.back", "back to the grid"), + "ToggleColorMode" => cn("develop.treatment", "colour or black & white"), + "OpenExportDialog" | "ExportWithPreset" | "ExportWithPrevious" => cn("dialog.export", "the Export dialog"), + "CreateVirtualCopies" | "CreateVirtualCopy" => c("photo.virtualCopy"), + "ActivateCropTool" => c("panel.crop"), + "CycleCropGridOverlay" => c("view.cropOverlay"), + "CycleCropGridOverlayOrientation" => c("view.cropOverlayOrientation"), + "ToggleCropAspectRatio" => cp("crop.aspect", json!({"aspect": "toggle"})), + "TogglePerspectiveUpright" => cpn("geometry.upright", json!({"mode": "auto"}), "Upright: Auto"), + "DeactivateDevelopTool" => c("tool.done"), + "ActivateDevelopTool" => match param { + Some("localized") => cn("tool.brush", "the brush"), + Some("circularGradient") => c("tool.radial"), + Some("gradient") => c("tool.linear"), + Some("spotRemoval") => cn("panel.remove", "the Remove tool (heal and clone)"), + Some("redeye") => c("panel.redeye"), + Some("crop") => c("panel.crop"), + Some("masking") => cn("panel.masking", "the Masks panel"), + _ => Mapped::Dropped("LightCraft has no such tool"), + }, + "ApplyDevelopPreset" => { + let full = param.unwrap_or_default(); + // `Group|Name`: LightCraft's presets go by name + let short = full.rsplit('|').next().unwrap_or(full).trim_end_matches('.').trim(); + match preset(short).or_else(|| preset(full)) { + Some(id) => Mapped::To(Binding::command_with("preset.apply", json!({"id": id})), None), + None => Mapped::Dropped("no LightCraft preset has this name: import the preset, then import the profile again"), + } + } + "@Macro" => Mapped::Dropped(MACRO), + "@ActivateClientApplication" | "@ActivateLoupedeckConfiguration" => { + Mapped::Dropped("Loupedeck's own button: it switches the console's app or profile") + } + "EditInPhotoshop" | "EditInOtherApplication" => Mapped::Dropped(OTHER_APP), + "SetColorModeHue" | "SetColorModeSaturation" | "SetColorModeLuminance" => { + Mapped::Dropped("Hue, Sat and Lum switch what P1–P8 send; LightCraft follows the console") + } + _ => Mapped::Dropped("LightCraft has no counterpart for this action yet"), + } +} + +fn cpn(command: &str, params: Value, note: &'static str) -> Mapped { + Mapped::To(Binding::command_with(command, params), Some(note)) +} + +/// An imported Loupedeck profile: the bindings of the console's controls and what came over. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Imported { + /// The profile's name in Loupedeck's software. + pub name: String, + pub bindings: BTreeMap, + pub report: Report, +} + +/// The largest profile read (a Loupedeck profile is tens of kilobytes). +const MAX_BYTES: usize = 32 << 20; + +/// Read a Loupedeck profile: its `ProfileInfo.json`, or an exported `.lp5` (a ZIP holding one). +/// Only the console's main mode (the photo in the editor) and its first workspace are read; the +/// `Fn` workspace's presses go to the same controls when the main one leaves them empty. +pub fn import(bytes: &[u8], preset: &dyn Fn(&str) -> Option) -> Result { + if bytes.len() > MAX_BYTES { + return Err("This file is too large to be a Loupedeck profile.".into()); + } + let json = if bytes.starts_with(b"PK") { + crate::zip::read_member(bytes, "ProfileInfo.json").map_err(|e| format!("This .lp5 file has no profile in it: {e}"))? + } else { + bytes.to_vec() + }; + let text = String::from_utf8_lossy(&json); + let text = text.trim_start_matches('\u{feff}'); + let v: Value = serde_json::from_str(text).map_err(|e| format!("This isn't a Loupedeck profile ({e})."))?; + let device = v.get("deviceType").and_then(Value::as_str).unwrap_or_default(); + if !device.is_empty() && device != "Loupedeck15" && device != "Loupedeck10" { + return Err(format!("This profile is for another Loupedeck console ({device}); LightCraft reads Loupedeck+ profiles.")); + } + let modes = v.pointer("/layout/layoutModes").and_then(Value::as_array).ok_or("This Loupedeck profile has no layout.")?; + // the editor's own mode: `loupe` (Loupedeck's name for the develop view), else the first + let mode = modes + .iter() + .find(|m| m.get("modeName").and_then(Value::as_str) == Some("loupe")) + .or_else(|| modes.first()) + .ok_or("This Loupedeck profile has no layout.")?; + let workspaces = mode.get("workspaces").and_then(Value::as_array).cloned().unwrap_or_default(); + let mut out = Imported { name: v.get("displayName").and_then(Value::as_str).unwrap_or("Loupedeck").to_string(), ..Default::default() }; + // (control, action) of the main workspace, then the Fn workspace for what it leaves empty + let mut seen = std::collections::BTreeSet::new(); + for ws in workspaces.iter().take(2) { + for (kind, id_of) in [("rotateActions", rotate_id as fn(usize) -> String), ("pressActions", press_id as fn(usize) -> String)] { + let Some(list) = ws.get(kind).and_then(Value::as_array) else { continue }; + for (n, a) in list.iter().enumerate().take(512) { + let Some(raw) = a.as_str() else { continue }; + let control = id_of(n); + if !seen.insert(control.clone()) { + continue; + } + // `$Lightroom___Exposure`, `$@Generic___@Macro___`, `LR:Exposure` + let action = match raw.strip_prefix('$') { + // `$___`: the action without its plugin + Some(owned) => owned.split_once("___").map_or(owned, |(_, rest)| rest), + None => raw.strip_prefix("LR:").unwrap_or(raw), + }; + let from = format!("{}: {}", label(&control), pretty(action)); + match map_action(action, preset) { + Mapped::To(b, note) => { + out.report.mapped.push(ReportLine { from, to: b.describe(), note: note.unwrap_or_default().into() }); + out.bindings.insert(control, b); + } + Mapped::Dropped(why) => out.report.dropped.push(ReportLine { from, to: String::new(), note: why.into() }), + } + } + } + } + Ok(out) +} + +/// A control's printed name. +pub fn label(control: &str) -> String { + CONTROLS.iter().find(|c| c.id == control).map_or_else(|| control.to_string(), |c| c.label.to_string()) +} + +/// `ApplyDevelopPreset___Group|Name` → `ApplyDevelopPreset: Group|Name`, a macro's id dropped. +fn pretty(action: &str) -> String { + match action.split_once("___") { + Some(("@Macro", _)) => "Macro".into(), + Some((n, p)) => format!("{n}: {p}"), + None => action.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn profile(press: &[(usize, &str)], rotate: &[(usize, &str)]) -> Vec { + let mut p = vec![Value::Null; 127]; + for (i, a) in press { + p[*i] = json!(a); + } + let mut r = vec![Value::Null; 127]; + for (i, a) in rotate { + r[*i] = json!(a); + } + serde_json::to_vec(&json!({ + "displayName": "My LD+", + "deviceType": "Loupedeck15", + "layout": {"layoutModes": [ + {"modeName": "library", "workspaces": [{"pressActions": [], "rotateActions": []}]}, + {"modeName": "loupe", "workspaces": [{"pressActions": p, "rotateActions": r}]} + ]} + })) + .unwrap() + } + + #[test] + fn imports_the_editor_mode_of_a_loupedeck_profile() { + let bytes = profile( + &[ + (95, "$Lightroom___Undo"), + (67, "$Lightroom___RatingStar2"), + (80, "$Lightroom___ApplyDevelopPreset___Mine|Soft Skin"), + (76, "$@Generic___@Macro___ABC"), + ], + &[(33, "$Lightroom___Exposure"), (34, "$Lightroom___Temperature"), (9, "$Lightroom___SaturationAdjustmentRed")], + ); + let presets = |n: &str| (n == "Soft Skin").then(|| "p-1".to_string()); + let out = import(&bytes, &presets).unwrap(); + assert_eq!(out.name, "My LD+"); + assert_eq!(out.bindings.get("ld.r33"), Some(&Binding::value("light.exposure"))); + assert_eq!(out.bindings.get("ld.r34"), Some(&Binding::value("wb.temp"))); + assert_eq!(out.bindings.get("ld.r9"), Some(&Binding::value("mixer.red.sat"))); + assert_eq!(out.bindings.get("ld.b95"), Some(&Binding::command("edit.undo"))); + assert_eq!(out.bindings.get("ld.b67"), Some(&Binding::command_with("photo.rate", json!({"rating": 2})))); + assert_eq!(out.bindings.get("ld.b80"), Some(&Binding::command_with("preset.apply", json!({"id": "p-1"})))); + assert!(!out.bindings.contains_key("ld.b76"), "macros don't come along"); + assert_eq!(out.report.dropped.len(), 1); + assert!(out.report.dropped[0].from.contains("Button 76"), "{:?}", out.report.dropped); + } + + #[test] + fn bad_files_are_errors() { + assert!(import(b"not json", &|_| None).is_err()); + assert!(import(b"{}", &|_| None).is_err()); + assert!(import(br#"{"deviceType":"Loupedeck70","layout":{"layoutModes":[]}}"#, &|_| None).is_err()); + assert!(import(b"PK\x03\x04garbage", &|_| None).is_err()); + assert!(import(br#"{"layout":{"layoutModes":[{"workspaces":[{"pressActions":[1,{"a":2},null,"$Lightroom___Undo"]}]}]}}"#, &|_| None).is_ok()); + } + + #[test] + fn the_console_works_as_labelled_with_no_setup() { + assert_eq!(default_binding("ld.r33"), Some(Binding::value("light.exposure"))); + assert_eq!(default_binding("ld.r46"), Some(Binding::value("light.contrast"))); + assert_eq!(default_binding("ld.r1"), Some(Binding::value("mixer.red.hue"))); + assert_eq!(default_binding("ld.r24"), Some(Binding::value("mixer.magenta.lum"))); + assert_eq!(default_binding("ld.r32"), Some(Binding::value("bw.magenta"))); + assert_eq!(default_binding("ld.b95"), Some(Binding::command("edit.undo"))); + assert_eq!(default_binding("ld.b999"), None); + assert_eq!(default_binding("ld.rx"), None); + // every default names a known LightCraft action or value + for (control, _) in DEFAULTS { + assert!(default_binding(control).is_some(), "{control}"); + assert!(CONTROLS.iter().any(|c| c.id == *control), "{control}"); + } + } +} diff --git a/crates/surface/src/motion.rs b/crates/surface/src/motion.rs new file mode 100644 index 00000000000..4c84066732c --- /dev/null +++ b/crates/surface/src/motion.rs @@ -0,0 +1,148 @@ +//! Dial ticks to value changes: speed, the acceleration curve, modifiers and direction. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: the acceleration curve, its +//! clamps and the speed model are TactileBridge's `CaptureOneAdjustment.GetAcceleration` and +//! `ApplyAdjustment`. + +use std::collections::BTreeMap; + +use crate::binding::Modifier; +use crate::settings::{MotionSettings, Tuning}; + +/// The largest acceleration factor, whatever the multipliers say. +pub const MAX_ACCELERATION: f64 = 25.0; +/// The most ticks one input event may carry (a hostile or confused client can't jump a value +/// further than this in one go). +pub const MAX_TICKS: i32 = 1000; + +/// Remembers when each value last got a tick, to measure turning speed. +#[derive(Clone, Debug, Default)] +pub struct Accelerator { + last_tick_ms: BTreeMap, +} + +impl Accelerator { + /// The acceleration for a tick of `target` at `now_ms`: the floor when ticks are slow, the + /// ceiling when they are fast, and a quadratic curve between (calm at moderate speed, + /// explosive only near the fast end, like a mouse). + pub fn acceleration(&mut self, target: &str, now_ms: f64, tuning: &Tuning, motion: &MotionSettings) -> f64 { + let t = tuning.sanitized(); + let min = t.acceleration_min.max(0.1); + let global = if motion.acceleration.is_finite() { motion.acceleration.clamp(0.1, 4.0) } else { 1.0 }; + let max = (t.acceleration_max * t.acceleration * global).clamp(min, MAX_ACCELERATION.max(min)); + let prev = self.last_tick_ms.insert(target.to_string(), now_ms); + let Some(prev) = prev else { return min }; + let gap = now_ms - prev; + if !gap.is_finite() { + return min; + } + let (fast, slow) = (f64::from(t.fast_ms), f64::from(t.slow_ms)); + if gap >= slow { + return min; + } + if gap <= fast { + return max; + } + let x = (slow - gap) / (slow - fast); + min + (max - min) * x * x + } + + /// Forget a value's timing (its gesture ended). + pub fn reset(&mut self, target: &str) { + self.last_tick_ms.remove(target); + } +} + +/// The step factor of the held modifiers (Fine wins over Coarse when both are held). +pub fn modifier_factor(held: &[Modifier], motion: &MotionSettings) -> f64 { + let d = MotionSettings::default(); + if held.contains(&Modifier::Fine) { + if motion.fine.is_finite() { motion.fine.clamp(0.01, 1.0) } else { d.fine } + } else if held.contains(&Modifier::Coarse) { + if motion.coarse.is_finite() { motion.coarse.clamp(1.0, 20.0) } else { d.coarse } + } else { + 1.0 + } +} + +/// The value change for `ticks` of a value whose step is `step` units per tick: ticks × step × +/// speed × acceleration × modifier, turned around when inverted (global XOR per value), limited to +/// `max_delta`. Never NaN or infinite. +pub fn delta(ticks: i32, step: f64, acceleration: f64, modifier: f64, tuning: &Tuning, motion: &MotionSettings, max_delta: f64) -> f64 { + let t = tuning.sanitized(); + let ticks = ticks.clamp(-MAX_TICKS, MAX_TICKS); + let invert = motion.invert ^ t.invert; + let ticks = f64::from(if invert { -ticks } else { ticks }); + let global = if motion.speed.is_finite() { motion.speed } else { 1.0 }; + let speed = (global * t.speed).clamp(0.1, 5.0); + let d = ticks * step * speed * acceleration * modifier; + if !d.is_finite() { + return 0.0; + } + let lim = if max_delta.is_finite() && max_delta > 0.0 { max_delta } else { 0.0 }; + d.clamp(-lim, lim) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first_and_slow_ticks_get_the_floor_fast_ticks_the_ceiling() { + let (t, m) = (Tuning::default(), MotionSettings::default()); + let mut a = Accelerator::default(); + assert_eq!(a.acceleration("x", 0.0, &t, &m), 1.0, "first tick"); + assert_eq!(a.acceleration("x", 1000.0, &t, &m), 1.0, "slow"); + assert_eq!(a.acceleration("x", 1010.0, &t, &m), 10.0, "fast"); + // halfway between fast (20) and slow (200): quadratic, so a quarter of the way up + let mid = a.acceleration("x", 1010.0 + 110.0, &t, &m); + assert!((mid - (1.0 + 9.0 * 0.25)).abs() < 1e-9, "{mid}"); + // targets are timed separately + assert_eq!(a.acceleration("y", 1121.0, &t, &m), 1.0); + a.reset("x"); + assert_eq!(a.acceleration("x", 1122.0, &t, &m), 1.0); + } + + #[test] + fn ceiling_scales_with_both_multipliers_and_is_capped() { + let t = Tuning { acceleration: 4.0, acceleration_max: 15.0, ..Tuning::default() }; + let m = MotionSettings { acceleration: 4.0, ..MotionSettings::default() }; + let mut a = Accelerator::default(); + a.acceleration("x", 0.0, &t, &m); + assert_eq!(a.acceleration("x", 1.0, &t, &m), MAX_ACCELERATION); + let calm = Tuning { acceleration: 0.1, acceleration_max: 1.0, acceleration_min: 2.0, ..Tuning::default() }; + a.acceleration("y", 0.0, &calm, &m); + assert_eq!(a.acceleration("y", 1.0, &calm, &m), 2.0, "never below the floor"); + } + + #[test] + fn time_going_backwards_or_nan_is_harmless() { + let (t, m) = (Tuning::default(), MotionSettings::default()); + let mut a = Accelerator::default(); + a.acceleration("x", 100.0, &t, &m); + assert_eq!(a.acceleration("x", 50.0, &t, &m), 10.0, "negative gap counts as fast"); + assert_eq!(a.acceleration("x", f64::NAN, &t, &m), 1.0); + assert_eq!(a.acceleration("x", 10.0, &t, &m), 1.0, "after NaN: no usable gap"); + } + + #[test] + fn deltas_speed_invert_modifiers_and_limits() { + let (t, m) = (Tuning::default(), MotionSettings::default()); + assert!((delta(3, 0.01, 1.0, 1.0, &t, &m, 10.0) - 0.03).abs() < 1e-12); + let slow = Tuning { speed: 0.5, ..t.clone() }; + assert!((delta(2, 1.0, 1.0, 1.0, &slow, &m, 100.0) - 1.0).abs() < 1e-12); + let inv = Tuning { invert: true, ..t.clone() }; + assert_eq!(delta(1, 1.0, 1.0, 1.0, &inv, &m, 100.0), -1.0); + let both = MotionSettings { invert: true, ..m.clone() }; + assert_eq!(delta(1, 1.0, 1.0, 1.0, &inv, &both, 100.0), 1.0, "global XOR per value"); + assert_eq!(delta(1, 1.0, 1.0, modifier_factor(&[Modifier::Fine], &m), &t, &m, 100.0), 0.25); + assert_eq!(delta(1, 1.0, 1.0, modifier_factor(&[Modifier::Coarse, Modifier::Fine], &m), &t, &m, 100.0), 0.25); + assert_eq!(delta(1, 1.0, 1.0, modifier_factor(&[Modifier::Coarse], &m), &t, &m, 100.0), 4.0); + assert_eq!(delta(i32::MAX, 1.0, 25.0, 4.0, &t, &m, 200.0), 200.0, "limited to the range"); + assert_eq!(delta(i32::MIN, 1.0, 25.0, 4.0, &t, &m, 200.0), -200.0); + assert_eq!(delta(1, f64::NAN, 1.0, 1.0, &t, &m, 200.0), 0.0); + assert_eq!(delta(1, 1.0, 1.0, 1.0, &t, &m, f64::NAN), 0.0); + let fast_global = MotionSettings { speed: 100.0, ..m.clone() }; + assert_eq!(delta(1, 1.0, 1.0, 1.0, &t, &fast_global, 100.0), 5.0, "speed product capped at 5"); + } +} diff --git a/crates/surface/src/profile.rs b/crates/surface/src/profile.rs new file mode 100644 index 00000000000..2dd400d44a1 --- /dev/null +++ b/crates/surface/src/profile.rs @@ -0,0 +1,210 @@ +//! Pages and profiles. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT. +//! +//! A **profile** (Default, Wedding, Portrait…) is a set of **pages**. Each page binds some +//! controls; a page belongs to the key group, the dial group or both ([`PageGroup`]), and each +//! group has its own current page, so the keypad and the dialpad page separately. Controls a page +//! leaves unbound fall back to the profile's **base** bindings (the Dialpad's buttons, typically). +//! A profile's **contexts** map what LightCraft shows (`crop`, `masking.mask`, `develop.color`, +//! `dialog.export` …, see [`crate::context`]) to the pages to show there. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::binding::Binding; +use crate::devices::{PageGroup, group_of}; + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Page { + pub name: String, + /// The groups this page fills (`[keys]`, `[dials]` or both). Empty = both. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub groups: Vec, + /// Control id → binding. + pub bindings: BTreeMap, + /// Shown only when its context comes up (a tool page): paging by hand skips it. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub auto: bool, +} + +impl Page { + pub fn new(name: &str, groups: &[PageGroup], bindings: impl IntoIterator) -> Page { + Page { + name: name.to_string(), + groups: groups.to_vec(), + bindings: bindings.into_iter().map(|(k, v)| (k.to_string(), v)).collect(), + auto: false, + } + } + + /// Does this page fill `group`? + pub fn in_group(&self, group: PageGroup) -> bool { + self.groups.is_empty() || self.groups.contains(&group) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Profile { + pub name: String, + #[serde(skip_serializing_if = "String::is_empty")] + pub description: String, + /// Bindings that hold on every page unless a page binds the same control. + pub base: BTreeMap, + pub pages: Vec, + /// Context key → page names to show there (at most one per group is used). + pub contexts: BTreeMap>, +} + +impl Profile { + pub fn page(&self, name: &str) -> Option<&Page> { + self.pages.iter().find(|p| p.name == name) + } + + /// Pages of a group a user pages through by hand (not the automatic tool pages), in order. + pub fn pages_in(&self, group: PageGroup) -> impl Iterator { + self.pages.iter().filter(move |p| p.in_group(group) && !p.auto) + } + + /// The page after (`step` 1) or before (`-1`) `current` within `group`, wrapping. + pub fn step_page(&self, group: PageGroup, current: Option<&str>, step: i32) -> Option { + let names: Vec<&str> = self.pages_in(group).map(|p| p.name.as_str()).collect(); + if names.is_empty() { + return None; + } + let n = names.len() as i64; + let i = current.and_then(|c| names.iter().position(|p| *p == c)).map_or(0, |i| i as i64); + let j = (i + i64::from(step)).rem_euclid(n); + names.get(usize::try_from(j).unwrap_or(0)).map(|s| s.to_string()) + } + + /// The binding of `control` with `pages` current (group → page name): the page of the + /// control's group, else the base. + pub fn binding<'a>(&'a self, control: &str, pages: &BTreeMap) -> Option<&'a Binding> { + let group = group_of(control); + pages.get(&group).and_then(|name| self.page(name)).and_then(|p| p.bindings.get(control)).or_else(|| self.base.get(control)) + } + + /// The pages to show for `context`, by group: the context's own entry, else its parents' + /// (`masking.mask.brush` → `masking.mask` → `masking`), else `default`. + pub fn pages_for_context(&self, context: &str) -> BTreeMap { + self.context_pages(context, true) + } + + /// As [`Profile::pages_for_context`]; without `default` when `include_default` is false (the + /// pages this context asks for itself). + pub fn context_pages(&self, context: &str, include_default: bool) -> BTreeMap { + let mut out = BTreeMap::new(); + for key in crate::context::fallbacks(context) { + if !include_default && key == "default" { + break; + } + if let Some(names) = self.contexts.get(&key) { + for name in names { + let Some(page) = self.page(name) else { continue }; + for g in PageGroup::ALL { + if page.in_group(g) { + out.entry(g).or_insert_with(|| page.name.clone()); + } + } + } + } + if out.len() == PageGroup::ALL.len() { + break; + } + } + out + } + + /// Make the profile safe to use whatever a settings file says: unique page names, context + /// entries that name existing pages. + pub fn sanitize(&mut self) { + let mut seen = std::collections::BTreeSet::new(); + for (i, p) in self.pages.iter_mut().enumerate() { + if p.name.trim().is_empty() { + p.name = format!("Page {}", i + 1); + } + let base = p.name.clone(); + let mut n = 2; + while !seen.insert(p.name.clone()) { + p.name = format!("{base} {n}"); + n += 1; + } + } + let names: std::collections::BTreeSet = self.pages.iter().map(|p| p.name.clone()).collect(); + for list in self.contexts.values_mut() { + list.retain(|n| names.contains(n)); + } + self.contexts.retain(|_, l| !l.is_empty()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::binding::Binding as B; + + fn profile() -> Profile { + let mut p = Profile { + name: "T".into(), + base: [("pad.1".to_string(), B::command("edit.undo"))].into_iter().collect(), + pages: vec![ + Page::new("Cull", &[PageGroup::Keys], [("key.1", B::command("library.previous"))]), + Page::new("Edit", &[PageGroup::Keys], [("key.1", B::command("develop.copy"))]), + Page::new("Light", &[PageGroup::Dials], [("dial", B::value("light.exposure"))]), + Page { auto: true, ..Page::new("Crop", &[], [("key.1", B::command("crop.rotateAspect")), ("dial", B::value("crop.angle"))]) }, + ], + ..Default::default() + }; + p.contexts.insert("default".into(), vec!["Cull".into(), "Light".into()]); + p.contexts.insert("crop".into(), vec!["Crop".into()]); + p + } + + #[test] + fn bindings_resolve_by_group_page_then_base() { + let p = profile(); + let pages: BTreeMap<_, _> = [(PageGroup::Keys, "Edit".to_string()), (PageGroup::Dials, "Light".to_string())].into_iter().collect(); + assert_eq!(p.binding("key.1", &pages), Some(&B::command("develop.copy"))); + assert_eq!(p.binding("dial", &pages), Some(&B::value("light.exposure"))); + assert_eq!(p.binding("pad.1", &pages), Some(&B::command("edit.undo")), "base"); + assert_eq!(p.binding("key.2", &pages), None); + } + + #[test] + fn contexts_fall_back_to_parents_and_default() { + let p = profile(); + let crop = p.pages_for_context("crop"); + assert_eq!(crop.get(&PageGroup::Keys).map(String::as_str), Some("Crop")); + assert_eq!(crop.get(&PageGroup::Dials).map(String::as_str), Some("Crop"), "a page of both groups fills both"); + let d = p.pages_for_context("develop.light"); + assert_eq!(d.get(&PageGroup::Keys).map(String::as_str), Some("Cull")); + assert_eq!(d.get(&PageGroup::Dials).map(String::as_str), Some("Light")); + } + + #[test] + fn paging_wraps_within_a_group() { + let p = profile(); + assert_eq!(p.step_page(PageGroup::Keys, Some("Cull"), 1).as_deref(), Some("Edit")); + assert_eq!(p.step_page(PageGroup::Keys, Some("Edit"), 1).as_deref(), Some("Cull"), "the automatic Crop page is skipped"); + assert_eq!(p.step_page(PageGroup::Keys, Some("Cull"), -1).as_deref(), Some("Edit")); + assert_eq!(p.step_page(PageGroup::Keys, Some("Crop"), 1).as_deref(), Some("Edit"), "from an automatic page: on from the first"); + assert_eq!(p.step_page(PageGroup::Dials, None, 1).as_deref(), Some("Light"), "one dial page: stays"); + assert_eq!(Profile::default().step_page(PageGroup::Keys, None, 1), None); + } + + #[test] + fn sanitize_makes_names_unique_and_drops_dangling_contexts() { + let mut p = profile(); + p.pages.push(Page { name: "Cull".into(), ..Default::default() }); + p.pages.push(Page::default()); + p.contexts.insert("x".into(), vec!["Missing".into()]); + p.sanitize(); + let names: Vec<_> = p.pages.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Cull", "Edit", "Light", "Crop", "Cull 2", "Page 6"]); + assert!(!p.contexts.contains_key("x")); + } +} diff --git a/crates/surface/src/protocol.rs b/crates/surface/src/protocol.rs new file mode 100644 index 00000000000..14cbbdb24ff --- /dev/null +++ b/crates/surface/src/protocol.rs @@ -0,0 +1,259 @@ +//! The surface protocol's pairing: a client asks, the user approves in Settings ▸ Controls after +//! checking the code both sides show, and the client gets a token it presents from then on. +//! Only a SHA-256 of each token is stored (`control-surfaces.json` → `paired`). +//! +//! Message shapes and the method list are in `docs/control-surfaces.md`. + +use serde::Serialize; +use sha2::{Digest, Sha256}; + +use crate::settings::{PairedClient, SurfaceSettings}; + +/// The protocol version this LightCraft speaks. +pub const PROTOCOL: u32 = 1; +/// A pairing request not answered within this time is dropped (ms). +pub const REQUEST_TTL_MS: f64 = 10.0 * 60.0 * 1000.0; +/// At most this many requests wait at once (one per client). +pub const MAX_PENDING: usize = 4; +/// Client ids and names are cut to this many characters. +pub const MAX_NAME: usize = 64; + +/// Where a pairing request stands. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "status", rename_all = "camelCase")] +pub enum PairState { + /// Waiting for the user; `code` is shown on both sides. + Pending { + code: String, + }, + /// Approved: the client keeps `token` (given out once). + Approved { + token: String, + }, + Denied, +} + +/// A request waiting in Settings ▸ Controls. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PairRequest { + pub request: String, + pub client: String, + pub name: String, + pub code: String, + #[serde(skip)] + created_ms: u64, + #[serde(skip)] + state: PairState, +} + +/// Pending pairing requests (in memory; they don't survive a restart). +#[derive(Clone, Debug, Default)] +pub struct Pairing { + requests: Vec, + seed: Vec, + counter: u64, +} + +/// Lowercase hex. +pub fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// SHA-256 of a token, hex. +pub fn token_hash(token: &str) -> String { + hex(&Sha256::digest(token.as_bytes())) +} + +/// Compare without stopping at the first difference. +fn same(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// The paired client a token belongs to. +pub fn verify<'a>(settings: &'a SurfaceSettings, token: &str) -> Option<&'a PairedClient> { + if token.is_empty() || token.len() > 256 { + return None; + } + let h = token_hash(token); + let mut found = None; + for c in &settings.paired { + if same(&c.token_sha256, &h) { + found = Some(c); + } + } + found +} + +/// `s` cut to `MAX_NAME` characters, control characters removed. +pub fn clean(s: &str) -> String { + s.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect::().trim().to_string() +} + +impl Pairing { + /// `seed`: unpredictable bytes from the host (codes and tokens are derived from it). + pub fn new(seed: &[u8]) -> Pairing { + Pairing { requests: Vec::new(), seed: seed.to_vec(), counter: 0 } + } + + fn random(&mut self, salt: &[u8]) -> [u8; 32] { + self.counter = self.counter.wrapping_add(1); + let mut h = Sha256::new(); + h.update(&self.seed); + h.update(self.counter.to_le_bytes()); + h.update(salt); + h.finalize().into() + } + + /// Requests waiting for the user. + pub fn waiting(&self) -> impl Iterator { + self.requests.iter().filter(|r| matches!(r.state, PairState::Pending { .. })) + } + + /// Drop requests older than [`REQUEST_TTL_MS`]. + pub fn expire(&mut self, now_ms: u64) { + self.requests.retain(|r| (now_ms.saturating_sub(r.created_ms) as f64) < REQUEST_TTL_MS); + } + + /// A client asks to pair (`surface.pair {client, name}`): its open request, or a new one. + pub fn ask(&mut self, client: &str, name: &str, now_ms: u64) -> Result { + self.expire(now_ms); + let client = clean(client); + if client.is_empty() { + return Err("surface.pair: give a `client` id".into()); + } + if let Some(r) = self.requests.iter().find(|r| r.client == client && matches!(r.state, PairState::Pending { .. })) { + return Ok(r.clone()); + } + if self.waiting().count() >= MAX_PENDING { + return Err("surface.pair: too many pairing requests are waiting; answer them in Settings ▸ Controls first".into()); + } + let r = self.random(client.as_bytes()); + let request = hex(r.get(..8).unwrap_or(&[])); + let n = u32::from_le_bytes([r[8], r[9], r[10], r[11]]) % 1_000_000; + let code = format!("{n:06}"); + let req = PairRequest { request, client, name: clean(name), code: code.clone(), created_ms: now_ms, state: PairState::Pending { code } }; + self.requests.push(req.clone()); + Ok(req) + } + + /// Where request `id` stands (`surface.pair {request}`); an approved token is handed out once. + pub fn poll(&mut self, id: &str, now_ms: u64) -> Option { + self.expire(now_ms); + let i = self.requests.iter().position(|r| r.request == id)?; + let state = self.requests.get(i)?.state.clone(); + if !matches!(state, PairState::Pending { .. }) { + self.requests.remove(i); + } + Some(state) + } + + /// The user approved request `id`: a token for the client, its hash saved in `settings`. + pub fn approve(&mut self, id: &str, settings: &mut SurfaceSettings, now_s: u64) -> Result { + let i = + self.requests.iter().position(|r| r.request == id && matches!(r.state, PairState::Pending { .. })).ok_or("no such pairing request")?; + let (client, name) = self.requests.get(i).map(|r| (r.client.clone(), r.name.clone())).ok_or("no such pairing request")?; + let token = hex(&self.random(b"token")); + settings.paired.retain(|c| c.client != client); + settings.paired.push(PairedClient { + client: client.clone(), + name: if name.is_empty() { client } else { name }, + token_sha256: token_hash(&token), + approved_at: now_s, + }); + if let Some(r) = self.requests.get_mut(i) { + r.state = PairState::Approved { token: token.clone() }; + } + Ok(token) + } + + /// Trust a local client without asking (a plugin LightCraft installed or found installed for + /// this user): a new token, its hash saved in `settings` (any earlier token of the client + /// stops working). The host hands the token to the plugin through a file only this user can + /// read; the port stays loopback-only and the token stays required. + pub fn trust(&mut self, client: &str, name: &str, settings: &mut SurfaceSettings, now_s: u64) -> String { + let client = clean(client); + let token = hex(&self.random(b"trust")); + settings.paired.retain(|c| c.client != client); + settings.paired.push(PairedClient { client: client.clone(), name: clean(name), token_sha256: token_hash(&token), approved_at: now_s }); + // a request the client may have left waiting is answered by the token instead + self.requests.retain(|r| r.client != client); + token + } + + pub fn deny(&mut self, id: &str) -> bool { + match self.requests.iter_mut().find(|r| r.request == id && matches!(r.state, PairState::Pending { .. })) { + Some(r) => { + r.state = PairState::Denied; + true + } + None => false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trusted_local_client() { + let mut p = Pairing::new(b"seed"); + let mut s = SurfaceSettings::default(); + let waiting = p.ask("lightcraft-logi", "plugin", 0).unwrap(); + let t1 = p.trust("lightcraft-logi", "LightCraft plugin", &mut s, 5); + assert_eq!(verify(&s, &t1).map(|c| c.client.as_str()), Some("lightcraft-logi")); + assert!(p.poll(&waiting.request, 1).is_none(), "its waiting request is gone"); + let t2 = p.trust("lightcraft-logi", "LightCraft plugin", &mut s, 6); + assert_ne!(t1, t2); + assert!(verify(&s, &t1).is_none(), "the old token stops working"); + assert_eq!(s.paired.len(), 1); + assert!(!s.to_json().contains(&t2)); + } + + #[test] + fn pair_approve_verify() { + let mut p = Pairing::new(b"seed"); + let mut s = SurfaceSettings::default(); + let r = p.ask("lightcraft-logi", "Logi Actions plugin", 0).unwrap(); + assert_eq!(r.code.len(), 6); + assert_eq!(p.ask("lightcraft-logi", "again", 1).unwrap().request, r.request, "one open request per client"); + assert_eq!(p.poll(&r.request, 2), Some(PairState::Pending { code: r.code.clone() })); + let token = p.approve(&r.request, &mut s, 100).unwrap(); + assert_eq!(token.len(), 64); + assert!(!s.to_json().contains(&token), "only the hash is stored"); + assert_eq!(p.poll(&r.request, 3), Some(PairState::Approved { token: token.clone() })); + assert_eq!(p.poll(&r.request, 4), None, "handed out once"); + assert_eq!(verify(&s, &token).map(|c| c.client.as_str()), Some("lightcraft-logi")); + assert!(verify(&s, "wrong").is_none()); + assert!(verify(&s, "").is_none()); + // re-pairing the same client replaces its token + let r2 = p.ask("lightcraft-logi", "", 5).unwrap(); + let t2 = p.approve(&r2.request, &mut s, 101).unwrap(); + assert_eq!(s.paired.len(), 1); + assert!(verify(&s, &token).is_none() && verify(&s, &t2).is_some()); + // the settings file keeps it + let back = SurfaceSettings::from_json(&s.to_json()).unwrap(); + assert!(verify(&back, &t2).is_some()); + } + + #[test] + fn deny_expire_and_limits() { + let mut p = Pairing::new(b"x"); + let r = p.ask("a", "A", 0).unwrap(); + assert!(p.deny(&r.request)); + assert_eq!(p.poll(&r.request, 1), Some(PairState::Denied)); + let r = p.ask("b", "B", 0).unwrap(); + p.expire(REQUEST_TTL_MS as u64 + 1); + assert_eq!(p.poll(&r.request, REQUEST_TTL_MS as u64 + 1), None); + for c in ["c", "d", "e", "f"] { + p.ask(c, "", 0).unwrap(); + } + assert!(p.ask("g", "", 0).is_err()); + assert!(p.ask(" ", "", 0).is_err()); + assert!(p.approve("nope", &mut SurfaceSettings::default(), 0).is_err()); + let long: String = "é".repeat(500); + assert_eq!(clean(&long).chars().count(), MAX_NAME); + assert_eq!(clean("a\u{0}b\nc"), "abc"); + } +} diff --git a/crates/surface/src/runtime.rs b/crates/surface/src/runtime.rs new file mode 100644 index 00000000000..20b5fb33c2d --- /dev/null +++ b/crates/surface/src/runtime.rs @@ -0,0 +1,1074 @@ +//! The live engine: input events in, [`Effect`]s out. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: dial focus by key (the +//! "adjustment dial toggle"), tool-following pages, the coalescing flush, echo suppression and +//! Auto Sync's idle timeout come from TactileBridge (`ToolContextFolder`, `CaptureOneAdjustment`, +//! `TipcBridgeService`). +//! +//! Time is passed in (milliseconds on any monotonic clock), so everything here is deterministic +//! and testable. The host: +//! 1. calls [`Runtime::set_context`] when what the app shows changes; +//! 2. feeds surface input to [`Runtime::input`]; +//! 3. calls [`Runtime::flush`] every frame (and [`Runtime::interrupt`] when the active photo +//! changes or the app takes over the edit); +//! 4. runs the effects: `Begin`/`End` bracket one undoable gesture, `Adjust` moves a value by a +//! delta, `Command` runs a command by id. + +use std::collections::BTreeMap; + +use serde_json::Value; + +use crate::binding::{Binding, Modifier}; +use crate::devices::{PageGroup, group_of, is_encoder}; +use crate::motion::{Accelerator, delta, modifier_factor}; +use crate::profile::{Page, Profile}; +use crate::settings::SurfaceSettings; +use crate::targets::target_spec; + +/// Input from a surface. +#[derive(Clone, Debug, PartialEq)] +pub enum Input { + /// An encoder turned by `ticks` detents (positive = clockwise). + Turn { control: String, ticks: i32 }, + /// A key or button went down. `page` (1-based) is the key page the device itself shows, for + /// devices that page their keys in hardware (the MX Creative Keypad's page buttons). + Press { control: String, page: Option }, + /// A key or button came up. + Release { control: String }, +} + +/// What the host should do. +#[derive(Clone, Debug, PartialEq)] +pub enum Effect { + /// Run a command by id (engine or UI command). + Command { command: String, params: Value }, + /// A dial gesture starts on `target`: open one undo step (develop and mask values). + Begin { target: String }, + /// Move `target` by `delta` (in the target's units, already clamped to its range span). + Adjust { target: String, delta: f64 }, + /// The gesture on `target` ends: commit its undo step; with `apply_to_selected`, the change + /// goes to every selected photo in that same step. + End { target: String, apply_to_selected: bool }, + /// Put `target` back to its default (its own undo step). + Reset { target: String }, + /// The surface's own state changed (page, profile, dial focus, a toggle): push the layout + /// again; `notice` is an English line for the on-screen readout. + Changed { notice: Option }, + /// Settings changed from a key (profile, toggles): save them. + Save, +} + +/// What the on-screen readout shows. +#[derive(Clone, Debug, PartialEq)] +pub enum Shown { + /// A value being turned (the host reads its current value). + Value { target: String }, + /// A command that ran: English label and icon. + Command { label: String, icon: Option<&'static str> }, + /// A surface notice (page or profile change, a toggle): English text. + Notice { text: String }, +} + +#[derive(Clone, Debug)] +struct Gesture { + target: String, + last_input_ms: f64, + /// The way the dial last turned (the sign of its ticks). + direction: i32, +} + +/// Learn mode: the next control touched is reported instead of acting. +#[derive(Clone, Debug, Default, PartialEq)] +enum Learn { + #[default] + Off, + Armed, + Got(String), +} + +/// Commands a key runs only while it is held (pressed: `{on: true}`, released: `{on: false}`): +/// the brush's Erase works like holding Alt. +pub const MOMENTARY: &[&str] = &["brush.erase"]; + +/// Commands that destroy or discard something: a console key runs them only after being held +/// for [`HOLD_MS`] (a quick press shows "Hold to …" instead), so a stray press never deletes. +pub const HOLD_TO_RUN: &[&str] = + &["photo.delete", "photo.deletePermanently", "history.clear", "mask.deleteAll", "develop.reset", "version.delete", "preset.delete"]; + +/// How long a destructive key must be held (ms). +pub const HOLD_MS: f64 = 700.0; + +pub struct Runtime { + settings: SurfaceSettings, + /// Momentary commands running while their key is held: (control, command, params). + momentary: Vec<(String, String, Value)>, + /// A destructive key waiting to be held long enough: (control, binding, pressed at ms, label). + armed: Option<(String, Binding, f64)>, + context: String, + /// The current page of each group. + pages: BTreeMap, + /// The pages the context asks for itself (not inherited from `default`). + context_pages: BTreeMap, + /// The pages last chosen by hand (or the profile's defaults): shown again when a context + /// that asks for nothing special comes back. + manual: BTreeMap, + /// The value the dials move instead of their own (a key bound to a value was pressed). + focus: Option, + held: Vec<(String, Modifier)>, + accel: Accelerator, + pending: BTreeMap, + gesture: Option, + last_flush_ms: f64, + learn: Learn, + shown: Option<(Shown, f64)>, + revision: u64, +} + +impl Runtime { + pub fn new(settings: SurfaceSettings) -> Runtime { + let mut r = Runtime { + settings, + momentary: Vec::new(), + armed: None, + context: "default".into(), + pages: BTreeMap::new(), + context_pages: BTreeMap::new(), + manual: BTreeMap::new(), + focus: None, + held: Vec::new(), + accel: Accelerator::default(), + pending: BTreeMap::new(), + gesture: None, + last_flush_ms: f64::NEG_INFINITY, + learn: Learn::Off, + shown: None, + revision: 0, + }; + r.settings.sanitize(); + r.reset_pages(); + r + } + + pub fn settings(&self) -> &SurfaceSettings { + &self.settings + } + + /// Change settings (the editor), then [`Runtime::settings_changed`]. + pub fn settings_mut(&mut self) -> &mut SurfaceSettings { + &mut self.settings + } + + /// Settings were edited: clamp them, keep pages that still exist. + pub fn settings_changed(&mut self) { + self.settings.sanitize(); + let valid = |p: &Profile, g: PageGroup, n: &String| p.page(n).is_some_and(|pg| pg.in_group(g)); + if let Some(p) = self.settings.active_profile().cloned() { + self.manual.retain(|g, n| valid(&p, *g, n)); + self.pages.retain(|g, n| valid(&p, *g, n)); + } + let ctx = std::mem::take(&mut self.context); + self.apply_context(&ctx); + self.revision += 1; + } + + /// Replace all settings (a file was imported or reloaded). + pub fn replace_settings(&mut self, settings: SurfaceSettings) { + self.settings = settings; + self.settings.sanitize(); + self.reset_pages(); + self.revision += 1; + } + + /// Bumped whenever the layout may have changed (pages, focus, profile, settings). + pub fn revision(&self) -> u64 { + self.revision + } + + pub fn profile(&self) -> Option<&Profile> { + self.settings.active_profile() + } + + pub fn context(&self) -> &str { + &self.context + } + + /// The current page of each group. + pub fn pages(&self) -> &BTreeMap { + &self.pages + } + + /// The value the dials move instead of their own, if a key put one there. + pub fn focus(&self) -> Option<&str> { + self.focus.as_deref() + } + + /// Modifiers held right now. + pub fn held(&self) -> Vec { + self.held.iter().map(|(_, m)| *m).collect() + } + + /// The value being turned, if a gesture is in progress. + pub fn turning(&self) -> Option<&str> { + self.gesture.as_ref().map(|g| g.target.as_str()) + } + + /// While turning, values for `target` aren't sent back until every tick so far has been + /// applied (TactileBridge's echo suppression; the readout never jumps back). + pub fn holds_feedback(&self, target: &str) -> bool { + self.settings.transport.echo_suppression && self.pending.get(target).is_some_and(|d| *d != 0.0) + } + + /// What the on-screen readout shows at `now_ms`, and since when (it fades after the + /// display time). + pub fn shown(&self, now_ms: f64) -> Option<(&Shown, f64)> { + let (s, at) = self.shown.as_ref()?; + let age = now_ms - at; + (self.settings.osd.enabled && age.is_finite() && age < f64::from(self.settings.osd.display_ms) + 400.0).then_some((s, *at)) + } + + fn show(&mut self, s: Shown, now_ms: f64) { + let commands_ok = self.settings.osd.show_commands || matches!(s, Shown::Value { .. }); + if commands_ok { + self.shown = Some((s, now_ms)); + } + } + + // ------------------------------------------------------------------------------- learning + + /// The next control touched is reported by [`Runtime::take_learned`] instead of acting. + pub fn arm_learn(&mut self) { + self.learn = Learn::Armed; + } + + pub fn cancel_learn(&mut self) { + self.learn = Learn::Off; + } + + pub fn learning(&self) -> bool { + self.learn == Learn::Armed + } + + /// The control learnt, once. + pub fn take_learned(&mut self) -> Option { + match std::mem::take(&mut self.learn) { + Learn::Got(c) => Some(c), + other => { + self.learn = other; + None + } + } + } + + // ------------------------------------------------------------------------------- pages + + fn reset_pages(&mut self) { + self.manual = self.profile().map(|p| p.pages_for_context("default")).unwrap_or_default(); + self.pages.clear(); + self.focus = None; + let ctx = std::mem::take(&mut self.context); + self.apply_context(if ctx.is_empty() { "default" } else { &ctx }); + } + + fn apply_context(&mut self, key: &str) { + self.context = key.to_string(); + let Some(p) = self.profile().cloned() else { + self.pages.clear(); + self.context_pages.clear(); + return; + }; + self.context_pages = p.context_pages(key, false); + let defaults = p.pages_for_context("default"); + for g in PageGroup::ALL { + let follow = self.settings.follow_context.then(|| self.context_pages.get(&g)).flatten(); + let keep = (!self.settings.follow_context).then(|| self.pages.get(&g)).flatten(); + let name = + follow.or(keep).or(self.manual.get(&g)).or(defaults.get(&g)).cloned().or_else(|| p.pages_in(g).next().map(|pg| pg.name.clone())); + match name { + Some(n) => { + self.pages.insert(g, n); + } + None => { + self.pages.remove(&g); + } + } + } + } + + /// What the app shows changed (`crate::context::context_key`). Pages follow when Follow + /// Context is on; the dial focus is dropped either way (as TactileBridge did on a tool + /// change). Returns whether anything changed. + pub fn set_context(&mut self, key: &str) -> bool { + if key == self.context { + return false; + } + let before = (self.pages.clone(), self.focus.clone()); + self.focus = None; + self.apply_context(key); + let changed = before != (self.pages.clone(), self.focus.clone()); + if changed { + self.revision += 1; + } + changed + } + + fn page_step(&mut self, group: Option, step: i32, now_ms: f64) -> Vec { + let Some(p) = self.profile().cloned() else { return Vec::new() }; + let groups: Vec = group.map_or(PageGroup::ALL.to_vec(), |g| vec![g]); + let mut names = Vec::new(); + for g in groups { + if let Some(next) = p.step_page(g, self.pages.get(&g).map(String::as_str), step) { + self.pages.insert(g, next.clone()); + self.manual.insert(g, next.clone()); + names.push(next); + } + } + if names.is_empty() { + return Vec::new(); + } + names.dedup(); + self.focus = None; + self.revision += 1; + let text = names.join(" · "); + self.show(Shown::Notice { text: text.clone() }, now_ms); + vec![Effect::Changed { notice: Some(text) }] + } + + /// Show page `name` on the surface without a notice (the editor in Settings ▸ Controls shows + /// the device the page being edited). False when it's already shown or doesn't exist. + pub fn show_page(&mut self, name: &str) -> bool { + let Some(page) = self.profile().and_then(|p| p.page(name)).cloned() else { return false }; + let mut changed = false; + for g in PageGroup::ALL { + if page.in_group(g) && self.pages.get(&g) != Some(&page.name) { + self.pages.insert(g, page.name.clone()); + self.manual.insert(g, page.name.clone()); + changed = true; + } + } + if changed { + self.revision += 1; + } + changed + } + + fn goto_page(&mut self, name: &str, now_ms: f64) -> Vec { + let Some(page) = self.profile().and_then(|p| p.page(name)).cloned() else { return Vec::new() }; + for g in PageGroup::ALL { + if page.in_group(g) { + self.pages.insert(g, page.name.clone()); + self.manual.insert(g, page.name.clone()); + } + } + self.focus = None; + self.revision += 1; + self.show(Shown::Notice { text: page.name.clone() }, now_ms); + vec![Effect::Changed { notice: Some(page.name) }] + } + + fn switch_profile(&mut self, name: Option<&str>, now_ms: f64) -> Vec { + let names: Vec = self.settings.profiles.iter().map(|p| p.name.clone()).collect(); + let target = match name { + Some(n) => names.iter().find(|p| *p == n).cloned(), + None => { + let i = names.iter().position(|p| *p == self.settings.profile).map_or(0, |i| i + 1); + names.get(i % names.len().max(1)).cloned() + } + }; + let Some(target) = target else { return Vec::new() }; + let mut out = self.interrupt(); + self.settings.profile = target.clone(); + self.reset_pages(); + self.revision += 1; + self.show(Shown::Notice { text: target.clone() }, now_ms); + out.push(Effect::Save); + out.push(Effect::Changed { notice: Some(target) }); + out + } + + // ------------------------------------------------------------------------------- bindings + + /// The page the device shows as its key page `n` (1-based): the context's own key page while + /// one is active, else the profile's `n`-th key page. + pub fn device_key_page(&self, n: usize) -> Option<&Page> { + let p = self.profile()?; + if self.settings.follow_context + && let Some(name) = self.context_pages.get(&PageGroup::Keys) + { + return p.page(name); + } + p.pages_in(PageGroup::Keys).nth(n.checked_sub(1)?) + } + + /// How many key pages the profile has. + pub fn key_page_count(&self) -> usize { + self.profile().map_or(0, |p| p.pages_in(PageGroup::Keys).count()) + } + + /// The binding of `control` now (`page`: the device's own key page, see [`Input::Press`]). + /// Encoders bound to nothing, or a value, follow the dial focus. + pub fn binding(&self, control: &str, page: Option) -> Option { + let p = self.profile()?; + if is_encoder(control) + && let Some(f) = &self.focus + { + let own = p.binding(control, &self.pages).cloned().or_else(|| crate::loupedeck::default_binding(control)); + // a dial focus moves the dial (the first encoder) only; the others keep their values + if control == "dial" || own.is_none() { + return Some(Binding::value(f)); + } + } + if let (Some(n), PageGroup::Keys) = (page, group_of(control)) { + return self.device_key_page(n).and_then(|pg| pg.bindings.get(control)).or_else(|| p.base.get(control)).cloned(); + } + // a Loupedeck+ control nothing binds does what its label says + p.binding(control, &self.pages).cloned().or_else(|| crate::loupedeck::default_binding(control)) + } + + // ------------------------------------------------------------------------------- input + + /// Handle one input event at `now_ms`. + pub fn input(&mut self, input: Input, now_ms: f64) -> Vec { + if !self.settings.enabled { + return Vec::new(); + } + // learning, or learnt and not yet taken: input is captured, never applied (the host takes + // the control at its next frame; the last one touched wins) + if self.learn != Learn::Off { + let control = match &input { + Input::Turn { control, .. } | Input::Press { control, .. } => Some(control.clone()), + Input::Release { .. } => None, + }; + if let Some(c) = control { + self.learn = Learn::Got(c); + self.revision += 1; + return vec![Effect::Changed { notice: None }]; + } + return Vec::new(); + } + match input { + Input::Turn { control, ticks } => self.turn(&control, ticks, now_ms), + Input::Press { control, page } => self.press(&control, page, now_ms), + Input::Release { control } => { + let mut out = Vec::new(); + // a destructive key let go too soon: say how to use it, run nothing + if let Some((c, b, start)) = self.armed.take() { + if c == control { + let text = format!("Hold the key: {}", b.describe()); + self.show(Shown::Notice { text: text.clone() }, now_ms); + out.push(Effect::Changed { notice: Some(text) }); + } else { + self.armed = Some((c, b, start)); + } + } + // a momentary command ends with its key + if let Some(i) = self.momentary.iter().position(|(c, _, _)| *c == control) { + let (_, command, params) = self.momentary.remove(i); + out.push(Effect::Command { command, params: with_on(¶ms, false) }); + self.revision += 1; + out.push(Effect::Changed { notice: None }); + } + let before = self.held.len(); + self.held.retain(|(c, _)| *c != control); + if self.held.len() != before { + self.revision += 1; + out.push(Effect::Changed { notice: None }); + } + out + } + } + } + + /// An action a surface's own app put on a control (a plugin's action list: see + /// [`crate::catalog`]): turning a value moves it, pressing a value resets it, pressing anything + /// else does what a key bound to it does. + pub fn act(&mut self, b: &Binding, ticks: Option, now_ms: f64) -> Vec { + if !self.settings.enabled { + return Vec::new(); + } + match (b, ticks) { + (Binding::Value { target }, Some(t)) if t != 0 => self.turn_value(target, t, now_ms), + (Binding::Value { target }, None) => self.reset(target, now_ms), + (_, None) => self.perform("action", b, now_ms), + // other actions act once per turn event, clockwise only + (_, Some(t)) if t > 0 => self.perform("action", b, now_ms), + _ => Vec::new(), + } + } + + fn turn(&mut self, control: &str, ticks: i32, now_ms: f64) -> Vec { + if ticks == 0 { + return Vec::new(); + } + match self.binding(control, None) { + Some(Binding::Value { target }) => self.turn_value(&target, ticks, now_ms), + Some(Binding::PageNext { group }) => self.page_step(group, ticks.signum(), now_ms), + Some(Binding::PagePrevious { group }) => self.page_step(group, -ticks.signum(), now_ms), + // other bindings act once per turn event, clockwise only + Some(b) if ticks > 0 => self.perform(control, &b, now_ms), + _ => Vec::new(), + } + } + + fn turn_value(&mut self, target: &str, ticks: i32, now_ms: f64) -> Vec { + let Some(spec) = target_spec(target) else { return Vec::new() }; + let mut out = Vec::new(); + if self.gesture.as_ref().is_some_and(|g| g.target != target) { + out.extend(self.finish_gesture()); + } + if self.gesture.is_none() { + out.push(Effect::Begin { target: target.to_string() }); + } + // The dial turned back (TactileBridge's `LastInputDirection`): the new way is followed at + // once. What the old way gathered but hasn't applied yet is dropped, and the speed starts + // again from the floor, so a fast spin turned back doesn't carry on (or overshoot) first. + let direction = ticks.signum(); + let reversed = self.gesture.as_ref().is_some_and(|g| g.direction != 0 && g.direction != direction); + if reversed { + self.accel.reset(target); + if let Some(p) = self.pending.get_mut(target) { + *p = 0.0; + } + } + self.gesture = Some(Gesture { target: target.to_string(), last_input_ms: now_ms, direction }); + let tuning = self.settings.tuning_of(target); + let motion = self.settings.motion.clone(); + let acc = self.accel.acceleration(target, now_ms, &tuning, &motion); + let held = self.held(); + let d = delta(ticks, spec.step, acc, modifier_factor(&held, &motion), &tuning, &motion, spec.max_delta()); + let lim = spec.max_delta(); + let p = self.pending.entry(target.to_string()).or_insert(0.0); + *p = (*p + d).clamp(-lim, lim); + self.show(Shown::Value { target: target.to_string() }, now_ms); + out + } + + fn press(&mut self, control: &str, page: Option, now_ms: f64) -> Vec { + if is_encoder(control) { + // a dial press: its own binding (`dial.press`), else reset what the dial moves + let own = format!("{control}.press"); + if let Some(b) = self.binding(&own, None) { + return self.perform(&own, &b, now_ms); + } + return match self.binding(control, None) { + Some(Binding::Value { target }) => self.reset(&target, now_ms), + _ => Vec::new(), + }; + } + match self.binding(control, page) { + Some(b) => self.perform(control, &b, now_ms), + None => Vec::new(), + } + } + + fn reset(&mut self, target: &str, now_ms: f64) -> Vec { + let mut out = self.interrupt(); + if target_spec(target).is_some() { + self.show(Shown::Value { target: target.to_string() }, now_ms); + out.push(Effect::Reset { target: target.to_string() }); + } + out + } + + /// Do what `b` does, as if a key bound to it (`control`) were pressed (commands that page, + /// switch profiles or toggle without a key). + pub fn perform(&mut self, control: &str, b: &Binding, now_ms: f64) -> Vec { + match b { + Binding::Value { target } => { + // the adjustment dial toggle: press to put this value on the dial, again to give + // the dial back + self.focus = if self.focus.as_deref() == Some(target) { None } else { Some(target.clone()) }; + self.revision += 1; + let text = match &self.focus { + Some(t) => format!("Dial: {}", target_spec(t).map_or(t.as_str(), |s| s.label)), + None => "Dial: page".to_string(), + }; + // no readout: putting a value on the dial changes nothing in the photo (the lit key + // says it); the readout appears once the dial turns + let _ = now_ms; + vec![Effect::Changed { notice: Some(text) }] + } + Binding::Command { command, params } if MOMENTARY.contains(&command.as_str()) => { + // held: on now, off at the release (no readout: the key itself lights up) + let mut out = self.interrupt(); + self.momentary.retain(|(c, _, _)| c != control); + self.momentary.push((control.to_string(), command.clone(), params.clone())); + self.revision += 1; + out.push(Effect::Command { command: command.clone(), params: with_on(params, true) }); + out.push(Effect::Changed { notice: None }); + out + } + Binding::Command { command, .. } if HOLD_TO_RUN.contains(&command.as_str()) && control != "command" => { + // destructive: armed now, run by flush once held long enough + self.armed = Some((control.to_string(), b.clone(), now_ms)); + Vec::new() + } + Binding::Command { command, params } => { + self.show(Shown::Command { label: b.describe(), icon: crate::icons::icon_for(b) }, now_ms); + // a command may change the photo: what the dial did so far goes to this one first + let mut out = self.interrupt(); + out.push(Effect::Command { command: command.clone(), params: params.clone() }); + out + } + Binding::Modifier { modifier } => { + if !self.held.iter().any(|(c, m)| c == control && m == modifier) { + self.held.push((control.to_string(), *modifier)); + } + self.revision += 1; + vec![Effect::Changed { notice: None }] + } + Binding::PageNext { group } => self.page_step(*group, 1, now_ms), + Binding::PagePrevious { group } => self.page_step(*group, -1, now_ms), + Binding::Page { page } => self.goto_page(page, now_ms), + Binding::Profile { profile } => self.switch_profile(Some(profile), now_ms), + Binding::ProfileNext => self.switch_profile(None, now_ms), + Binding::Reset => match self.binding("dial", None) { + Some(Binding::Value { target }) => self.reset(&target, now_ms), + _ => Vec::new(), + }, + Binding::ApplyToSelected => { + self.settings.apply_to_selected = !self.settings.apply_to_selected; + self.revision += 1; + let text = format!("Apply to all selected: {}", if self.settings.apply_to_selected { "On" } else { "Off" }); + self.show(Shown::Notice { text: text.clone() }, now_ms); + vec![Effect::Save, Effect::Changed { notice: Some(text) }] + } + Binding::FollowContext => { + self.settings.follow_context = !self.settings.follow_context; + let ctx = self.context.clone(); + self.apply_context(&ctx); + self.revision += 1; + let text = format!("Pages follow the app: {}", if self.settings.follow_context { "On" } else { "Off" }); + self.show(Shown::Notice { text: text.clone() }, now_ms); + vec![Effect::Save, Effect::Changed { notice: Some(text) }] + } + } + } + + // ------------------------------------------------------------------------------- flushing + + fn finish_gesture(&mut self) -> Vec { + let Some(g) = self.gesture.take() else { return Vec::new() }; + let mut out = Vec::new(); + if let Some(d) = self.pending.remove(&g.target) + && d != 0.0 + { + out.push(Effect::Adjust { target: g.target.clone(), delta: d }); + } + self.accel.reset(&g.target); + out.push(Effect::End { target: g.target, apply_to_selected: self.settings.apply_to_selected }); + out + } + + /// Apply gathered dial movement (at most once per flush interval) and end a gesture that has + /// been idle for the gesture time. Call every frame. + pub fn flush(&mut self, now_ms: f64) -> Vec { + let mut out = Vec::new(); + if !now_ms.is_finite() { + return out; + } + let interval = f64::from(self.settings.transport.flush_ms); + if !self.pending.is_empty() && (now_ms - self.last_flush_ms >= interval || now_ms < self.last_flush_ms) { + for (target, d) in std::mem::take(&mut self.pending) { + if d != 0.0 { + out.push(Effect::Adjust { target, delta: d }); + } + } + self.last_flush_ms = now_ms; + } + // a destructive key held long enough: run it now (once) + if self.armed.as_ref().is_some_and(|(_, _, start)| now_ms - start >= HOLD_MS || now_ms < *start) + && let Some((_, b, _)) = self.armed.take() + && let Binding::Command { command, params } = &b + { + self.show(Shown::Command { label: b.describe(), icon: crate::icons::icon_for(&b) }, now_ms); + out.extend(self.interrupt()); + out.push(Effect::Command { command: command.clone(), params: params.clone() }); + } + let idle = f64::from(self.settings.transport.gesture_end_ms); + if self.pending.is_empty() && self.gesture.as_ref().is_some_and(|g| now_ms - g.last_input_ms >= idle) { + out.extend(self.finish_gesture()); + } + out + } + + /// End any gesture now, applying what is pending (the active photo changed, the app took + /// over the edit, the surface went away). + /// A momentary command (see [`MOMENTARY`]) is running on `control`: its key is held. + pub fn momentary_on(&self, control: &str) -> bool { + self.momentary.iter().any(|(c, _, _)| c == control) + } + + /// A destructive key is being held, waiting to run (see [`HOLD_TO_RUN`]). + pub fn arming(&self) -> bool { + self.armed.is_some() + } + + pub fn interrupt(&mut self) -> Vec { + let mut out: Vec = std::mem::take(&mut self.pending) + .into_iter() + .filter(|(_, d)| *d != 0.0) + .map(|(target, delta)| Effect::Adjust { target, delta }) + .collect(); + // nothing is pending now: this only ends the gesture + out.extend(self.finish_gesture()); + out + } + + /// Does anything still need frames (pending movement, an open gesture, a fading readout)? + pub fn busy(&self, now_ms: f64) -> bool { + !self.pending.is_empty() || self.gesture.is_some() || self.shown(now_ms).is_some() || self.armed.is_some() + } + + /// The modifier held on a control, if any (keys show it lit). + pub fn held_on(&self, control: &str) -> Option { + self.held.iter().find(|(c, _)| c == control).map(|(_, m)| *m) + } +} + +/// `params` with `on` set (an object; anything else becomes `{on}`). +fn with_on(params: &Value, on: bool) -> Value { + let mut m = params.as_object().cloned().unwrap_or_default(); + m.insert("on".into(), Value::Bool(on)); + Value::Object(m) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::devices::PageGroup; + use crate::profile::Page; + + fn settings() -> SurfaceSettings { + let mut p = Profile { name: "T".into(), ..Default::default() }; + p.pages.push(Page::new( + "Cull", + &[PageGroup::Keys], + [("key.1", Binding::command("library.next")), ("key.2", Binding::value("light.contrast"))], + )); + p.pages.push(Page::new("Edit", &[PageGroup::Keys], [("key.1", Binding::command("develop.copy"))])); + p.pages.push(Page::new("Light", &[PageGroup::Dials], [("dial", Binding::value("light.exposure")), ("roller", Binding::value("wb.temp"))])); + p.pages.push(Page::new("HDR", &[PageGroup::Dials], [("dial", Binding::value("light.highlights"))])); + p.pages.push(Page::new("Crop", &[], [("key.1", Binding::command("crop.rotateAspect")), ("dial", Binding::value("crop.angle"))])); + p.base.insert("pad.1".into(), Binding::Modifier { modifier: Modifier::Fine }); + p.base.insert("pad.2".into(), Binding::PageNext { group: Some(PageGroup::Dials) }); + p.base.insert("pad.3".into(), Binding::ApplyToSelected); + p.base.insert("pad.4".into(), Binding::Reset); + p.contexts.insert("default".into(), vec!["Cull".into(), "Light".into()]); + p.contexts.insert("crop".into(), vec!["Crop".into()]); + SurfaceSettings { profiles: vec![p], profile: "T".into(), enabled: true, ..SurfaceSettings::default() } + } + + fn turn(c: &str, t: i32) -> Input { + Input::Turn { control: c.into(), ticks: t } + } + fn press(c: &str) -> Input { + Input::Press { control: c.into(), page: None } + } + fn release(c: &str) -> Input { + Input::Release { control: c.into() } + } + fn adjusts(e: &[Effect]) -> f64 { + e.iter().map(|e| if let Effect::Adjust { delta, .. } = e { *delta } else { 0.0 }).sum() + } + + #[test] + fn ticks_coalesce_into_one_adjust_per_flush_and_one_gesture() { + let mut r = Runtime::new(settings()); + let e = r.input(turn("dial", 1), 0.0); + assert_eq!(e, [Effect::Begin { target: "light.exposure".into() }]); + assert!(r.input(turn("dial", 1), 300.0).is_empty(), "no second Begin"); + assert!(r.holds_feedback("light.exposure")); + let f = r.flush(300.0); + assert!((adjusts(&f) - 0.02).abs() < 1e-12, "{f:?}"); + assert!(!r.holds_feedback("light.exposure")); + // within the flush interval nothing more goes out + r.input(turn("dial", 1), 305.0); // 5 ms after the last tick: the full 10× ceiling + assert!(r.flush(306.0).is_empty()); + assert!((adjusts(&r.flush(320.0)) - 0.1).abs() < 1e-12); + // idle past the gesture time: one End + assert!(r.flush(1000.0).is_empty()); + let end = r.flush(305.0 + 800.0); + assert_eq!(end, [Effect::End { target: "light.exposure".into(), apply_to_selected: false }]); + assert!(r.flush(5000.0).is_empty()); + assert!(r.turning().is_none()); + } + + /// TactileBridge's direction rule: a dial turned back follows the new way at once — the old + /// way's ticks not applied yet are dropped and the speed starts from the floor again. + #[test] + fn a_dial_turned_back_follows_the_new_way_at_once() { + let mut r = Runtime::new(settings()); + r.input(turn("dial", 1), 0.0); + r.flush(0.0); + // a fast spin up: the ceiling (10×) + r.input(turn("dial", 1), 5.0); + r.input(turn("dial", 1), 10.0); + let up = adjusts(&r.flush(20.0)); + assert!((up - 0.2).abs() < 1e-12, "{up}"); + // more up, then back down before the next frame: down wins, at the floor speed + r.input(turn("dial", 3), 22.0); + r.input(turn("dial", -1), 25.0); + let f = r.flush(40.0); + assert!((adjusts(&f) + 0.01).abs() < 1e-12, "down at once, one step: {f:?}"); + // still the same gesture (one undo step) + assert!(f.iter().all(|e| !matches!(e, Effect::Begin { .. } | Effect::End { .. })), "{f:?}"); + assert_eq!(r.turning(), Some("light.exposure")); + } + + /// Hundreds of ticks in bursts between frames: every frame applies what came in once, nothing + /// is left behind (no backlog), and the value moves by exactly the sum of the ticks. + #[test] + fn hundreds_of_ticks_apply_once_per_frame_and_sum_exactly() { + let mut s = settings(); + // no acceleration: one step a tick + s.motion.acceleration = 0.1; + let mut r = Runtime::new(s); + let (mut total, mut ticks, mut now) = (0.0, 0i64, 0.0); + for frame in 0..100 { + // 1–7 ticks arrive within each 16 ms frame, the same way + for k in 0..(1 + frame % 7) { + r.input(turn("dial", 1), now + f64::from(k)); + ticks += 1; + } + now += 16.0; + let f = r.flush(now); + let adjust_count = f.iter().filter(|e| matches!(e, Effect::Adjust { .. })).count(); + assert_eq!(adjust_count, 1, "one apply per frame: {f:?}"); + total += adjusts(&f); + assert!(!r.holds_feedback("light.exposure"), "nothing pending after a frame"); + } + assert!(ticks >= 300); + assert!((total - 0.01 * ticks as f64).abs() < 1e-9, "{total} for {ticks} ticks"); + } + + /// A key pressed while the dial is turning runs at once (what the dial gathered goes first). + #[test] + fn a_key_press_runs_at_once_even_mid_turn() { + let mut r = Runtime::new(settings()); + r.input(turn("dial", 1), 0.0); + r.input(turn("dial", 1), 300.0); + let e = r.input(press("key.1"), 301.0); + let cmd = e.iter().position(|e| matches!(e, Effect::Command { .. })).expect("the command"); + let adj = e.iter().position(|e| matches!(e, Effect::Adjust { .. })).expect("the pending turn"); + assert!(adj < cmd, "{e:?}"); + } + + #[test] + fn erase_works_while_held_and_delete_needs_a_hold() { + let mut s = settings(); + let p = s.profiles.get_mut(0).unwrap(); + p.base.insert("key.7".into(), Binding::command("brush.erase")); + p.base.insert("key.8".into(), Binding::command("photo.delete")); + let mut r = Runtime::new(s); + // Erase: on while the key is down, off when it comes up + let e = r.input(press("key.7"), 0.0); + assert!(e.contains(&Effect::Command { command: "brush.erase".into(), params: serde_json::json!({"on": true}) }), "{e:?}"); + assert!(r.momentary_on("key.7")); + let e = r.input(release("key.7"), 300.0); + assert!(e.contains(&Effect::Command { command: "brush.erase".into(), params: serde_json::json!({"on": false}) }), "{e:?}"); + assert!(!r.momentary_on("key.7")); + // Delete: a quick press runs nothing and says to hold + assert!(r.input(press("key.8"), 1000.0).is_empty()); + assert!(r.flush(1200.0).iter().all(|e| !matches!(e, Effect::Command { .. }))); + let e = r.input(release("key.8"), 1300.0); + assert!(e.iter().all(|e| !matches!(e, Effect::Command { .. })), "{e:?}"); + assert!(matches!(r.shown(1310.0), Some((Shown::Notice { .. }, _))), "Hold to Delete"); + // held long enough: it runs, once + r.input(press("key.8"), 2000.0); + assert!(r.busy(2100.0), "frames keep coming while it is held"); + let e = r.flush(2000.0 + HOLD_MS + 1.0); + assert!(e.contains(&Effect::Command { command: "photo.delete".into(), params: Value::Null }), "{e:?}"); + assert!(r.flush(4000.0).iter().all(|e| !matches!(e, Effect::Command { .. }))); + assert!(r.input(release("key.8"), 4100.0).iter().all(|e| !matches!(e, Effect::Command { .. }))); + } + + #[test] + fn putting_a_value_on_the_dial_shows_no_readout_turning_does() { + let mut r = Runtime::new(settings()); + r.input(press("key.2"), 0.0); + r.input(release("key.2"), 10.0); + assert_eq!(r.focus(), Some("light.contrast")); + assert!(r.shown(20.0).is_none(), "no readout for picking the value"); + r.input(turn("dial", 1), 30.0); + assert!(matches!(r.shown(40.0), Some((Shown::Value { .. }, _))), "the turn shows it"); + } + + #[test] + fn actions_from_a_plugin_turn_reset_and_run() { + let mut r = Runtime::new(settings()); + let b = Binding::value("light.whites"); + assert_eq!(r.act(&b, Some(2), 0.0), [Effect::Begin { target: "light.whites".into() }]); + assert!(adjusts(&r.flush(20.0)) > 0.0); + let e = r.act(&b, None, 30.0); + assert!(e.contains(&Effect::Reset { target: "light.whites".into() }), "{e:?}"); + let e = r.act(&Binding::command("edit.undo"), None, 40.0); + assert!(e.contains(&Effect::Command { command: "edit.undo".into(), params: Value::Null }), "{e:?}"); + assert!(r.act(&Binding::command("edit.undo"), Some(-1), 50.0).is_empty(), "counter-clockwise does nothing"); + // a held modifier from an action lets go with the action's release + r.act(&Binding::Modifier { modifier: Modifier::Fine }, None, 60.0); + assert_eq!(r.held(), [Modifier::Fine]); + r.input(release("action"), 70.0); + assert!(r.held().is_empty()); + r.settings_mut().enabled = false; + assert!(r.act(&b, Some(1), 80.0).is_empty()); + } + + #[test] + fn fast_turning_accelerates() { + let mut r = Runtime::new(settings()); + r.input(turn("dial", 1), 0.0); + r.input(turn("dial", 1), 5.0); // 5 ms after: full ceiling (10×) + let f = r.flush(10.0); + assert!((adjusts(&f) - 0.11).abs() < 1e-9, "{f:?}"); + } + + #[test] + fn switching_dials_ends_the_first_gesture() { + let mut r = Runtime::new(settings()); + r.input(turn("dial", 2), 0.0); + let e = r.input(turn("roller", 1), 10.0); + assert_eq!( + e, + [ + Effect::Adjust { target: "light.exposure".into(), delta: 0.02 }, + Effect::End { target: "light.exposure".into(), apply_to_selected: false }, + Effect::Begin { target: "wb.temp".into() }, + ] + ); + } + + #[test] + fn modifiers_scale_steps_while_held() { + let mut r = Runtime::new(settings()); + r.input(press("pad.1"), 0.0); + assert_eq!(r.held(), [Modifier::Fine]); + r.input(turn("dial", 4), 1000.0); + assert!((adjusts(&r.flush(1000.0)) - 0.01).abs() < 1e-12, "4 ticks × 0.01 × ¼"); + r.input(release("pad.1"), 1001.0); + assert!(r.held().is_empty()); + } + + #[test] + fn a_key_bound_to_a_value_puts_it_on_the_dial_and_back() { + let mut r = Runtime::new(settings()); + let rev = r.revision(); + r.input(press("key.2"), 0.0); + assert_eq!(r.focus(), Some("light.contrast")); + assert!(r.revision() > rev); + assert_eq!(r.binding("dial", None), Some(Binding::value("light.contrast"))); + assert_eq!(r.binding("roller", None), Some(Binding::value("wb.temp")), "the roller keeps its own"); + assert_eq!(r.input(turn("dial", 1), 10.0), [Effect::Begin { target: "light.contrast".into() }]); + r.input(press("key.2"), 20.0); + assert_eq!(r.focus(), None); + // a context change drops the focus too + r.input(press("key.2"), 30.0); + r.set_context("crop"); + assert_eq!(r.focus(), None); + } + + #[test] + fn pages_follow_context_and_come_back_to_the_hand_picked_ones() { + let mut r = Runtime::new(settings()); + assert_eq!(r.pages()[&PageGroup::Dials], "Light"); + r.input(press("pad.2"), 0.0); // next dial page + assert_eq!(r.pages()[&PageGroup::Dials], "HDR"); + assert!(r.set_context("crop")); + assert_eq!((r.pages()[&PageGroup::Keys].as_str(), r.pages()[&PageGroup::Dials].as_str()), ("Crop", "Crop")); + assert_eq!(r.binding("key.1", Some(2)), Some(Binding::command("crop.rotateAspect")), "a context page fills every device page"); + r.set_context("develop.light"); + assert_eq!((r.pages()[&PageGroup::Keys].as_str(), r.pages()[&PageGroup::Dials].as_str()), ("Cull", "HDR")); + assert_eq!(r.binding("key.1", Some(2)), Some(Binding::command("develop.copy")), "device page 2 = second key page"); + assert_eq!(r.binding("key.1", Some(9)), None); + // follow off: contexts don't move pages + r.input(Input::Press { control: "x".into(), page: None }, 0.0); + r.settings_mut().follow_context = false; + r.settings_changed(); + r.set_context("crop"); + assert_eq!(r.pages()[&PageGroup::Keys], "Cull"); + } + + #[test] + fn commands_toggles_and_dial_press() { + let mut r = Runtime::new(settings()); + assert_eq!(r.input(press("key.1"), 0.0), [Effect::Command { command: "library.next".into(), params: Value::Null }]); + assert!(matches!(r.shown(100.0), Some((Shown::Command { .. }, _)))); + assert!(r.shown(100_000.0).is_none(), "the readout times out"); + let e = r.input(press("pad.3"), 0.0); + assert!(r.settings().apply_to_selected && e.contains(&Effect::Save)); + r.input(turn("dial", 1), 10.0); + let e = r.interrupt(); + assert_eq!(e.last(), Some(&Effect::End { target: "light.exposure".into(), apply_to_selected: true })); + assert_eq!(r.input(press("dial"), 20.0), [Effect::Reset { target: "light.exposure".into() }]); + assert_eq!(r.input(press("pad.4"), 30.0), [Effect::Reset { target: "light.exposure".into() }]); + assert!(r.input(press("key.9"), 0.0).is_empty(), "unbound"); + } + + #[test] + fn interrupt_applies_pending_and_ends() { + let mut r = Runtime::new(settings()); + r.input(turn("dial", 3), 0.0); + let e = r.interrupt(); + assert_eq!(e.len(), 2); + assert!((adjusts(&e) - 0.03).abs() < 1e-12); + assert!(r.interrupt().is_empty()); + assert!(!r.busy(1e9)); + } + + #[test] + fn learn_mode_reports_the_control_instead_of_acting() { + let mut r = Runtime::new(settings()); + r.arm_learn(); + assert!(r.learning()); + assert_eq!(r.input(press("key.1"), 0.0), [Effect::Changed { notice: None }]); + assert_eq!(r.take_learned().as_deref(), Some("key.1")); + assert_eq!(r.take_learned(), None); + assert_eq!(r.input(press("key.1"), 0.0).len(), 1, "acts again"); + } + + #[test] + fn learnt_and_not_yet_taken_still_captures_input() { + // Touch to find: a dial still turning after it was learnt, before the editor's next frame, + // must not move the photo; the last control touched is the one reported + let mut r = Runtime::new(settings()); + r.arm_learn(); + r.input(Input::Turn { control: "dial".into(), ticks: 1 }, 0.0); + let more = r.input(Input::Turn { control: "dial".into(), ticks: 5 }, 10.0); + assert!(!more.iter().any(|e| matches!(e, Effect::Command { .. } | Effect::Begin { .. } | Effect::Adjust { .. })), "{more:?}"); + r.input(press("key.4"), 20.0); + assert_eq!(r.take_learned().as_deref(), Some("key.4")); + assert!(r.turning().is_none(), "nothing was applied"); + } + + #[test] + fn disabled_surfaces_do_nothing_and_hostile_input_is_harmless() { + let mut r = Runtime::new(settings()); + r.input(turn("dial", i32::MAX), 0.0); + let f = r.flush(0.0); + assert!(adjusts(&f).abs() <= 10.0, "limited to the exposure range span"); + assert!(r.input(turn("nope", 5), 0.0).is_empty()); + assert!(r.input(turn("dial", 0), 0.0).is_empty()); + assert!(r.flush(f64::NAN).is_empty()); + r.settings_mut().enabled = false; + assert!(r.input(press("key.1"), 0.0).is_empty()); + } + + #[test] + fn profiles_switch_and_pages_reset() { + let mut s = settings(); + let mut q = s.profiles[0].clone(); + q.name = "Q".into(); + s.profiles.push(q); + let mut r = Runtime::new(s); + r.input(press("pad.2"), 0.0); + let e = r.perform("x", &Binding::ProfileNext, 10.0); + assert!(e.contains(&Effect::Save)); + assert_eq!(r.settings().profile, "Q"); + assert_eq!(r.pages()[&PageGroup::Dials], "Light", "a new profile starts on its default pages"); + r.perform("x", &Binding::Profile { profile: "T".into() }, 20.0); + assert_eq!(r.settings().profile, "T"); + assert!(r.perform("x", &Binding::Profile { profile: "missing".into() }, 30.0).is_empty()); + let e = r.perform("x", &Binding::Page { page: "Edit".into() }, 40.0); + assert_eq!(e, [Effect::Changed { notice: Some("Edit".into()) }]); + assert_eq!(r.pages()[&PageGroup::Keys], "Edit"); + } +} diff --git a/crates/surface/src/settings.rs b/crates/surface/src/settings.rs new file mode 100644 index 00000000000..75ce123b75b --- /dev/null +++ b/crates/surface/src/settings.rs @@ -0,0 +1,484 @@ +//! Everything the user tunes about control surfaces, saved as `control-surfaces.json` in +//! LightCraft's settings folder (format: `docs/control-surfaces.md` → Settings file). +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: the tuning model, its +//! defaults, ranges and the workflow presets come from TactileBridge's `TactileBridgeSettings`. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::profile::Profile; + +/// The settings file's format version. +/// 2: `dial` / `roller` name the Dialpad's encoders as they are (format 1 had them the wrong +/// way round: the Logi device's encoder 0 is the roller); format 1 files are swapped on load, so +/// every encoder keeps doing what it did. +/// 3: the brush's Erase key is the momentary `brush.erase` (format 2 had a subtracting new brush, +/// `tool.brush {op: subtract}`, from TactileBridge's Erase Mask Tool). +pub const FORMAT_VERSION: u32 = 3; +/// The port surfaces connect to by default. +pub const DEFAULT_PORT: u16 = 7981; + +/// Per-value dial feel (TactileBridge's `AdjustmentTuning`). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Tuning { + /// Multiplies the step per tick (0.1–5). + pub speed: f64, + /// Multiplies the acceleration ceiling (0.1–4). + pub acceleration: f64, + /// Acceleration when turning slowly (0.1–10). + pub acceleration_min: f64, + /// Acceleration when turning fast (≥ the floor, ≤ 15). + pub acceleration_max: f64, + /// Ticks closer together than this (ms) get the full ceiling (5–250). + pub fast_ms: u32, + /// Ticks further apart than this (ms) get the floor (fast + 10 – 1200). + pub slow_ms: u32, + /// Turn the other way for this value (combines with the global invert). + pub invert: bool, +} + +impl Default for Tuning { + fn default() -> Self { + Tuning { speed: 1.0, acceleration: 1.0, acceleration_min: 1.0, acceleration_max: 10.0, fast_ms: 20, slow_ms: 200, invert: false } + } +} + +fn clamp(v: f64, lo: f64, hi: f64, default: f64) -> f64 { + if v.is_finite() { v.clamp(lo, hi.max(lo)) } else { default } +} + +impl Tuning { + /// The tuning within TactileBridge's ranges (a hand-edited or imported file can say anything). + pub fn sanitized(&self) -> Tuning { + let d = Tuning::default(); + let fast = self.fast_ms.clamp(5, 250); + let min = clamp(self.acceleration_min, 0.1, 10.0, d.acceleration_min); + Tuning { + speed: clamp(self.speed, 0.1, 5.0, d.speed), + acceleration: clamp(self.acceleration, 0.1, 4.0, d.acceleration), + acceleration_min: min, + acceleration_max: clamp(self.acceleration_max, min, 15.0, d.acceleration_max.max(min)), + fast_ms: fast, + slow_ms: self.slow_ms.clamp(fast + 10, 1200), + invert: self.invert, + } + } +} + +/// TactileBridge's workflow presets, applied to every value at once (Settings ▸ Controls ▸ Dial +/// feel). Name, English description, tuning. +pub fn tuning_presets() -> Vec<(&'static str, &'static str, Tuning)> { + let t = |speed, acceleration, acceleration_max, fast_ms, slow_ms| Tuning { + speed, + acceleration, + acceleration_min: 1.0, + acceleration_max, + fast_ms, + slow_ms, + invert: false, + }; + vec![ + ("Wedding", "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.", t(0.7, 0.8, 4.0, 40, 280)), + ("Real Estate", "Balanced: a standard dial feel with responsive mid-range acceleration.", t(1.0, 1.0, 10.0, 20, 180)), + ("Fashion", "Bold and expressive: faster response with strong acceleration for dynamic edits.", t(1.3, 1.2, 14.0, 16, 150)), + // TactileBridge asked for an 18× ceiling; its own clamp made it 15× + ("Landscape", "Wide range: slow base speed with a very high peak for sweeping adjustments.", t(0.6, 1.5, 15.0, 12, 200)), + ] +} + +/// How dials turn values. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct MotionSettings { + /// Multiplies every step (0.1–5). + pub speed: f64, + /// Multiplies every acceleration ceiling (0.1–4). + pub acceleration: f64, + /// Turn every dial the other way. + pub invert: bool, + /// Step factor while a Fine modifier is held. + pub fine: f64, + /// Step factor while a Coarse modifier is held. + pub coarse: f64, +} + +impl Default for MotionSettings { + fn default() -> Self { + MotionSettings { speed: 1.0, acceleration: 1.0, invert: false, fine: 0.25, coarse: 4.0 } + } +} + +/// Timing of the pipe from dial to photo. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct TransportSettings { + /// Dial movement is gathered and applied at most this often (ms, 8–100). + pub flush_ms: u32, + /// While turning, values sent back to the surface are held until every tick so far has been + /// applied, so the readout never jumps back. + pub echo_suppression: bool, + /// How long after the last tick the readout counts as "turning" (ms, 0–1000). + pub echo_suppression_ms: u32, + /// A dial gesture ends (one undo step; Apply to Selected copies it over) after this long + /// without ticks (ms, 200–10000). + pub gesture_end_ms: u32, +} + +impl Default for TransportSettings { + fn default() -> Self { + TransportSettings { flush_ms: 16, echo_suppression: true, echo_suppression_ms: 100, gesture_end_ms: 800 } + } +} + +/// Where the on-screen readout appears. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum OsdPosition { + /// Above the bottom edge. + #[default] + Bottom, + /// At the bottom edge. + BottomEdge, + /// Below the top edge. + Top, + /// At the top edge. + TopEdge, +} + +/// The on-screen readout in the LightCraft window (TactileBridge's OSD). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct OsdSettings { + pub enabled: bool, + /// 0.1–1. + pub opacity: f64, + /// `#RRGGBB`. + pub background: String, + /// How long it stays (ms, 500–10000), then fades. + pub display_ms: u32, + pub position: OsdPosition, + /// Also show commands (key presses), not only dial values. + pub show_commands: bool, +} + +impl Default for OsdSettings { + fn default() -> Self { + OsdSettings { + enabled: true, + opacity: 0.9, + background: "#202020".into(), + display_ms: 1800, + position: OsdPosition::Bottom, + show_commands: true, + } + } +} + +/// What the surface itself shows (TactileBridge's plugin colours and hardware switches). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct DeviceLook { + /// Key background, `#RRGGBB`. + pub background: String, + /// Text, value and accent colour, `#RRGGBB`. + pub foreground: String, + /// Show live values on keys and the dial display. + pub show_values: bool, + /// Haptic feedback where the device supports it. + pub haptics: bool, +} + +impl Default for DeviceLook { + fn default() -> Self { + DeviceLook { background: "#000000".into(), foreground: "#FFFFFF".into(), show_values: true, haptics: true } + } +} + +/// A surface client the user approved (Settings ▸ Controls ▸ Paired surfaces). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct PairedClient { + /// The client's own id (`lightcraft-logi`). + pub client: String, + /// Its display name. + pub name: String, + /// SHA-256 of the token it was given (hex). The token itself is never stored here. + pub token_sha256: String, + /// When it was approved (Unix seconds). + pub approved_at: u64, +} + +/// The whole settings file. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct SurfaceSettings { + pub version: u32, + /// Surfaces may connect and drive the app. Off by default; turned on by itself when a + /// surface plugin is installed (the Logi Options+ plugin), unless the user turned it off. + pub enabled: bool, + /// The user switched control surfaces off: never turn them on by themselves again. + pub off_by_user: bool, + /// Dialogs put their own page on the keys (OK / Cancel…). Off by default: the keys keep the + /// page you work with while a dialog is open. + pub dialog_pages: bool, + /// The loopback port surfaces connect to while enabled (the surfaces-only listener). + pub port: u16, + /// The profile in use (by name). + pub profile: String, + /// Pages follow what the app shows (TactileBridge's automatic tool switching). + pub follow_context: bool, + /// Dials change every selected photo, one undo step per gesture (TactileBridge's Auto Sync). + pub apply_to_selected: bool, + pub motion: MotionSettings, + /// Target id → its own tuning; values not listed use the default tuning. + pub tuning: BTreeMap, + pub transport: TransportSettings, + pub osd: OsdSettings, + pub look: DeviceLook, + pub profiles: Vec, + pub paired: Vec, +} + +impl Default for SurfaceSettings { + fn default() -> Self { + SurfaceSettings { + version: FORMAT_VERSION, + enabled: false, + off_by_user: false, + dialog_pages: false, + port: DEFAULT_PORT, + profile: "Default".into(), + follow_context: true, + apply_to_selected: false, + motion: MotionSettings::default(), + tuning: BTreeMap::new(), + transport: TransportSettings::default(), + osd: OsdSettings::default(), + look: DeviceLook::default(), + profiles: crate::defaults::profiles(), + paired: Vec::new(), + } + } +} + +/// `#RRGGBB` (or `RRGGBB`), else `fallback`. +pub fn hex_color(s: &str, fallback: &str) -> String { + let t = s.trim().trim_start_matches('#'); + if t.len() == 6 && t.chars().all(|c| c.is_ascii_hexdigit()) { format!("#{}", t.to_ascii_uppercase()) } else { fallback.to_string() } +} + +/// `#RRGGBB` → (r, g, b). +pub fn rgb(s: &str) -> Option<(u8, u8, u8)> { + let t = s.trim().trim_start_matches('#'); + if t.len() != 6 || !t.is_ascii() { + return None; + } + let p = |i: usize| t.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + Some((p(0)?, p(2)?, p(4)?)) +} + +impl SurfaceSettings { + /// Parse a settings file. A damaged or newer file is an error the caller shows (it keeps the + /// file and runs on defaults); values out of range are clamped. + pub fn from_json(text: &str) -> Result { + if !text.trim_start().starts_with('{') { + return Err("control-surfaces.json can't be read: it is not a settings object".into()); + } + let mut s: SurfaceSettings = serde_json::from_str(text).map_err(|e| format!("control-surfaces.json can't be read: {e}"))?; + if s.version > FORMAT_VERSION { + return Err(format!("control-surfaces.json is from a newer LightCraft (format {}, this one reads {FORMAT_VERSION})", s.version)); + } + if s.version < 2 { + for p in &mut s.profiles { + swap_encoders(&mut p.base); + for pg in &mut p.pages { + swap_encoders(&mut pg.bindings); + } + } + } + if s.version < 3 { + let erase = crate::binding::Binding::command_with("tool.brush", serde_json::json!({"op": "subtract"})); + for p in &mut s.profiles { + for b in p.base.values_mut().chain(p.pages.iter_mut().flat_map(|pg| pg.bindings.values_mut())) { + if *b == erase { + *b = crate::binding::Binding::command("brush.erase"); + } + } + } + } + s.sanitize(); + Ok(s) + } + + pub fn to_json(&self) -> String { + serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".into()) + } + + /// Clamp every value into range and repair references, whatever the file said. + pub fn sanitize(&mut self) { + let d = MotionSettings::default(); + self.version = FORMAT_VERSION; + if self.port < 1024 { + self.port = DEFAULT_PORT; + } + self.motion.speed = clamp(self.motion.speed, 0.1, 5.0, d.speed); + self.motion.acceleration = clamp(self.motion.acceleration, 0.1, 4.0, d.acceleration); + self.motion.fine = clamp(self.motion.fine, 0.01, 1.0, d.fine); + self.motion.coarse = clamp(self.motion.coarse, 1.0, 20.0, d.coarse); + for t in self.tuning.values_mut() { + *t = t.sanitized(); + } + let tr = &mut self.transport; + tr.flush_ms = tr.flush_ms.clamp(8, 100); + tr.echo_suppression_ms = tr.echo_suppression_ms.min(1000); + tr.gesture_end_ms = tr.gesture_end_ms.clamp(200, 10_000); + let osd = &mut self.osd; + osd.opacity = clamp(osd.opacity, 0.1, 1.0, 0.9); + osd.display_ms = osd.display_ms.clamp(500, 10_000); + osd.background = hex_color(&osd.background, "#202020"); + self.look.background = hex_color(&self.look.background, "#000000"); + self.look.foreground = hex_color(&self.look.foreground, "#FFFFFF"); + if self.profiles.is_empty() { + self.profiles = crate::defaults::profiles(); + } + // the Actions Ring came later: profiles saved before it get its default slots (once: a + // ring set up anywhere is the user's own) + if !self.profiles.iter().any(|p| p.base.keys().any(|c| c.starts_with("ring."))) { + for p in &mut self.profiles { + for (c, b) in crate::defaults::ring() { + p.base.entry(c).or_insert(b); + } + } + } + let mut seen = std::collections::BTreeSet::new(); + for (i, p) in self.profiles.iter_mut().enumerate() { + if p.name.trim().is_empty() { + p.name = format!("Profile {}", i + 1); + } + let base = p.name.clone(); + let mut n = 2; + while !seen.insert(p.name.clone()) { + p.name = format!("{base} {n}"); + n += 1; + } + p.sanitize(); + } + if !self.profiles.iter().any(|p| p.name == self.profile) { + self.profile = self.profiles.first().map(|p| p.name.clone()).unwrap_or_default(); + } + self.paired.retain(|c| c.token_sha256.len() == 64 && c.token_sha256.chars().all(|c| c.is_ascii_hexdigit())); + } + + pub fn active_profile(&self) -> Option<&Profile> { + self.profiles.iter().find(|p| p.name == self.profile).or(self.profiles.first()) + } + + /// The tuning of a target (its own, else the default). + pub fn tuning_of(&self, target: &str) -> Tuning { + self.tuning.get(target).map(Tuning::sanitized).unwrap_or_default() + } +} + +/// Exchange the dial's and the roller's bindings (format 1 → 2). +fn swap_encoders(map: &mut BTreeMap) { + for (a, b) in [("dial", "roller"), ("dial.press", "roller.press")] { + let x = map.remove(a); + let y = map.remove(b); + if let Some(v) = x { + map.insert(b.to_string(), v); + } + if let Some(v) = y { + map.insert(a.to_string(), v); + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn format_2_files_get_the_momentary_erase() { + let mut v = serde_json::to_value(SurfaceSettings::default()).unwrap(); + v["version"] = serde_json::json!(2); + v["profiles"][0]["base"]["key.2"] = serde_json::json!({"kind": "command", "command": "tool.brush", "params": {"op": "subtract"}}); + let s = SurfaceSettings::from_json(&v.to_string()).unwrap(); + assert_eq!(s.profiles[0].base["key.2"], crate::Binding::command("brush.erase")); + } + + #[test] + fn format_1_files_swap_the_dial_and_the_roller() { + let mut v = serde_json::to_value(SurfaceSettings::default()).unwrap(); + v["version"] = serde_json::json!(1); + let p = v["profiles"][0]["pages"].as_array_mut().unwrap().iter_mut().find(|p| p["name"] == "Dial Page").unwrap(); + p["bindings"] = serde_json::json!({"dial": {"kind": "value", "target": "light.exposure"}, "roller": {"kind": "value", "target": "wb.temp"}}); + let s = SurfaceSettings::from_json(&v.to_string()).unwrap(); + let pg = s.profiles[0].page("Dial Page").unwrap(); + assert_eq!(pg.bindings["roller"], crate::Binding::value("light.exposure"), "what encoder 0 did, it still does"); + assert_eq!(pg.bindings["dial"], crate::Binding::value("wb.temp")); + assert_eq!(s.version, FORMAT_VERSION); + // a format 2 file is left alone + let again = SurfaceSettings::from_json(&s.to_json()).unwrap(); + assert_eq!(again.profiles[0].page("Dial Page").unwrap().bindings["roller"], crate::Binding::value("light.exposure")); + } + + use super::*; + + #[test] + fn defaults_round_trip() { + let s = SurfaceSettings::default(); + let back = SurfaceSettings::from_json(&s.to_json()).unwrap(); + assert_eq!(back, s); + assert!(s.active_profile().is_some()); + } + + #[test] + fn hostile_values_are_clamped() { + let text = r##"{"motion": {"speed": 1e300, "acceleration": -4, "fine": 0, "coarse": 1000}, + "tuning": {"light.exposure": {"speed": "NaN", "fastMs": 1, "slowMs": 0, "accelerationMin": 50, "accelerationMax": 0}}, + "transport": {"flushMs": 0, "gestureEndMs": 4294967295}, + "osd": {"opacity": 7, "background": "zzz", "displayMs": 1}, + "look": {"foreground": "#12345g"}, + "profile": "missing", + "profiles": [{"name": ""}, {"name": ""}], + "paired": [{"client": "x", "tokenSha256": "short"}]}"##; + // "NaN" is not a number: the file is rejected rather than half-read + assert!(SurfaceSettings::from_json(text).is_err()); + let text = text.replace("\"NaN\"", "1e9"); + let s = SurfaceSettings::from_json(&text).unwrap(); + assert_eq!((s.motion.speed, s.motion.acceleration, s.motion.fine, s.motion.coarse), (5.0, 0.1, 0.01, 20.0)); + let t = &s.tuning["light.exposure"]; + assert_eq!((t.speed, t.fast_ms, t.slow_ms, t.acceleration_min, t.acceleration_max), (5.0, 5, 15, 10.0, 10.0)); + assert_eq!((s.transport.flush_ms, s.transport.gesture_end_ms), (8, 10_000)); + assert_eq!((s.osd.opacity, s.osd.background.as_str(), s.osd.display_ms), (1.0, "#202020", 500)); + assert_eq!(s.look.foreground, "#FFFFFF"); + assert_eq!(s.profiles.iter().map(|p| p.name.as_str()).collect::>(), ["Profile 1", "Profile 2"]); + assert_eq!(s.profile, "Profile 1"); + assert!(s.paired.is_empty()); + } + + #[test] + fn newer_or_damaged_files_are_errors() { + assert!(SurfaceSettings::from_json("{\"version\": 99}").unwrap_err().contains("newer")); + assert!(SurfaceSettings::from_json("{").is_err()); + assert!(SurfaceSettings::from_json("[]").is_err()); + assert_eq!(SurfaceSettings::from_json("{}").unwrap().profiles.len(), crate::defaults::profiles().len()); + } + + #[test] + fn colours() { + assert_eq!(hex_color("ff7800", "#000000"), "#FF7800"); + assert_eq!(hex_color("#ff78", "#000000"), "#000000"); + assert_eq!(rgb("#FF7800"), Some((255, 120, 0))); + assert_eq!(rgb("#ÿÿÿ"), None); + assert_eq!(rgb(""), None); + } + + #[test] + fn presets_are_in_range() { + for (_, _, t) in tuning_presets() { + assert_eq!(t.sanitized(), t); + } + } +} diff --git a/crates/surface/src/tactilebridge.rs b/crates/surface/src/tactilebridge.rs new file mode 100644 index 00000000000..c86fee58941 --- /dev/null +++ b/crates/surface/src/tactilebridge.rs @@ -0,0 +1,1051 @@ +//! Bring a TactileBridge setup over: its `settings.json` (dial feel, OSD, colours, tool contexts, +//! Auto Sync) and its Logi profiles (`.lp5`), with every TactileBridge action mapped to a +//! LightCraft binding or reported as having no LightCraft counterpart. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: the action keys, groups, +//! default tool contexts and curated layouts are TactileBridge's. Capture One's own control ids +//! and anything learnt from its files are not used: actions are mapped by their TactileBridge +//! names only. + +use std::collections::BTreeMap; + +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::binding::Binding; +use crate::devices::PageGroup; +use crate::profile::{Page, Profile}; +use crate::settings::{OsdPosition, SurfaceSettings, Tuning, hex_color}; + +/// Is it a dial value or a key action in TactileBridge? +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum TbKind { + Adjustment, + Command, +} + +/// Where a TactileBridge action goes in LightCraft. +#[derive(Clone, Debug, PartialEq)] +pub enum Mapped { + /// The LightCraft binding, with a note when the match is not exact. + To(Binding, Option<&'static str>), + /// No LightCraft counterpart, and why. + Dropped(&'static str), +} + +/// TactileBridge's dial values (its `KnownAdjustmentGroups`, plus the Color Editor values). +pub const ADJUSTMENTS: &[&str] = &[ + "Kelvin", + "Tint", + "Exposure", + "Contrast", + "Brightness", + "Saturation", + "Highlight", + "Shadow", + "White", + "Black", + "MasterToneX", + "MasterToneY", + "ShadowToneX", + "ShadowToneY", + "ShadowLightness", + "MidtoneToneX", + "MidtoneToneY", + "MidtoneLightness", + "HighlightToneX", + "HighlightToneY", + "HighlightLightness", + "BWRed", + "BWYellow", + "BWGreen", + "BWCyan", + "BWBlue", + "BWMagenta", + "BWHighlightsHue", + "BWHighlightsSat", + "BWShadowsHue", + "BWShadowsSat", + "Clarity", + "Structure", + "Vignetting", + "Distortion", + "SharpnessFalloff", + "LightFalloff", + "Defringe", + "UniformLight", + "SharpeningAmount", + "SharpeningRadius", + "SharpeningThreshold", + "SharpeningHalo", + "NRLuminance", + "NRDetail", + "NRColor", + "NRSinglePixel", + "GrainImpact", + "GrainGranularity", + "MoireAmount", + "MoirePattern", + "LayerOpacity", + "SpotRadius", + "BrushSize", + "BrushHardness", + "BrushOpacity", + "BrushFlow", + "Zoom", + "OverlayOpacity", + "OverlayScale", + "OverlayHorizontal", + "OverlayVertical", + "PenSize", + "CERedHue", + "CERedSat", + "CERedLight", + "CEOrangeHue", + "CEOrangeSat", + "CEOrangeLight", + "CEYellowHue", + "CEYellowSat", + "CEYellowLight", + "CEGreenHue", + "CEGreenSat", + "CEGreenLight", + "CECyanHue", + "CECyanSat", + "CECyanLight", + "CEBlueHue", + "CEBlueSat", + "CEBlueLight", + "CEPurpleHue", + "CEPurpleSat", + "CEPurpleLight", + "CEMagentaHue", + "CEMagentaSat", + "CEMagentaLight", +]; + +/// TactileBridge's key actions (its `KnownCommandGroups`). +pub const COMMANDS: &[&str] = &[ + "ClearRating", + "Rate1Star", + "Rate2Stars", + "Rate3Stars", + "Rate4Stars", + "Rate5Stars", + "ColorTagNone", + "ColorTagRed", + "ColorTagOrange", + "ColorTagYellow", + "ColorTagGreen", + "ColorTagBlue", + "ColorTagPink", + "ColorTagPurple", + "PreviousImage", + "NextImage", + "FirstImage", + "LastImage", + "SelectAll", + "DeselectAll", + "InvertSelection", + "SelectPrimaryOnly", + "DeselectPrimary", + "SelectSameColorTag", + "SelectSameSequenceId", + "SelectSameVariantPos", + "PreviousSet", + "NextSet", + "PreviousCollection", + "NextCollection", + "Undo", + "Redo", + "ResetAdjustments", + "CopyAdjustments", + "ApplyAdjustments", + "CopyAndApplyAdj", + "AutoAdjust", + "RotateLeft", + "RotateRight", + "SnapTo90", + "NewEmptyLayer", + "NewFilledLayer", + "NewCloneLayer", + "NewHealLayer", + "RemoveLayer", + "SelectLayerUp", + "SelectLayerDown", + "SelectBackground", + "ToggleLayerOnOff", + "InvertMask", + "FillMask", + "ClearMask", + "RasterizeMask", + "RefineMask", + "FeatherMask", + "LumaRange", + "ToggleSelectionPoints", + "ZoomIn", + "ZoomOut", + "ZoomToFit", + "Zoom100", + "Zoom200", + "Zoom400", + "IncreaseZoom", + "DecreaseZoom", + "ToggleMultiView", + "ToggleExposureWarn", + "ToggleFocusMask", + "ToggleOverlay", + "ToggleBeforeAfter", + "ShowGuides", + "ShowGrid", + "RecipeProofing", + "FullScreen", + "SlideShow", + "ShowHideViewer", + "ShowHideBrowser", + "ToggleTools", + "SelectTool", + "MoveTool", + "PanTool", + "ZoomInTool", + "ZoomOutTool", + "CropTool", + "SwitchCropOrientation", + "StraightenTool", + "RotateFreehandTool", + "SpotRemovalTool", + "WBPickerTool", + "ApplyNormalization", + "PickNormTarget", + "PickHighlightLevel", + "PickShadowLevel", + "PickCurvePoint", + "PickLumaCurve", + "PickColorCorrection", + "DirectColorEditor", + "PickSkinColor", + "AddColorReadout", + "DeleteColorReadout", + "OverlayTool", + "WatermarkTool", + "FocusMeterTool", + "PickFocusPoint", + "LoupeTool", + "KeystoneTool", + "KeystoneVertical", + "KeystoneHorizontal", + "DrawMaskTool", + "DrawHealTool", + "DrawCloneTool", + "EraseMaskTool", + "LinearGradientTool", + "RadialGradientTool", + "Process", + "ExportOriginals", + "ExportVariants", + "ImportImages", + "Print", + "EditAllSelected", + "Rename", + "NewVariant", + "CloneVariant", + "Delete", + "MoveToTrash", + "RegeneratePreviews", + "SetCompareVariant", + "ClearCompareVariant", + "PickVariant", + "PromoteVariant", + "DemoteVariant", + "ShowInLibrary", + "ShowInFileSystem", + "Capture", + "CompositionMode", + "LiveView", + "AutoFocus", + "AutoFocusFine", + "ShutterSpeedUp", + "ShutterSpeedDown", + "ApertureUp", + "ApertureDown", + "ExposureBiasUp", + "ExposureBiasDown", + "ISOUp", + "ISODown", + "BWEnable", + "ToggleGrading", + "SelectPen", + "SelectEraser", + "PenBlack", + "PenWhite", + "PenRed", + "PenYellow", + "PenGreen", + "PenBlue", + "ToggleSelectImage", + "NextGroup", + "PreviousGroup", + "NextImageImport", + "PreviousImageImport", + "FilterRatingNone", + "FilterRating1Star", + "FilterRating2Stars", + "FilterRating3Stars", + "FilterRating4Stars", + "FilterRating5Stars", + "FilterTagNone", + "FilterTagRed", + "FilterTagOrange", + "FilterTagYellow", + "FilterTagGreen", + "FilterTagBlue", + "FilterTagPink", + "FilterTagPurple", + "SelectUnrated", + "Select1Star", + "Select2Stars", + "Select3Stars", + "Select4Stars", + "Select5Stars", + "SelectTagNone", + "SelectTagRed", + "SelectTagOrange", + "SelectTagYellow", + "SelectTagGreen", + "SelectTagBlue", + "SelectTagPink", + "SelectTagPurple", + "AutoSync", +]; + +fn v(target: &str) -> Mapped { + Mapped::To(Binding::value(target), None) +} +fn vn(target: &str, note: &'static str) -> Mapped { + Mapped::To(Binding::value(target), Some(note)) +} +fn c(command: &str) -> Mapped { + Mapped::To(Binding::command(command), None) +} +fn cn(command: &str, note: &'static str) -> Mapped { + Mapped::To(Binding::command(command), Some(note)) +} +fn cp(command: &str, params: Value) -> Mapped { + Mapped::To(Binding::command_with(command, params), None) +} +fn cpn(command: &str, params: Value, note: &'static str) -> Mapped { + Mapped::To(Binding::command_with(command, params), Some(note)) +} + +const NO_LABEL: &str = "LightCraft's colour labels are red, yellow, green, blue and purple (as Lightroom's)"; +const C1_ONLY: &str = "a Capture One feature LightCraft does not have"; +const TETHER: &str = "tethered capture is not in LightCraft yet"; +const ANNOTATE: &str = "LightCraft has no annotations"; + +fn label_of(tag: &str) -> Option<&'static str> { + Some(match tag { + "None" => "none", + "Red" => "red", + "Yellow" => "yellow", + "Green" => "green", + "Blue" => "blue", + "Purple" => "purple", + _ => return None, + }) +} + +/// Where a TactileBridge action key goes in LightCraft. +pub fn map_key(key: &str) -> Mapped { + // ratings, labels, filters and selections come in families + if let Some(n) = key.strip_prefix("Rate").and_then(|r| r.chars().next()).and_then(|d| d.to_digit(10)) { + return cp("photo.rate", json!({"rating": n})); + } + if let Some(tag) = key.strip_prefix("ColorTag") { + return label_of(tag).map_or(Mapped::Dropped(NO_LABEL), |l| cp("photo.label", json!({"label": l}))); + } + if let Some(tag) = key.strip_prefix("FilterTag") { + return label_of(tag) + .map_or(Mapped::Dropped(NO_LABEL), |l| cp("library.filter", json!({"label": if l == "none" { Value::Null } else { json!(l) }}))); + } + if let Some(tag) = key.strip_prefix("SelectTag") { + return label_of(tag).map_or(Mapped::Dropped(NO_LABEL), |l| cp("library.selectBy", json!({"label": l}))); + } + if let Some(r) = key.strip_prefix("FilterRating") { + return match r.chars().next().and_then(|d| d.to_digit(10)) { + Some(n) => cp("library.filter", json!({"rating": n, "ratingOp": "atLeast"})), + None => cpn("library.filter", json!({"rating": 0, "ratingOp": "exactly"}), "shows unrated photos"), + }; + } + if let Some(n) = key.strip_prefix("Select").and_then(|r| r.chars().next()).and_then(|d| d.to_digit(10)) { + return cp("library.selectBy", json!({"rating": n, "ratingOp": "eq"})); + } + if let Some(m) = map_mixer(key) { + return m; + } + match key { + // ---- dial values + "Kelvin" => v("wb.temp"), + "Tint" => v("wb.tint"), + "Exposure" => v("light.exposure"), + "Contrast" => v("light.contrast"), + "Brightness" => Mapped::Dropped("Lightroom and LightCraft have no Brightness slider (use Exposure, Whites or the Tone Curve)"), + "Saturation" => v("color.saturation"), + "Highlight" => v("light.highlights"), + "Shadow" => v("light.shadows"), + "White" => v("light.whites"), + "Black" => v("light.blacks"), + "MasterToneX" => vn("grading.global.hue", "Color Grading uses hue and saturation where Capture One's Color Balance uses x / y"), + "MasterToneY" => vn("grading.global.sat", "Color Grading uses hue and saturation where Capture One's Color Balance uses x / y"), + "ShadowToneX" => vn("grading.shadows.hue", "Color Grading uses hue and saturation where Capture One's Color Balance uses x / y"), + "ShadowToneY" => vn("grading.shadows.sat", "Color Grading uses hue and saturation where Capture One's Color Balance uses x / y"), + "ShadowLightness" => v("grading.shadows.lum"), + "MidtoneToneX" => vn("grading.midtones.hue", "Color Grading uses hue and saturation where Capture One's Color Balance uses x / y"), + "MidtoneToneY" => vn("grading.midtones.sat", "Color Grading uses hue and saturation where Capture One's Color Balance uses x / y"), + "MidtoneLightness" => v("grading.midtones.lum"), + "HighlightToneX" => vn("grading.highlights.hue", "Color Grading uses hue and saturation where Capture One's Color Balance uses x / y"), + "HighlightToneY" => vn("grading.highlights.sat", "Color Grading uses hue and saturation where Capture One's Color Balance uses x / y"), + "HighlightLightness" => v("grading.highlights.lum"), + "BWRed" => v("bw.red"), + "BWYellow" => v("bw.yellow"), + "BWGreen" => v("bw.green"), + "BWCyan" => vn("bw.aqua", "Cyan is called Aqua in the B&W mixer"), + "BWBlue" => v("bw.blue"), + "BWMagenta" => v("bw.magenta"), + "BWHighlightsHue" => vn("grading.highlights.hue", "B&W split toning is done with Color Grading"), + "BWHighlightsSat" => vn("grading.highlights.sat", "B&W split toning is done with Color Grading"), + "BWShadowsHue" => vn("grading.shadows.hue", "B&W split toning is done with Color Grading"), + "BWShadowsSat" => vn("grading.shadows.sat", "B&W split toning is done with Color Grading"), + "Clarity" => v("effects.clarity"), + "Structure" => vn("effects.texture", "Texture is the closest to Capture One's Structure"), + "Vignetting" => vn("vignette.amount", "post-crop vignette"), + "Distortion" => v("optics.distortion"), + "SharpnessFalloff" => Mapped::Dropped("LightCraft has no sharpness falloff correction"), + "LightFalloff" => vn("optics.vignetting", "lens vignetting (light falloff) correction"), + "Defringe" => vn("optics.defringePurple", "purple fringe amount"), + "UniformLight" => Mapped::Dropped(C1_ONLY), + "SharpeningAmount" => v("detail.sharpenAmount"), + "SharpeningRadius" => v("detail.sharpenRadius"), + "SharpeningThreshold" => vn("detail.sharpenMasking", "Masking is the closest to a sharpening threshold"), + "SharpeningHalo" => Mapped::Dropped("LightCraft has no halo suppression slider"), + "NRLuminance" => v("detail.nrLuminance"), + "NRDetail" => v("detail.nrDetail"), + "NRColor" => v("detail.nrColor"), + "NRSinglePixel" => Mapped::Dropped("LightCraft has no single-pixel noise slider"), + "GrainImpact" => v("grain.amount"), + "GrainGranularity" => v("grain.size"), + "MoireAmount" => vn("mask.moire", "moiré is a mask adjustment in LightCraft (as in Lightroom)"), + "MoirePattern" => Mapped::Dropped("LightCraft's moiré reduction has no pattern size"), + "LayerOpacity" => vn("mask.amount", "a mask's Amount"), + "SpotRadius" => vn("ui.removeSize", "the Remove brush size"), + "BrushSize" => v("ui.brushSize"), + "BrushHardness" => vn("ui.brushFeather", "Feather (softness) — turn the other way for harder"), + "BrushOpacity" => Mapped::Dropped("LightCraft brushes have Size, Feather and Flow"), + "BrushFlow" => v("ui.brushFlow"), + "Zoom" => v("ui.zoom"), + "OverlayOpacity" | "OverlayScale" | "OverlayHorizontal" | "OverlayVertical" | "OverlayTool" => Mapped::Dropped(C1_ONLY), + "PenSize" => Mapped::Dropped(ANNOTATE), + // ---- keys + "ClearRating" => cp("photo.rate", json!({"rating": 0})), + "PreviousImage" => c("library.previous"), + "NextImage" => c("library.next"), + "FirstImage" | "LastImage" => Mapped::Dropped("no LightCraft command jumps to the first or last photo yet"), + "SelectAll" => c("library.selectAll"), + "DeselectAll" => c("library.selectNone"), + "InvertSelection" => Mapped::Dropped("no LightCraft command inverts the selection yet"), + "SelectPrimaryOnly" | "DeselectPrimary" | "SelectSameColorTag" | "SelectSameSequenceId" | "SelectSameVariantPos" => Mapped::Dropped(C1_ONLY), + "PreviousSet" | "NextSet" | "PreviousCollection" | "NextCollection" => Mapped::Dropped(C1_ONLY), + "SelectUnrated" => cp("library.selectBy", json!({"rating": 0, "ratingOp": "eq"})), + "Undo" => c("edit.undo"), + "Redo" => c("edit.redo"), + "ResetAdjustments" => c("develop.reset"), + "CopyAdjustments" => c("develop.copy"), + "ApplyAdjustments" => c("develop.paste"), + "CopyAndApplyAdj" => cn("develop.sync", "copies the active photo's settings to the other selected photos"), + "AutoAdjust" => c("develop.auto"), + "RotateLeft" => c("photo.rotateLeft"), + "RotateRight" => c("photo.rotateRight"), + "SnapTo90" => Mapped::To(Binding::command_with("develop.resetControl", json!({"control": "crop.angle"})), Some("straightens back to 0°")), + "NewEmptyLayer" => cpn("mask.add", json!({"kind": "brush"}), "a new brush mask"), + "NewFilledLayer" => { + cpn("mask.add", json!({"kind": "radial", "center": [0.5, 0.5], "rx": 1.0, "ry": 1.0, "feather": 0.0}), "a new mask over the whole photo") + } + "NewCloneLayer" | "NewHealLayer" | "DrawHealTool" | "DrawCloneTool" | "SpotRemovalTool" => { + cn("panel.remove", "the Remove tool (heal and clone)") + } + "RemoveLayer" => cn("mask.delete", "deletes the selected mask"), + "SelectLayerUp" => cn("surface.maskPrevious", "selects the mask above"), + "SelectLayerDown" => cn("surface.maskNext", "selects the mask below"), + "SelectBackground" => Mapped::To(Binding::command_with("mask.select", json!({"id": null})), Some("deselects the mask")), + "ToggleLayerOnOff" => cn("mask.visible", "shows or hides the selected mask"), + "InvertMask" => c("mask.invert"), + "FillMask" | "ClearMask" | "RasterizeMask" | "FeatherMask" => Mapped::Dropped(C1_ONLY), + "RefineMask" => Mapped::Dropped("Refine runs on a mask's own component in LightCraft"), + "LumaRange" => cpn("mask.add", json!({"kind": "luminanceRange"}), "a new luminance range mask"), + "ToggleSelectionPoints" => cn("view.maskPins", "mask pins"), + "ZoomIn" | "IncreaseZoom" | "ZoomInTool" => c("view.zoomIn"), + "ZoomOut" | "DecreaseZoom" | "ZoomOutTool" => c("view.zoomOut"), + "ZoomToFit" => c("view.zoomFit"), + "Zoom100" => c("view.zoom100"), + "Zoom200" => cp("view.navigate", json!({"zoom": {"percent": 200}})), + "Zoom400" => cp("view.navigate", json!({"zoom": {"percent": 400}})), + "ToggleMultiView" => cn("view.survey", "Survey view"), + "ToggleExposureWarn" => cn("view.clipping", "clipping warnings"), + "ToggleFocusMask" => Mapped::Dropped("LightCraft has no focus mask yet"), + "ToggleOverlay" | "WatermarkTool" => Mapped::Dropped(C1_ONLY), + "ToggleBeforeAfter" => c("view.beforeAfter"), + "ShowGuides" | "ShowGrid" => cn("view.cropOverlay", "cycles the crop overlay"), + "RecipeProofing" => cn("view.softProof", "soft proofing"), + "FullScreen" => c("view.fullScreenPreview"), + "SlideShow" => c("view.slideshow"), + "ShowHideViewer" => Mapped::Dropped(C1_ONLY), + "ShowHideBrowser" => cn("view.filmstrip", "the filmstrip"), + "ToggleTools" => cn("panel.edit", "opens or closes the Edit panel"), + "SelectTool" | "MoveTool" | "PanTool" => cn("tool.none", "no tool: click and drag pans"), + "CropTool" | "StraightenTool" | "RotateFreehandTool" => cn("panel.crop", "Crop & Rotate (straighten there)"), + "SwitchCropOrientation" => c("crop.rotateAspect"), + "WBPickerTool" => c("tool.wbPicker"), + "ApplyNormalization" | "PickNormTarget" | "PickSkinColor" | "AddColorReadout" | "DeleteColorReadout" => Mapped::Dropped(C1_ONLY), + "PickHighlightLevel" | "PickShadowLevel" | "PickCurvePoint" | "PickLumaCurve" | "PickColorCorrection" => { + Mapped::Dropped("LightCraft's targeted adjustment works on the photo with the pointer") + } + "DirectColorEditor" => cn("section.color", "the Color section (Point Color is there)"), + "FocusMeterTool" | "PickFocusPoint" => Mapped::Dropped(C1_ONLY), + "LoupeTool" => cn("view.zoomToggle", "zooms to 100 % and back"), + "KeystoneTool" => cn("tool.guidedUpright", "Guided Upright"), + "KeystoneVertical" => cpn("geometry.upright", json!({"mode": "vertical"}), "Upright: Vertical"), + "KeystoneHorizontal" => cpn("geometry.upright", json!({"mode": "level"}), "Upright: Level"), + "DrawMaskTool" => c("tool.brush"), + "EraseMaskTool" => cn("brush.erase", "erases while the key is held, like Alt"), + "LinearGradientTool" => c("tool.linear"), + "RadialGradientTool" => c("tool.radial"), + "Process" | "ExportOriginals" | "ExportVariants" => cn("dialog.export", "the Export dialog"), + "ImportImages" => c("file.addPhotos"), + "Print" => cn("dialog.contactSheet", "LightCraft prints contact sheets as PDF"), + "EditAllSelected" => cn("develop.autoSync", "Auto Sync: edits change every selected photo"), + "Rename" => c("dialog.rename"), + "NewVariant" | "CloneVariant" => cn("photo.virtualCopy", "a virtual copy"), + "Delete" | "MoveToTrash" => cn("photo.delete", "moves to Recently Deleted"), + "RegeneratePreviews" => c("library.buildPreviews"), + "SetCompareVariant" => cn("photo.setReference", "the reference photo"), + "ClearCompareVariant" => Mapped::Dropped(C1_ONLY), + "PickVariant" => cn("photo.pick", "flags as Pick"), + "PromoteVariant" => cn("stack.moveUp", "one place up in the stack"), + "DemoteVariant" => cn("stack.moveDown", "one place down in the stack"), + "ShowInLibrary" => cn("view.back", "back to the grid"), + "ShowInFileSystem" => c("app.showInFinder"), + "Capture" | "CompositionMode" | "LiveView" | "AutoFocus" | "AutoFocusFine" | "ShutterSpeedUp" | "ShutterSpeedDown" | "ApertureUp" + | "ApertureDown" | "ExposureBiasUp" | "ExposureBiasDown" | "ISOUp" | "ISODown" => Mapped::Dropped(TETHER), + "BWEnable" => c("develop.treatment"), + "ToggleGrading" => Mapped::Dropped("Capture One's grading switch has no single LightCraft counterpart"), + "SelectPen" | "SelectEraser" | "PenBlack" | "PenWhite" | "PenRed" | "PenYellow" | "PenGreen" | "PenBlue" => Mapped::Dropped(ANNOTATE), + "ToggleSelectImage" | "NextGroup" | "PreviousGroup" | "NextImageImport" | "PreviousImageImport" => { + Mapped::Dropped("these sent keystrokes to Capture One's import window; LightCraft's import dialog takes the keyboard directly") + } + "AutoSync" => Mapped::To(Binding::ApplyToSelected, Some("dials change every selected photo")), + _ => Mapped::Dropped("not a TactileBridge action LightCraft knows"), + } +} + +/// Color Editor values (`CERedHue`, …) → the colour mixer. +fn map_mixer(key: &str) -> Option { + let rest = key.strip_prefix("CE")?; + let (band, field) = + ["Red", "Orange", "Yellow", "Green", "Cyan", "Blue", "Purple", "Magenta"].iter().find_map(|b| rest.strip_prefix(b).map(|f| (*b, f)))?; + let field = match field { + "Hue" => "hue", + "Sat" => "sat", + "Light" => "lum", + _ => return None, + }; + let lc = if band == "Cyan" { "aqua".to_string() } else { band.to_ascii_lowercase() }; + let target = format!("mixer.{lc}.{field}"); + Some(if band == "Cyan" { + Mapped::To(Binding::value(&target), Some("Cyan is called Aqua in the colour mixer")) + } else { + Mapped::To(Binding::value(&target), None) + }) +} + +/// The kind of a known TactileBridge key. +pub fn kind_of(key: &str) -> Option { + if ADJUSTMENTS.contains(&key) { + Some(TbKind::Adjustment) + } else if COMMANDS.contains(&key) { + Some(TbKind::Command) + } else { + None + } +} + +/// The binding of a key, if it has one. +pub fn binding_of(key: &str) -> Option { + match map_key(key) { + Mapped::To(b, _) => Some(b), + Mapped::Dropped(_) => None, + } +} + +/// TactileBridge tool contexts → LightCraft contexts. +pub fn context_of(tool: &str) -> Option<&'static str> { + Some(match tool { + "default" => "default", + "Select" => "develop", + "Crop" => "crop", + "Draw Mask" | "Erase Mask" => "masking.mask.brush", + "Draw Healing Mask" => "remove", + "Direct Color Editor" => "develop.color", + "Import" => "dialog.import", + "Export" | "Process" => "dialog.export", + _ => return None, + }) +} + +/// One line of an import report. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] +pub struct ReportLine { + /// What it was in TactileBridge. + pub from: String, + /// What it is now (empty when dropped). + pub to: String, + /// Why it was dropped or how it differs. + pub note: String, +} + +/// What an import did. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] +pub struct Report { + pub mapped: Vec, + pub dropped: Vec, +} + +impl Report { + fn note(&mut self, from: String, key: &str) -> Option { + match map_key(key) { + Mapped::To(b, note) => { + self.mapped.push(ReportLine { from, to: b.describe(), note: note.unwrap_or_default().to_string() }); + Some(b) + } + Mapped::Dropped(why) => { + self.dropped.push(ReportLine { from, to: String::new(), note: why.to_string() }); + None + } + } + } +} + +fn num(v: &Value, k: &str) -> Option { + v.get(k).and_then(Value::as_f64).filter(|f| f.is_finite()) +} +fn int(v: &Value, k: &str) -> Option { + v.get(k).and_then(Value::as_f64).filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.min(f64::from(u32::MAX)) as u32) +} +fn boolean(v: &Value, k: &str) -> Option { + v.get(k).and_then(Value::as_bool) +} +/// TactileBridge wrote camelCase; older hand-edited files may use PascalCase. +fn field<'a>(v: &'a Value, camel: &str) -> Option<&'a Value> { + v.get(camel).or_else(|| { + let mut c = camel.chars(); + let pascal: String = c.next().map(|f| f.to_ascii_uppercase().to_string() + c.as_str()).unwrap_or_default(); + v.get(pascal) + }) +} + +/// Apply a TactileBridge `settings.json` to `s`: dial feel, OSD, colours, Auto Sync, automatic +/// switching, and its tool contexts as pages of a "TactileBridge" profile (made active). Returns +/// what was brought over and what was left behind. +pub fn import_settings(s: &mut SurfaceSettings, text: &str) -> Result { + let root: Value = serde_json::from_str(text).map_err(|e| format!("not a TactileBridge settings file: {e}"))?; + if !root.is_object() { + return Err("not a TactileBridge settings file".into()); + } + let mut r = Report::default(); + let line = |r: &mut Report, from: &str, to: &str, note: &str| r.mapped.push(ReportLine { from: from.into(), to: to.into(), note: note.into() }); + if let Some(c) = field(&root, "controls") { + if let Some(x) = num(c, "globalSpeedMultiplier") { + s.motion.speed = x; + line(&mut r, "Global speed", "Dial Feel ▸ Speed", ""); + } + if let Some(x) = num(c, "globalAccelerationMultiplier") { + s.motion.acceleration = x; + line(&mut r, "Global acceleration", "Dial Feel ▸ Acceleration", ""); + } + if let Some(x) = boolean(c, "invertDirection") { + s.motion.invert = x; + line(&mut r, "Invert dial direction", "Dial Feel ▸ Turn every dial the other way", ""); + } + if let Some(x) = boolean(c, "enableEchoSuppression") { + s.transport.echo_suppression = x; + } + if let Some(x) = int(c, "echoSuppressionMs") { + s.transport.echo_suppression_ms = x; + line(&mut r, "Echo suppression", "Editing ▸ Keep the surface's readout steady while turning", ""); + } + if let Some(Value::Object(profiles)) = field(c, "adjustmentProfiles") { + for (key, t) in profiles { + let from = format!("Tuning: {key}"); + let d = Tuning::default(); + let tuning = Tuning { + speed: num(t, "speedMultiplier").unwrap_or(d.speed), + acceleration: num(t, "accelerationMultiplier").unwrap_or(d.acceleration), + acceleration_min: num(t, "accelerationMin").unwrap_or(d.acceleration_min), + acceleration_max: num(t, "accelerationMax").unwrap_or(d.acceleration_max), + fast_ms: int(t, "fastThresholdMs").unwrap_or(d.fast_ms), + slow_ms: int(t, "slowThresholdMs").unwrap_or(d.slow_ms), + invert: boolean(t, "invertDirection").unwrap_or(false), + } + .sanitized(); + // an untouched (default) tuning carries nothing to bring over + if tuning == Tuning::default() { + continue; + } + let Some(Binding::Value { target }) = binding_of(key) else { + r.dropped.push(ReportLine { from, to: String::new(), note: "no LightCraft value to tune".into() }); + continue; + }; + r.mapped.push(ReportLine { from, to: format!("Tuning: {target}"), note: String::new() }); + s.tuning.insert(target, tuning); + } + } + } + if let Some(b) = field(&root, "bridge") { + if let Some(x) = int(b, "flushIntervalMs") { + s.transport.flush_ms = x; + line(&mut r, "Flush interval", "Editing ▸ Apply movement every", ""); + } + for k in ["idleReconcileDelayMs", "stateRetentionMs", "periodicValuePollMs", "enableCoalescingDiagnostics"] { + if b.get(k).is_some() { + r.dropped.push(ReportLine { + from: format!("Bridge: {k}"), + to: String::new(), + note: "LightCraft pushes its values to the surface; there is nothing to poll or reconcile".into(), + }); + } + } + } + if let Some(h) = field(&root, "hardware") { + if let Some(x) = boolean(h, "enableHapticFeedback") { + s.look.haptics = x; + } + if let Some(x) = boolean(h, "enableLedIndicator") { + s.look.show_values = x; + line(&mut r, "LED value indicator", "Surface ▸ Show values on the keys and the dial display", ""); + } + } + if let Some(o) = field(&root, "osd") { + if let Some(x) = boolean(o, "enabled") { + s.osd.enabled = x; + } + if let Some(x) = num(o, "opacity") { + s.osd.opacity = x; + } + if let Some(x) = o.get("backgroundColor").and_then(Value::as_str) { + s.osd.background = hex_color(x, "#202020"); + } + if let Some(x) = int(o, "displayTimeMs") { + s.osd.display_ms = x; + } + if let Some(p) = o.get("position").and_then(Value::as_str) { + s.osd.position = match p { + "DownLow" => OsdPosition::BottomEdge, + "Up" => OsdPosition::Top, + "UpHigh" => OsdPosition::TopEdge, + _ => OsdPosition::Bottom, + }; + } + line(&mut r, "On-screen display", "On-Screen Readout", "drawn inside the LightCraft window"); + } + if let Some(c) = field(&root, "pluginColors") { + if let Some(x) = c.get("backgroundColor").and_then(Value::as_str) { + s.look.background = hex_color(x, "#000000"); + } + if let Some(x) = c.get("foregroundColor").and_then(Value::as_str) { + s.look.foreground = hex_color(x, "#FFFFFF"); + } + line(&mut r, "Plugin colours", "Surface ▸ Key background, Key text", ""); + } + if let Some(x) = field(&root, "toolSwitching").and_then(|t| boolean(t, "enabled")) { + s.follow_context = x; + line(&mut r, "Automatic tool switching", "Pages That Follow the App", ""); + } + if let Some(a) = field(&root, "autoSync") { + if let Some(x) = boolean(a, "enabled") { + s.apply_to_selected = x; + } + if let Some(x) = int(a, "idleTimeoutMs") { + s.transport.gesture_end_ms = x; + } + line(&mut r, "Auto Sync", "Editing ▸ Dials change every selected photo", "one undo step per dial gesture"); + if a.get("copyApplyDelayMs").is_some() { + r.dropped.push(ReportLine { + from: "Auto Sync: copy-apply delay".into(), + to: String::new(), + note: "LightCraft applies to the selection directly".into(), + }); + } + } + if let Some(Value::Object(ctx)) = field(&root, "toolContext").and_then(|t| field(t, "contexts")) { + let mut p = crate::defaults::profiles().into_iter().find(|p| p.name == "Default").unwrap_or_default(); + p.name = unique_name(s, "TactileBridge"); + p.description = "Imported from TactileBridge".into(); + // TactileBridge's tool layouts take the contexts they cover; LightCraft's own tool pages stay + // for the rest (a selected mask, Masking without a tool, …) + let mut taken: std::collections::BTreeSet = std::collections::BTreeSet::new(); + for (tool, m) in ctx { + let Some(context) = context_of(tool) else { + r.dropped.push(ReportLine { + from: format!("Tool context: {tool}"), + to: String::new(), + note: "no matching LightCraft context".into(), + }); + continue; + }; + let mut bindings = BTreeMap::new(); + let buttons = field(m, "buttons").and_then(Value::as_array).cloned().unwrap_or_default(); + for (i, k) in buttons.iter().filter_map(Value::as_str).take(9).enumerate() { + if let Some(b) = r.note(format!("{tool}: key {} ({k})", i + 1), k) { + bindings.insert(format!("key.{}", i + 1), b); + } + } + let encoders = field(m, "encoders").and_then(Value::as_array).cloned().unwrap_or_default(); + // the Dialpad's encoder 0 is its roller, 1 its big dial + let slots = ["roller", "dial", "knob.3", "knob.4"]; + for (slot, k) in slots.iter().zip(encoders.iter().filter_map(Value::as_str)) { + if let Some(b) = r.note(format!("{tool}: {slot} ({k})"), k) { + bindings.insert((*slot).to_string(), b); + } + } + let name = if tool == "default" { "Tool: Default".to_string() } else { format!("Tool: {tool}") }; + // TactileBridge's default and Select layouts were its everyday ones (Select is Capture + // One's normal cursor): ordinary pages, first, so the Keypad's own page 1 shows them; the + // other tools' layouts are tool pages shown by their context + let everyday = tool == "default" || tool == "Select"; + let page = Page { name: name.clone(), groups: Vec::new(), bindings, auto: !everyday }; + if everyday { + let at = if tool == "default" { 0 } else { usize::from(p.pages.first().is_some_and(|f| f.name == "Tool: Default")) }; + p.pages.insert(at.min(p.pages.len()), page); + if tool == "default" { + p.contexts.insert("default".into(), vec![name]); + } + } else { + p.pages.push(page); + if taken.insert(context.to_string()) { + p.contexts.insert(context.to_string(), vec![name]); + } else { + p.contexts.entry(context.to_string()).or_default().push(name); + } + } + } + p.sanitize(); + s.profile = p.name.clone(); + s.profiles.push(p); + } + s.sanitize(); + Ok(r) +} + +fn unique_name(s: &SurfaceSettings, base: &str) -> String { + let mut name = base.to_string(); + let mut n = 2; + while s.profiles.iter().any(|p| p.name == name) { + name = format!("{base} {n}"); + n += 1; + } + name +} + +/// Read a Logi profile package (`.lp5`) TactileBridge shipped or the user saved: its pages, with +/// TactileBridge actions mapped. Keypad profiles (`Loupedeck70`) give key pages, Dialpad profiles +/// (`Loupedeck71`) dial pages and base buttons; Actions Ring profiles (`Loupedeck72`) both. +pub fn import_lp5(bytes: &[u8]) -> Result<(Profile, Report), String> { + let info = crate::zip::read_member(bytes, "ProfileInfo.json")?; + let text = String::from_utf8_lossy(&info); + let root: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("ProfileInfo.json can't be read: {e}"))?; + let device = root.get("deviceType").and_then(Value::as_str).unwrap_or(""); + let name = root.get("displayName").and_then(Value::as_str).unwrap_or("Imported").trim(); + let mut profile = Profile { name: if name.is_empty() { "Imported".into() } else { name.to_string() }, ..Default::default() }; + let mut report = Report::default(); + let workspaces = root.pointer("/layout/layoutModes").and_then(Value::as_array).cloned().unwrap_or_default(); + for mode in workspaces.iter().take(16) { + for ws in mode.get("workspaces").and_then(Value::as_array).into_iter().flatten().take(16) { + for (pages_key, rotate) in [("pressPages", false), ("rotatePages", true)] { + for page in ws.get(pages_key).and_then(Value::as_array).into_iter().flatten().take(64) { + let pname = page.get("displayName").and_then(Value::as_str).unwrap_or("Page").to_string(); + let mut bindings = BTreeMap::new(); + for ctl in page.get("controls").and_then(Value::as_array).into_iter().flatten().take(64) { + let Some(id) = ctl.get("controlId").and_then(Value::as_u64) else { continue }; + let action = ctl.get(if rotate { "rotateAction" } else { "pressAction" }).and_then(Value::as_str).unwrap_or(""); + // "$______" + let Some(key) = action.rsplit("___").next().filter(|k| !k.is_empty() && *k != action) else { continue }; + let slot = match (rotate, device, id) { + // Logi's encoder 0 on the Dialpad is the roller, 1 the big dial + (true, _, 0) => "roller".to_string(), + (true, _, 1) => "dial".to_string(), + (true, _, n) => format!("knob.{}", n + 1), + (false, "Loupedeck71", n) => format!("pad.{}", n + 1), + (false, _, n) => format!("key.{}", n + 1), + }; + if let Some(b) = report.note(format!("{pname}: {slot} ({key})"), key) { + bindings.insert(slot, b); + } + } + let is_pads = !rotate && device == "Loupedeck71"; + if is_pads { + // the Dialpad's buttons stay put while its dial pages change + profile.base.extend(bindings); + } else { + let group = if rotate { PageGroup::Dials } else { PageGroup::Keys }; + profile.pages.push(Page { name: pname, groups: vec![group], bindings, auto: false }); + } + } + } + } + } + if profile.pages.is_empty() && profile.base.is_empty() { + return Err("the profile has no pages".into()); + } + profile.sanitize(); + Ok((profile, report)) +} + +/// The table of every TactileBridge action and where it went (docs, the import dialog). +pub fn mapping_table() -> Vec<(TbKind, &'static str, Mapped)> { + ADJUSTMENTS.iter().map(|k| (TbKind::Adjustment, *k, map_key(k))).chain(COMMANDS.iter().map(|k| (TbKind::Command, *k, map_key(k)))).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::zip::tests::make_zip; + + #[test] + fn every_tactilebridge_action_is_mapped_or_explained() { + for (kind, key, m) in mapping_table() { + match m { + Mapped::To(Binding::Value { target }, _) => { + assert_eq!(kind, TbKind::Adjustment, "{key}"); + assert!(crate::targets::target_spec(&target).is_some(), "{key} → unknown target {target}"); + } + Mapped::To(Binding::Command { command, params }, _) => { + assert!(command.contains('.'), "{key} → {command}"); + assert!(params.is_null() || params.is_object(), "{key}"); + } + Mapped::To(_, _) => {} + Mapped::Dropped(why) => assert!(!why.is_empty(), "{key}"), + } + } + assert_eq!(map_key("Rate3Stars"), Mapped::To(Binding::command_with("photo.rate", json!({"rating": 3})), None)); + assert!(matches!(map_key("ColorTagOrange"), Mapped::Dropped(_))); + assert_eq!(binding_of("CECyanSat"), Some(Binding::value("mixer.aqua.sat"))); + assert_eq!(binding_of("Select4Stars"), Some(Binding::command_with("library.selectBy", json!({"rating": 4, "ratingOp": "eq"})))); + assert_eq!(binding_of("SelectTool"), Some(Binding::command("tool.none")), "Select… families don't swallow tools"); + assert_eq!(binding_of("SelectAll"), Some(Binding::command("library.selectAll"))); + assert!(matches!(map_key("Bogus"), Mapped::Dropped(_))); + let mapped = mapping_table().iter().filter(|(_, _, m)| matches!(m, Mapped::To(..))).count(); + assert!(mapped > 120, "{mapped}"); + } + + #[test] + fn settings_import_brings_tuning_osd_colours_and_contexts() { + let tb = r##"{ + "bridge": {"flushIntervalMs": 20, "idleReconcileDelayMs": 120}, + "controls": {"globalSpeedMultiplier": 1.5, "invertDirection": true, "echoSuppressionMs": 150, + "adjustmentProfiles": {"Kelvin": {"speedMultiplier": 0.3}, "Exposure": {"speedMultiplier": 0.49, "fastThresholdMs": 1}, "PenSize": {"speedMultiplier": 2}}}, + "hardware": {"enableLedIndicator": false}, + "osd": {"enabled": true, "opacity": 0.6, "position": "Up", "displayTimeMs": 1800, "backgroundColor": "#202020"}, + "pluginColors": {"backgroundColor": "#101010", "foregroundColor": "ff7800"}, + "toolSwitching": {"enabled": false}, + "autoSync": {"enabled": true, "idleTimeoutMs": 1500, "copyApplyDelayMs": 100}, + "toolContext": {"contexts": { + "Crop": {"buttons": ["SwitchCropOrientation", "ZoomIn", "ToggleOverlay"], "encoders": ["Zoom"]}, + "Draw Annotations": {"buttons": ["SelectPen"], "encoders": ["PenSize"]}, + "default": {"buttons": ["Rate5Stars", "Undo"], "encoders": ["Exposure", "Kelvin"]} + }} + }"##; + let mut s = SurfaceSettings::default(); + let r = import_settings(&mut s, tb).unwrap(); + assert_eq!((s.motion.speed, s.motion.invert, s.transport.echo_suppression_ms, s.transport.flush_ms), (1.5, true, 150, 20)); + assert_eq!(s.tuning["wb.temp"].speed, 0.3); + assert_eq!((s.tuning["light.exposure"].speed, s.tuning["light.exposure"].fast_ms), (0.49, 5), "clamped"); + assert!(!s.look.show_values); + assert_eq!((s.osd.opacity, s.osd.position), (0.6, OsdPosition::Top)); + assert_eq!((s.look.background.as_str(), s.look.foreground.as_str()), ("#101010", "#FF7800")); + assert!(!s.follow_context && s.apply_to_selected); + assert_eq!(s.transport.gesture_end_ms, 1500); + let p = s.active_profile().unwrap(); + assert_eq!(p.name, "TactileBridge"); + let crop = p.page("Tool: Crop").unwrap(); + assert_eq!(crop.bindings["key.1"], Binding::command("crop.rotateAspect")); + assert_eq!(crop.bindings["roller"], Binding::value("ui.zoom")); + assert!(!crop.bindings.contains_key("key.3"), "ToggleOverlay has no counterpart"); + assert_eq!(p.contexts["crop"], ["Tool: Crop"]); + let def = p.page("Tool: Default").unwrap(); + assert_eq!(def.bindings["dial"], Binding::value("wb.temp")); + assert!(!def.auto && p.pages[0].name == "Tool: Default", "TactileBridge's default layout is the first ordinary page"); + assert_eq!(p.contexts["default"], ["Tool: Default"]); + assert!(p.page("Tool: Crop").unwrap().auto); + assert!(r.dropped.iter().any(|l| l.from.contains("Draw Annotations"))); + assert!(r.dropped.iter().any(|l| l.from == "Tuning: PenSize")); + assert!(r.dropped.iter().any(|l| l.from.contains("idleReconcileDelayMs"))); + // importing twice makes a second profile, it doesn't overwrite the first + import_settings(&mut s, tb).unwrap(); + assert!(s.profiles.iter().any(|p| p.name == "TactileBridge 2")); + } + + #[test] + fn junk_settings_are_errors() { + let mut s = SurfaceSettings::default(); + assert!(import_settings(&mut s, "[").is_err()); + assert!(import_settings(&mut s, "[1]").is_err()); + let r = import_settings( + &mut s, + r#"{"controls": {"adjustmentProfiles": {"Exposure": {"speedMultiplier": "fast"}}, "globalSpeedMultiplier": null}}"#, + ) + .unwrap(); + assert!(r.mapped.is_empty(), "nothing usable, nothing changed"); + assert_eq!(s, SurfaceSettings::default()); + } + + fn lp5(device: &str, press: Value, rotate: Value) -> Vec { + let info = json!({"deviceType": device, "displayName": "Wedding", "layout": {"layoutModes": [{"workspaces": [{"pressPages": press, "rotatePages": rotate}]}]}}); + let text = format!("\u{feff}{info}"); + make_zip(&[("ProfileInfo.json", text.as_bytes(), true)]) + } + + #[test] + fn lp5_profiles_become_pages() { + let keypad = lp5( + "Loupedeck70", + json!([{"displayName": "Cull", "controls": [ + {"controlId": 0, "pressAction": "$CaptureOne___CaptureOneCmd___PreviousImage"}, + {"controlId": 5, "pressAction": "$CaptureOne___CaptureOneCmd___Rate5Stars"}, + {"controlId": 8, "pressAction": "$CaptureOne___CaptureOneCmd___ColorTagOrange"}]}]), + json!([]), + ); + let (p, r) = import_lp5(&keypad).unwrap(); + assert_eq!(p.name, "Wedding"); + let cull = p.page("Cull").unwrap(); + assert_eq!(cull.groups, [PageGroup::Keys]); + assert_eq!(cull.bindings["key.1"], Binding::command("library.previous")); + assert_eq!(cull.bindings["key.6"], Binding::command_with("photo.rate", json!({"rating": 5}))); + assert_eq!(r.dropped.len(), 1); + let dialpad = lp5( + "Loupedeck71", + json!([{"displayName": "Buttons", "controls": [{"controlId": 0, "pressAction": "$CaptureOne___CaptureOneCmd___CopyAdjustments"}]}]), + json!([{"displayName": "HDR", "controls": [ + {"controlId": 0, "rotateAction": "$CaptureOne___CaptureOneAdj___Highlight"}, + {"controlId": 1, "rotateAction": "$CaptureOne___CaptureOneAdj___Shadow"}]}]), + ); + let (p, _) = import_lp5(&dialpad).unwrap(); + assert_eq!(p.base["pad.1"], Binding::command("develop.copy")); + let hdr = p.page("HDR").unwrap(); + assert_eq!( + (hdr.groups.as_slice(), &hdr.bindings["dial"], &hdr.bindings["roller"]), + // encoder 0 (Highlight) is the roller, encoder 1 (Shadow) the big dial + ([PageGroup::Dials].as_slice(), &Binding::value("light.shadows"), &Binding::value("light.highlights")) + ); + assert!(import_lp5(b"not a zip").is_err()); + assert!(import_lp5(&make_zip(&[("ProfileInfo.json", b"{\"layout\": 5}", false)])).is_err()); + } +} diff --git a/crates/surface/src/targets.rs b/crates/surface/src/targets.rs new file mode 100644 index 00000000000..24913773b9e --- /dev/null +++ b/crates/surface/src/targets.rs @@ -0,0 +1,214 @@ +//! The values a dial can move. +//! +//! - develop sliders by their control id (`light.exposure`, `mixer.red.hue`, `pointColor.0.hueShift` +//! …: [`lightcraft_develop::controls`]); +//! - the selected mask's sliders, `mask.` (`mask.exposure`, `mask.amount`, …), as the +//! `mask.adjust` command names them; +//! - brush, Remove and view values the UI keeps (`ui.brushSize`, `ui.removeSize`, `ui.zoom`, …), +//! with the ids and display scales the panels already use. + +use lightcraft_develop::controls; +use serde::Serialize; + +/// Who owns the value, and so how the host changes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum TargetKind { + /// A develop slider of the active photo (`develop.adjust`; undoable, Auto Sync applies). + Develop, + /// A slider of the selected mask (`mask.adjust`; undoable). + Mask, + /// A tool or view value of the interface (not part of the photo's edit; no undo step). + Ui, +} + +/// Range, default, step and display precision of a target, like a develop control spec. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct TargetSpec { + pub id: String, + /// English label (the UI translates it). + pub label: &'static str, + /// The panel it belongs to (English), for the editor's list. + pub group: &'static str, + pub kind: TargetKind, + pub min: f64, + pub max: f64, + pub default: f64, + /// Value units per dial tick at speed 1 without acceleration. + pub step: f64, + pub decimals: u8, +} + +impl TargetSpec { + pub fn clamp(&self, v: f64) -> f64 { + if v.is_finite() { v.clamp(self.min, self.max) } else { self.default } + } + + /// The value as the panels print it (`+0.35`, `5600`, `-12`). + pub fn format(&self, v: f64) -> String { + let v = if v.is_finite() { v } else { self.default }; + let s = format!("{:.*}", self.decimals as usize, v); + // "-0" / "-0.00" read as zero + let s = if s.starts_with('-') && s.trim_start_matches('-').chars().all(|c| c == '0' || c == '.') { + s.trim_start_matches('-').to_string() + } else { + s + }; + if v > 0.0 && self.min < 0.0 && s.chars().any(|c| c.is_ascii_digit() && c != '0') { format!("+{s}") } else { s } + } + + /// Where `v` sits between the ends, 0…1 (for the OSD bar and device rings). + pub fn position(&self, v: f64) -> f64 { + if let Some(spec) = controls::find(&self.id) { + return spec.position(v); + } + let span = self.max - self.min; + if !(span.is_finite() && span > 0.0) { + return 0.0; + } + let p = (self.clamp(v) - self.min) / span; + if p.is_finite() { p.clamp(0.0, 1.0) } else { 0.0 } + } + + /// The largest change one flush may make: the whole range (a runaway delta never overshoots + /// by more than a slider's travel). + pub fn max_delta(&self) -> f64 { + let span = self.max - self.min; + if span.is_finite() && span > 0.0 { span } else { 0.0 } + } +} + +struct Static { + id: &'static str, + label: &'static str, + group: &'static str, + min: f64, + max: f64, + default: f64, + step: f64, + decimals: u8, +} + +const fn st(id: &'static str, label: &'static str, group: &'static str, min: f64, max: f64, default: f64, step: f64, decimals: u8) -> Static { + Static { id, label, group, min, max, default, step, decimals } +} + +/// The selected mask's sliders (ranges as `mask.adjust` clamps them). +const MASK: &[Static] = &[ + st("mask.temp", "Temp", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.tint", "Tint", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.exposure", "Exposure", "Mask", -4.0, 4.0, 0.0, 0.01, 2), + st("mask.contrast", "Contrast", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.highlights", "Highlights", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.shadows", "Shadows", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.whites", "Whites", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.blacks", "Blacks", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.texture", "Texture", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.clarity", "Clarity", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.dehaze", "Dehaze", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.hue", "Hue", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.saturation", "Saturation", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.sharpness", "Sharpness", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.noise", "Noise", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.moire", "Moire", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.defringe", "Defringe", "Mask", -100.0, 100.0, 0.0, 1.0, 0), + st("mask.amount", "Amount", "Mask", 0.0, 200.0, 100.0, 1.0, 0), +]; + +/// Tool and view values (ids and display scales as the Masking and Remove panels show them). +const UI: &[Static] = &[ + st("ui.brushSize", "Brush Size", "Brush", 1.0, 100.0, 16.0, 1.0, 0), + st("ui.brushFeather", "Brush Feather", "Brush", 0.0, 100.0, 50.0, 1.0, 0), + st("ui.brushFlow", "Brush Flow", "Brush", 1.0, 100.0, 60.0, 1.0, 0), + st("ui.removeSize", "Remove Size", "Remove", 1.0, 250.0, 20.0, 1.0, 0), + st("ui.removeFeather", "Remove Feather", "Remove", 0.0, 100.0, 50.0, 1.0, 0), + st("ui.removeOpacity", "Remove Opacity", "Remove", 0.0, 100.0, 100.0, 1.0, 0), + st("ui.zoom", "Zoom", "View", 5.0, 800.0, 100.0, 1.0, 0), +]; + +fn from_static(s: &Static, kind: TargetKind) -> TargetSpec { + TargetSpec { + id: s.id.to_string(), + label: s.label, + group: s.group, + kind, + min: s.min, + max: s.max, + default: s.default, + step: s.step, + decimals: s.decimals, + } +} + +/// The spec of a target id, or `None` for an id nothing knows. +pub fn target_spec(id: &str) -> Option { + if let Some(s) = MASK.iter().find(|s| s.id == id) { + return Some(from_static(s, TargetKind::Mask)); + } + if let Some(s) = UI.iter().find(|s| s.id == id) { + return Some(from_static(s, TargetKind::Ui)); + } + let c = controls::find(id)?; + Some(TargetSpec { + id: id.to_string(), + label: c.label, + group: c.section.label(), + kind: TargetKind::Develop, + min: c.min, + max: c.max, + default: c.default, + step: c.step, + decimals: c.decimals, + }) +} + +/// Every target the editor offers: the develop sliders in panel order, then the mask, brush, +/// Remove and view values. +pub fn all_targets() -> Vec { + let mut v: Vec = controls::CONTROLS.iter().filter_map(|c| target_spec(c.id)).collect(); + v.extend(MASK.iter().map(|s| from_static(s, TargetKind::Mask))); + v.extend(UI.iter().map(|s| from_static(s, TargetKind::Ui))); + v +} + +/// The mask field `mask.adjust` takes for a `mask.` target. +pub fn mask_field(id: &str) -> Option<&str> { + let f = id.strip_prefix("mask.")?; + MASK.iter().any(|s| s.id == id).then_some(f) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn develop_mask_and_ui_targets_resolve() { + let e = target_spec("light.exposure").unwrap(); + assert_eq!((e.kind, e.min, e.max, e.step), (TargetKind::Develop, -5.0, 5.0, 0.01)); + assert_eq!(target_spec("mask.exposure").unwrap().kind, TargetKind::Mask); + assert_eq!(target_spec("ui.brushSize").unwrap().kind, TargetKind::Ui); + assert_eq!(target_spec("pointColor.2.hueShift").unwrap().kind, TargetKind::Develop); + assert!(target_spec("nope").is_none()); + assert_eq!(mask_field("mask.amount"), Some("amount")); + assert_eq!(mask_field("mask.nope"), None); + let all = all_targets(); + let mut ids: Vec<_> = all.iter().map(|t| t.id.as_str()).collect(); + ids.sort_unstable(); + let n = ids.len(); + ids.dedup(); + assert_eq!(ids.len(), n, "target ids are unique"); + } + + #[test] + fn formatting_and_position_are_total() { + let e = target_spec("light.exposure").unwrap(); + assert_eq!(e.format(0.5), "+0.50"); + assert_eq!(e.format(-0.001), "0.00"); + assert_eq!(e.format(f64::NAN), "0.00"); + assert_eq!(e.position(0.0), 0.5); + let b = target_spec("ui.brushFlow").unwrap(); + assert_eq!(b.format(60.0), "60"); + assert_eq!(b.position(f64::INFINITY), (b.default - b.min) / (b.max - b.min)); + assert_eq!(b.max_delta(), 99.0); + } +} diff --git a/crates/surface/src/zip.rs b/crates/surface/src/zip.rs new file mode 100644 index 00000000000..af62221becd --- /dev/null +++ b/crates/surface/src/zip.rs @@ -0,0 +1,144 @@ +//! Just enough ZIP reading to take one file out of a Logi profile package (`.lp5`). Every offset +//! and size comes from the file and is checked; inflated data is capped. + +/// Largest archive read. +pub const MAX_ARCHIVE: usize = 16 * 1024 * 1024; +/// Largest member inflated. +pub const MAX_MEMBER: usize = 8 * 1024 * 1024; + +/// `len` bytes at `at`, if they are all there. +fn bytes(b: &[u8], at: usize, len: usize) -> Option<&[u8]> { + b.get(at..at.checked_add(len)?) +} + +fn u16_at(b: &[u8], at: usize) -> Option { + let s = bytes(b, at, 2)?; + Some(u16::from_le_bytes([*s.first()?, *s.get(1)?])) +} + +fn u32_at(b: &[u8], at: usize) -> Option { + let s = bytes(b, at, 4)?; + Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?])) +} + +/// The bytes of the member called `name` (exact match, `/` separators). +pub fn read_member(archive: &[u8], name: &str) -> Result, String> { + if archive.len() > MAX_ARCHIVE { + return Err("the file is too large to be a Logi profile".into()); + } + // End of central directory: the last "PK\x05\x06" within the final 64 KiB + 22 bytes. + let min_start = archive.len().saturating_sub(22 + 65_535); + let eocd = + (min_start..archive.len().saturating_sub(21)).rev().find(|&i| bytes(archive, i, 4) == Some(b"PK\x05\x06")).ok_or("not a ZIP archive")?; + let off = |base: usize, n: usize| base.checked_add(n).ok_or("damaged ZIP"); + let count = usize::from(u16_at(archive, off(eocd, 10)?).ok_or("damaged ZIP")?); + let cd = usize::try_from(u32_at(archive, off(eocd, 16)?).ok_or("damaged ZIP")?).map_err(|_| "damaged ZIP")?; + let mut at = cd; + for _ in 0..count { + if bytes(archive, at, 4) != Some(b"PK\x01\x02") { + return Err("damaged ZIP directory".into()); + } + let method = u16_at(archive, off(at, 10)?).ok_or("damaged ZIP")?; + let csize = usize::try_from(u32_at(archive, off(at, 20)?).ok_or("damaged ZIP")?).map_err(|_| "damaged ZIP")?; + let usize_ = usize::try_from(u32_at(archive, off(at, 24)?).ok_or("damaged ZIP")?).map_err(|_| "damaged ZIP")?; + let nlen = usize::from(u16_at(archive, off(at, 28)?).ok_or("damaged ZIP")?); + let elen = usize::from(u16_at(archive, off(at, 30)?).ok_or("damaged ZIP")?); + let clen = usize::from(u16_at(archive, off(at, 32)?).ok_or("damaged ZIP")?); + let local = usize::try_from(u32_at(archive, off(at, 42)?).ok_or("damaged ZIP")?).map_err(|_| "damaged ZIP")?; + let entry_name = bytes(archive, off(at, 46)?, nlen).ok_or("damaged ZIP")?; + if entry_name == name.as_bytes() { + if bytes(archive, local, 4) != Some(b"PK\x03\x04") { + return Err("damaged ZIP entry".into()); + } + let lnlen = usize::from(u16_at(archive, off(local, 26)?).ok_or("damaged ZIP")?); + let lelen = usize::from(u16_at(archive, off(local, 28)?).ok_or("damaged ZIP")?); + let start = off(off(local, 30)?, lnlen + lelen)?; + let data = bytes(archive, start, csize).ok_or("damaged ZIP entry")?; + if usize_ > MAX_MEMBER { + return Err(format!("{name} is too large")); + } + return match method { + 0 => Ok(data.to_vec()), + 8 => miniz_oxide::inflate::decompress_to_vec_with_limit(data, MAX_MEMBER).map_err(|_| format!("{name} can't be unpacked")), + m => Err(format!("{name} uses an unsupported compression ({m})")), + }; + } + at = off(at, 46 + nlen + elen + clen)?; + } + Err(format!("{name} is not in the file")) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// A ZIP with stored (method 0) and deflated (method 8) members. + pub(crate) fn make_zip(files: &[(&str, &[u8], bool)]) -> Vec { + let mut out = Vec::new(); + let mut cd = Vec::new(); + for (name, data, deflate) in files { + let packed = if *deflate { miniz_oxide::deflate::compress_to_vec(data, 6) } else { data.to_vec() }; + let off = out.len() as u32; + let method: u16 = if *deflate { 8 } else { 0 }; + out.extend_from_slice(b"PK\x03\x04"); + out.extend_from_slice(&20u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&method.to_le_bytes()); + out.extend_from_slice(&[0; 8]); // time, date, crc + out.extend_from_slice(&(packed.len() as u32).to_le_bytes()); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(&packed); + cd.extend_from_slice(b"PK\x01\x02"); + cd.extend_from_slice(&[20, 0, 20, 0, 0, 0]); + cd.extend_from_slice(&method.to_le_bytes()); + cd.extend_from_slice(&[0; 8]); + cd.extend_from_slice(&(packed.len() as u32).to_le_bytes()); + cd.extend_from_slice(&(data.len() as u32).to_le_bytes()); + cd.extend_from_slice(&(name.len() as u16).to_le_bytes()); + cd.extend_from_slice(&[0; 12]); // extra, comment, disk, int attr, ext attr (2+2+2+2+4) + cd.extend_from_slice(&off.to_le_bytes()); + cd.extend_from_slice(name.as_bytes()); + } + let cd_off = out.len() as u32; + out.extend_from_slice(&cd); + out.extend_from_slice(b"PK\x05\x06"); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(files.len() as u16).to_le_bytes()); + out.extend_from_slice(&(cd.len() as u32).to_le_bytes()); + out.extend_from_slice(&cd_off.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out + } + + #[test] + fn reads_stored_and_deflated_members() { + let z = make_zip(&[("a.txt", b"hello", false), ("dir/ProfileInfo.json", b"{\"x\": 1}", true)]); + assert_eq!(read_member(&z, "a.txt").unwrap(), b"hello"); + assert_eq!(read_member(&z, "dir/ProfileInfo.json").unwrap(), b"{\"x\": 1}"); + assert!(read_member(&z, "missing").unwrap_err().contains("not in the file")); + } + + #[test] + fn junk_and_truncation_are_errors_not_panics() { + let z = make_zip(&[("ProfileInfo.json", b"{}", true)]); + assert!(read_member(b"", "x").is_err()); + assert!(read_member(b"PK\x05\x06", "x").is_err()); + for cut in 0..z.len() { + let _ = read_member(&z[..cut], "ProfileInfo.json"); + } + let mut bad = z.clone(); + let n = bad.len(); + bad[n - 6..n - 2].copy_from_slice(&u32::MAX.to_le_bytes()); // directory offset past the end + assert!(read_member(&bad, "ProfileInfo.json").is_err()); + let mut flip = z; + for i in 0..flip.len() { + flip[i] ^= 0xA5; + let _ = read_member(&flip, "ProfileInfo.json"); + flip[i] ^= 0xA5; + } + } +} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index d5be5523f3b..861140dc9b9 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -53,6 +53,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("scenes", Class::Layer(1)), ("slideshow", Class::Layer(1)), ("pipeline", Class::Layer(2)), + ("surface", Class::Layer(2)), ("gpu", Class::Layer(3)), ("catalog", Class::Layer(3)), ("preview", Class::Layer(3)), From 0418f67f923cd8922a5d5411699c9a96e58ceb4a Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 25 Oct 2026 21:34:23 +1000 Subject: [PATCH 02/16] HW-SURFACE: control surfaces in the app: protocol, readout, Settings > Controls, Keys and Dials - The surface protocol on the control channel and on a loopback port of its own that serves surface.* only (pairing approved in Settings > Controls; layouts pushed as events). - Dials move values with one undo step per turn, on the active photo or every selected one; keys run commands; destructive keys need a hold; pages follow the tool (Crop, Masking, its brush, Remove, dialogs); the on-screen readout shows what a dial or key did. - Settings > Controls, in the Settings window's one size: on/off and profile, pairing, the device bar, Pages and Tools, Dial Feel, Readout and Look, Profiles and Setup (the Logi plugin install, TactileBridge / Loupedeck imports, export). Edit Keys and Dials... opens the drawn device and its editor (action picker, drag and drop, Touch to find) in a resizable window of its own. - The LightCraft plugin for Logi Options+ installed from Settings (Windows); the web app has no control surfaces. - Translations for the new strings; docs (control-surfaces.md, the protocol, hardware parity, what's new). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 187 +- apps/lightcraft-web/src/web.rs | 6 + apps/lightcraft/Cargo.toml | 2 + apps/lightcraft/src/control_server.rs | 546 +++++- apps/lightcraft/src/logi_plugin.rs | 175 ++ apps/lightcraft/src/main.rs | 71 +- crates/ui-egui/Cargo.toml | 2 + crates/ui-egui/locales/cs-formats.json | 13 +- crates/ui-egui/locales/cs.json | 46 +- crates/ui-egui/locales/de-formats.json | 13 +- crates/ui-egui/locales/de.json | 232 ++- crates/ui-egui/locales/es-formats.json | 13 +- crates/ui-egui/locales/es.json | 237 ++- crates/ui-egui/locales/fr-formats.json | 13 +- crates/ui-egui/locales/fr.json | 237 ++- crates/ui-egui/locales/it-formats.json | 13 +- crates/ui-egui/locales/it.json | 46 +- crates/ui-egui/locales/ja-formats.json | 13 +- crates/ui-egui/locales/ja.json | 237 ++- crates/ui-egui/locales/ka-formats.json | 13 +- crates/ui-egui/locales/pl-formats.json | 13 +- crates/ui-egui/locales/pl.json | 47 +- crates/ui-egui/locales/pt-br-formats.json | 13 +- crates/ui-egui/locales/pt-br.json | 237 ++- crates/ui-egui/locales/ru-formats.json | 13 +- crates/ui-egui/locales/ru.json | 237 ++- crates/ui-egui/locales/uk-formats.json | 13 +- crates/ui-egui/locales/uk.json | 237 ++- crates/ui-egui/locales/zh-hans-formats.json | 13 +- crates/ui-egui/locales/zh-hans.json | 237 ++- crates/ui-egui/locales/zh-hant-formats.json | 13 +- crates/ui-egui/locales/zh-hant.json | 238 ++- crates/ui-egui/src/control.rs | 62 +- crates/ui-egui/src/headless.rs | 6 + crates/ui-egui/src/lib.rs | 35 + crates/ui-egui/src/menus.rs | 42 + crates/ui-egui/src/panels/controls.rs | 1685 +++++++++++++++++++ crates/ui-egui/src/panels/mod.rs | 2 + crates/ui-egui/src/panels/settings.rs | 4 +- crates/ui-egui/src/panels/surface_osd.rs | 113 ++ crates/ui-egui/src/surface.rs | 1207 +++++++++++++ crates/ui-egui/src/surface_icons.rs | 144 ++ crates/ui-egui/src/surface_plugin.rs | 237 +++ crates/ui-egui/src/tests_surface.rs | 685 ++++++++ docs/control-protocol.md | 4 +- docs/control-surfaces.md | 663 ++++++++ docs/hardware-parity.md | 5 +- docs/whats-new.md | 14 + 48 files changed, 8224 insertions(+), 110 deletions(-) create mode 100644 apps/lightcraft/src/logi_plugin.rs create mode 100644 crates/ui-egui/src/panels/controls.rs create mode 100644 crates/ui-egui/src/panels/surface_osd.rs create mode 100644 crates/ui-egui/src/surface.rs create mode 100644 crates/ui-egui/src/surface_icons.rs create mode 100644 crates/ui-egui/src/surface_plugin.rs create mode 100644 crates/ui-egui/src/tests_surface.rs create mode 100644 docs/control-surfaces.md diff --git a/Cargo.lock b/Cargo.lock index 78de058c3c7..994ca525d4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -310,6 +310,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + [[package]] name = "arrayvec" version = "0.7.8" @@ -584,6 +590,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64ct" version = "1.8.3" @@ -1208,6 +1220,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + [[package]] name = "der" version = "0.7.10" @@ -1807,6 +1825,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + [[package]] name = "float8" version = "0.6.1" @@ -2612,7 +2636,7 @@ dependencies = [ "image-webp", "moxcms 0.8.1", "num-traits", - "png", + "png 0.18.1", "tiff", "zune-core", "zune-jpeg", @@ -2628,6 +2652,12 @@ dependencies = [ "quick-error 2.0.1", ] +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + [[package]] name = "imgref" version = "1.12.3" @@ -3020,6 +3050,17 @@ dependencies = [ "accesskit_consumer 0.35.0", ] +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + [[package]] name = "kurbo" version = "0.13.1" @@ -3095,6 +3136,7 @@ dependencies = [ "lightcraft-codecs", "lightcraft-engine", "lightcraft-raster", + "lightcraft-surface", "lightcraft-sysmem", "lightcraft-testkit", "lightcraft-ui-egui", @@ -3164,7 +3206,7 @@ dependencies = [ "lightcraft-raster", "lightcraft-testkit", "moxcms 0.9.1", - "png", + "png 0.18.1", "proptest", "rav1e", "ravif", @@ -3500,6 +3542,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "lightcraft-surface" +version = "0.13.0" +dependencies = [ + "lightcraft-develop", + "miniz_oxide 0.8.9", + "serde", + "serde_json", + "sha2", +] + [[package]] name = "lightcraft-sysmem" version = "0.13.0" @@ -3538,8 +3591,10 @@ dependencies = [ "lightcraft-preview", "lightcraft-raster", "lightcraft-slideshow", + "lightcraft-surface", "lightcraft-testkit", "log", + "resvg", "serde", "serde_json", "toml", @@ -3750,7 +3805,7 @@ dependencies = [ "objc2-core-foundation", "objc2-foundation 0.3.2", "once_cell", - "png", + "png 0.18.1", "thiserror 2.0.21", "windows-sys 0.61.2", ] @@ -4481,7 +4536,7 @@ checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" dependencies = [ "bytemuck", "color", - "kurbo", + "kurbo 0.13.1", "linebender_resource_handle", "smallvec", ] @@ -4535,6 +4590,12 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project" version = "1.1.13" @@ -4616,6 +4677,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "png" version = "0.18.1" @@ -5130,6 +5204,20 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "resvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" +dependencies = [ + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + [[package]] name = "rfc6979" version = "0.4.0" @@ -5172,6 +5260,9 @@ name = "rgb" version = "0.8.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] [[package]] name = "ring" @@ -5187,6 +5278,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + [[package]] name = "rsa" version = "0.9.10" @@ -5558,6 +5655,15 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + [[package]] name = "siphasher" version = "1.0.4" @@ -5704,12 +5810,31 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + [[package]] name = "subtle" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo 0.11.3", + "siphasher", +] + [[package]] name = "syn" version = "2.0.119" @@ -5864,6 +5989,32 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.17.16", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "tokio" version = "1.53.1" @@ -6075,6 +6226,28 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "usvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64", + "data-url", + "flate2", + "imagesize", + "kurbo 0.11.3", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "xmlwriter", +] + [[package]] name = "uuid" version = "1.26.1" @@ -7007,6 +7180,12 @@ version = "0.8.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + [[package]] name = "xtask" version = "0.13.0" diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index 8cdb324620a..5a91659908a 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -248,6 +248,12 @@ fn services(originals: Originals, backend: Option, files: Files, frozen pick_folder: None, // the browser reports prefers-color-scheme to egui system_theme: None, + // no control surfaces in the browser + surface_store: None, + pick_surface_file: None, + save_surface_file: None, + surface_listener: None, + surface_plugin: None, } } diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index 95e080974f9..7951c1c4a4e 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -23,6 +23,8 @@ lightcraft-sysmem = { workspace = true } lightcraft-ui-egui = { workspace = true } lightcraft-codecs = { workspace = true } lightcraft-raster = { workspace = true } +# reading the Logi plugin package's version (`logi_plugin`) and the control-surface e2e test +lightcraft-surface = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "glow", "accesskit", "wayland", "x11"] } egui = { workspace = true } serde_json = { workspace = true } diff --git a/apps/lightcraft/src/control_server.rs b/apps/lightcraft/src/control_server.rs index 95aa108964a..859319abd55 100644 --- a/apps/lightcraft/src/control_server.rs +++ b/apps/lightcraft/src/control_server.rs @@ -6,15 +6,21 @@ //! one error reply and the connection is closed, so nothing after it is executed. Lines are //! bounded ([`MAX_LINE`]) and so is the number of open connections ([`MAX_CONNECTIONS`]); junk //! never reaches the UI thread. See `docs/control-protocol.md`. +//! +//! A connection that subscribes to a control surface's layout (`surface.subscribe`, +//! `docs/control-surfaces.md`) also receives pushed event lines (`{"event": ...}`) between its +//! replies; lines never interleave. The surfaces-only listener ([`Mode::SurfacesOnly`], Settings, +//! Controls) serves nothing but `surface.*` methods, which need pairing. use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpListener, TcpStream}; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use lightcraft_ui_egui::ControlRequest; +use lightcraft_ui_egui::surface::EventSink; use serde_json::{Value, json}; /// Longest accepted request line (bytes, without the newline). Requests are small JSON objects; @@ -23,24 +29,63 @@ pub const MAX_LINE: usize = 4 * 1024 * 1024; /// Connections served at once; further ones get an error line and are closed. pub const MAX_CONNECTIONS: usize = 16; -pub fn start(port: u16, ctx: egui::Context) -> Receiver { - let (tx, rx) = channel::(); - let listener = match TcpListener::bind(("127.0.0.1", port)) { - Ok(l) => l, - Err(e) => { - log::error!("control server failed to bind 127.0.0.1:{port}: {e}"); - return rx; +/// What a listener serves. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// Every method (`--control PORT`). + Full, + /// Only `surface.*` (the control-surface port of Settings, Controls). + SurfacesOnly, +} + +/// Connection numbers (0 is the in-process channel). +static NEXT_CONN: AtomicU64 = AtomicU64::new(1); + +/// Serve `--control PORT`: requests go to `tx`. +pub fn start(port: u16, tx: Sender, ctx: egui::Context) { + match TcpListener::bind(("127.0.0.1", port)) { + Ok(l) => { + log::info!("control server listening on 127.0.0.1:{port}"); + let stop = Arc::new(AtomicBool::new(false)); + std::thread::spawn(move || accept_loop(l, tx, ctx, Mode::Full, stop)); } - }; - log::info!("control server listening on 127.0.0.1:{port}"); - std::thread::spawn(move || accept_loop(listener, tx, ctx)); - rx + Err(e) => log::error!("control server failed to bind 127.0.0.1:{port}: {e}"), + } } -fn accept_loop(listener: TcpListener, tx: Sender, ctx: egui::Context) { +/// Start the surfaces-only listener on `port` (0: any free port); set the returned flag to stop +/// it. Returns the flag and the port. +pub fn start_surfaces(port: u16, tx: Sender, ctx: egui::Context) -> Result<(Arc, u16), String> { + let l = TcpListener::bind(("127.0.0.1", port)).map_err(|e| format!("can't listen on 127.0.0.1:{port}: {e}"))?; + l.set_nonblocking(true).map_err(|e| e.to_string())?; + let port = l.local_addr().map(|a| a.port()).unwrap_or(port); + log::info!("control-surface listener on 127.0.0.1:{port}"); + let stop = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&stop); + std::thread::spawn(move || accept_loop(l, tx, ctx, Mode::SurfacesOnly, flag)); + Ok((stop, port)) +} + +fn accept_loop(listener: TcpListener, tx: Sender, ctx: egui::Context, mode: Mode, stop: Arc) { let open = Arc::new(AtomicUsize::new(0)); - for stream in listener.incoming().flatten() { - let _ = spawn_connection(stream, tx.clone(), ctx.clone(), Arc::clone(&open), IDLE_TIMEOUT); + // a surface connection (a paired device) may sit listening for pushed layouts for hours + let idle = if mode == Mode::SurfacesOnly { None } else { Some(IDLE_TIMEOUT) }; + loop { + if stop.load(Ordering::SeqCst) { + log::info!("control listener stopped"); + return; + } + let stream = match listener.accept() { + Ok((s, _)) => s, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(100)); + continue; + } + Err(_) => continue, + }; + // a non-blocking listener hands out non-blocking sockets on some systems + let _ = stream.set_nonblocking(false); + let _ = spawn_connection(stream, tx.clone(), ctx.clone(), Arc::clone(&open), mode, idle); } } @@ -50,7 +95,8 @@ fn spawn_connection( tx: Sender, ctx: egui::Context, open: Arc, - idle_timeout: Duration, + mode: Mode, + idle_timeout: Option, ) -> Option> { if open.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS { open.fetch_sub(1, Ordering::SeqCst); @@ -58,11 +104,57 @@ fn spawn_connection( return None; } Some(std::thread::spawn(move || { - serve(stream, &tx, &ctx, idle_timeout); + serve(stream, &tx, &ctx, mode, idle_timeout); open.fetch_sub(1, Ordering::SeqCst); })) } +/// A writer shared by a connection's replies and its pushed events: each line goes out whole. +/// It writes through `&TcpStream` (no `try_clone`: see [`serve`]); `lock` keeps lines whole. +#[derive(Clone)] +struct LineWriter { + out: Arc, + lock: Arc>, + buf: Vec, +} + +impl LineWriter { + fn new(out: Arc) -> Self { + LineWriter { out, lock: Arc::new(Mutex::new(())), buf: Vec::new() } + } +} + +impl Write for LineWriter { + fn write(&mut self, b: &[u8]) -> std::io::Result { + self.buf.extend_from_slice(b); + Ok(b.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + let data = std::mem::take(&mut self.buf); + let _line = self.lock.lock().unwrap_or_else(PoisonError::into_inner); + let mut out: &TcpStream = &self.out; + out.write_all(&data)?; + out.flush() + } +} + +/// Write pushed events to the connection until it closes. +fn pump_events(events: Receiver, mut out: LineWriter, open: Arc) { + loop { + match events.recv_timeout(Duration::from_millis(500)) { + Ok(v) => { + if writeln!(out, "{v}").and_then(|()| out.flush()).is_err() { + open.store(false, Ordering::SeqCst); + return; + } + } + Err(RecvTimeoutError::Timeout) if open.load(Ordering::SeqCst) => {} + Err(_) => return, + } + } +} + /// Five minutes allows pauses between automation commands without retaining abandoned slots forever. const IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60); @@ -82,18 +174,41 @@ pub const HIDDEN_WINDOW_ERROR: &str = "the app drew no frame for 5 s, so the req /// while a client is connected (a link in the browser, Show in Explorer, an external editor) kept a /// copy of the connection: closing it then reached the client only when that program exited, as a /// reset instead of a clean close. -fn serve(stream: TcpStream, tx: &Sender, ctx: &egui::Context, idle_timeout: Duration) { - if let Err(e) = stream.set_read_timeout(Some(idle_timeout)) { +/// +/// `idle_timeout`: how long the connection may send nothing before it is closed (`None`: never). +fn serve(stream: TcpStream, tx: &Sender, ctx: &egui::Context, mode: Mode, idle_timeout: Option) { + if let Err(e) = stream.set_read_timeout(idle_timeout) { log::warn!("control connection closed: could not set idle read timeout: {e}"); return; } - serve_lines(&stream, &stream, |method, params| { + let stream = Arc::new(stream); + let conn = NEXT_CONN.fetch_add(1, Ordering::SeqCst); + let open = Arc::new(AtomicBool::new(true)); + let (etx, erx) = channel::(); + let out = LineWriter::new(Arc::clone(&stream)); + let pump = { + let (out, open) = (out.clone(), Arc::clone(&open)); + std::thread::spawn(move || pump_events(erx, out, open)) + }; + let sink = EventSink { tx: etx, open: Arc::clone(&open) }; + serve_lines(&*stream, out, |method, params| { + if mode == Mode::SurfacesOnly && !method.starts_with("surface.") { + return Some(Reply::Ready(json!({"ok": false, "error": "this port serves control surfaces only (surface.* methods)"}))); + } + let pipelined = PIPELINED.contains(&method.as_str()); let (req, rrx) = ControlRequest::new(method, params); + let req = req.on_connection(conn, sink.clone()); let state = Arc::clone(&req.state); tx.send(req).ok()?; ctx.request_repaint(); - Some(await_reply(&rrx, &state, || ctx.cumulative_pass_nr(), || ctx.request_repaint(), NO_FRAMES_AFTER, REPLY_TIMEOUT)) + let ctx = ctx.clone(); + let wait: Waiter = + Box::new(move || await_reply(&rrx, &state, || ctx.cumulative_pass_nr(), || ctx.request_repaint(), NO_FRAMES_AFTER, REPLY_TIMEOUT)); + Some(if pipelined { Reply::Pipelined(wait) } else { Reply::Wait(wait) }) }); + open.store(false, Ordering::SeqCst); + drop(sink); + let _ = pump.join(); } /// Wait for a request's reply. While the app has not picked the request up and `frames` (its @@ -197,34 +312,104 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) - Ok(true) } +/// Methods whose requests are pipelined: the next line is read (and handed to the app) without +/// waiting for this one's reply, so a control surface's dial ticks never queue up one per frame in +/// the socket (TEST-NOTES 2026-10-16 item 8: a knob turned quickly sent ticks faster than the app +/// drew frames, and they drained seconds late, presses included). The app still runs them in +/// order, and their replies go out in order, after the replies to every earlier request. +pub const PIPELINED: &[&str] = &["surface.input"]; + +/// Requests of one connection handed to the app but not answered yet, at most (the reader waits +/// beyond that). +const PIPELINE_DEPTH: usize = 256; + +/// Waits for a request's reply. +type Waiter = Box Value + Send>; + +/// How a request is answered. +enum Reply { + /// At once (the request was refused without reaching the app). + Ready(Value), + /// When the app has run it; the next request is read only after this reply went out. + Wait(Waiter), + /// When the app has run it; the next request is read at once ([`PIPELINED`]). + Pipelined(Waiter), +} + +/// A reply to write, in order: its request's id (`None`: an error that closes the connection), +/// the reply, and who waits for it to be written. +struct Queued { + id: Option, + reply: Reply, + written: Option>, +} + +/// Write the replies `queue` hands over, in order, until it closes or a write fails. +fn write_replies(queue: Receiver, mut out: W) { + for q in queue { + let mut v = match q.reply { + Reply::Ready(v) => v, + Reply::Wait(f) | Reply::Pipelined(f) => f(), + }; + if let (Some(id), Some(o)) = (q.id, v.as_object_mut()) { + o.insert("id".into(), id); + } + let ok = writeln!(out, "{v}").and_then(|()| out.flush()).is_ok(); + if let Some(w) = q.written { + let _ = w.send(ok); + } + if !ok { + return; + } + } +} + /// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is /// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and -/// returns the reply object (the request's `id` is added here). -fn serve_lines(read: R, mut out: W, mut handle: impl FnMut(String, Value) -> Option) { - let mut reader = BufReader::new(read); - let mut buf = Vec::new(); - loop { - let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) { - Ok(false) => return, - Err(e) => e, - Ok(true) => match parse_line(&buf) { - Line::Blank => continue, - Line::Reject(e) => e, - Line::Request { id, method, params } => { - let Some(mut r) = handle(method, params) else { return }; - if let Some(o) = r.as_object_mut() { - o.insert("id".into(), id); - } - if writeln!(out, "{r}").and_then(|()| out.flush()).is_err() { - return; - } - continue; - } - }, +/// says how the request is answered (the request's `id` is added here). Replies go out in the +/// order of the requests; a [`Reply::Pipelined`] one doesn't hold back reading the next line. +fn serve_lines(read: R, out: W, mut handle: impl FnMut(String, Value) -> Option) { + std::thread::scope(|scope| { + let (queue, rx) = std::sync::mpsc::sync_channel::(PIPELINE_DEPTH); + let writer = scope.spawn(move || write_replies(rx, out)); + // hand a reply to the writer; with `wait`, until it is written. Whether to go on. + let send = |id: Option, reply: Reply, wait: bool| -> bool { + let (written, done) = if wait { + let (t, r) = std::sync::mpsc::sync_channel(1); + (Some(t), Some(r)) + } else { + (None, None) + }; + if queue.send(Queued { id, reply, written }).is_err() { + return false; + } + done.is_none_or(|d| d.recv().unwrap_or(false)) }; - let _ = writeln!(out, "{}", json!({"ok": false, "error": reject})).and_then(|()| out.flush()); - return; - } + let mut reader = BufReader::new(read); + let mut buf = Vec::new(); + loop { + let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) { + Ok(false) => break, + Err(e) => e, + Ok(true) => match parse_line(&buf) { + Line::Blank => continue, + Line::Reject(e) => e, + Line::Request { id, method, params } => { + let Some(r) = handle(method, params) else { break }; + let wait = !matches!(r, Reply::Pipelined(_)); + if !send(Some(id), r, wait) { + break; + } + continue; + } + }, + }; + send(None, Reply::Ready(json!({"ok": false, "error": reject})), true); + break; + } + drop(queue); + let _ = writer.join(); + }); } #[cfg(test)] @@ -252,7 +437,7 @@ mod tests { stream.set_nodelay(true).unwrap(); before(&mut client); let (tx, requests) = channel(); - let worker = spawn_connection(stream, tx, egui::Context::default(), Arc::clone(open), idle).unwrap(); + let worker = spawn_connection(stream, tx, egui::Context::default(), Arc::clone(open), Mode::Full, Some(idle)).unwrap(); Self { client: BufReader::new(client), requests, worker: Some(worker) } } @@ -381,12 +566,269 @@ mod tests { worker.join().unwrap(); } + /// A pushed event and a reply never share a line, and events stop when the peer goes. + #[test] + fn pushed_events_and_replies_arrive_as_whole_lines() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let client = TcpStream::connect(addr).unwrap(); + let (server, _) = listener.accept().unwrap(); + let open = Arc::new(AtomicBool::new(true)); + let (etx, erx) = channel::(); + let out = LineWriter::new(Arc::new(server)); + let pump = { + let (out, open) = (out.clone(), Arc::clone(&open)); + std::thread::spawn(move || pump_events(erx, out, open)) + }; + let mut reply = out.clone(); + for i in 0..50 { + etx.send(json!({"event": "surface.layout", "n": i})).unwrap(); + writeln!(reply, "{}", json!({"id": i, "ok": true})).unwrap(); + reply.flush().unwrap(); + } + client.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut r = BufReader::new(client); + let (mut events, mut replies) = (0, 0); + let mut line = String::new(); + while events + replies < 100 { + line.clear(); + r.read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(line.trim()).unwrap(); + if v.get("event").is_some() { events += 1 } else { replies += 1 } + } + assert_eq!((events, replies), (50, 50)); + open.store(false, Ordering::SeqCst); + drop(etx); + pump.join().unwrap(); + } + + /// A fake control surface drives a headless LightCraft over a real loopback socket: it is + /// refused until paired, pairs, subscribes, turns the dial and hears the new value pushed + /// back; the surfaces-only port refuses everything else. + #[test] + fn a_surface_client_pairs_subscribes_and_turns_the_dial_end_to_end() { + use std::time::Instant; + + use lightcraft_ui_egui::headless::Headless; + use lightcraft_ui_egui::surface::SurfaceStore; + use lightcraft_ui_egui::{LightcraftApp, Services}; + + struct Store(Mutex>); + impl SurfaceStore for Store { + fn load(&self) -> Result, String> { + Ok(self.0.lock().unwrap().clone()) + } + fn save(&self, t: &str) -> Result<(), String> { + *self.0.lock().unwrap() = Some(t.to_string()); + Ok(()) + } + } + let settings = lightcraft_surface::SurfaceSettings { enabled: true, ..Default::default() }; + let services = Services { png: None, surface_store: Some(Box::new(Store(Mutex::new(Some(settings.to_json()))))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1200.0, 800.0], 1.0); + h.settle(Duration::from_secs(20)); + let first = h.app.session.visible_cloned()[0]; + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [first.0]}}), Duration::from_secs(20)); + h.app.ui.view = lightcraft_ui_egui::state::ViewMode::Detail; + h.settle(Duration::from_secs(20)); + let before = h.app.session.develop_of(first).unwrap().light.exposure; + let (stop, port) = start_surfaces(0, h.control_sender(), egui::Context::default()).unwrap(); + + // the client, on its own thread (the app answers between frames on this one) + let client = std::thread::spawn(move || { + let send = |c: &mut TcpStream, id: u64, method: &str, params: Value| { + writeln!(c, "{}", json!({"id": id, "method": method, "params": params})).unwrap(); + }; + // read lines until the reply with `id`; events seen on the way are kept + let read = |r: &mut BufReader, id: u64, events: &mut Vec| -> Value { + loop { + let mut line = String::new(); + r.read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(line.trim()).unwrap(); + if v.get("event").is_some() { + events.push(v); + } else if v["id"] == id { + return v; + } + } + }; + let connect = || { + let c = TcpStream::connect(("127.0.0.1", port)).unwrap(); + c.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); + let r = BufReader::new(c.try_clone().unwrap()); + (c, r) + }; + let mut events = Vec::new(); + let (mut c, mut r) = connect(); + send(&mut c, 1, "engine.execute", json!({"command": "edit.undo"})); + let v = read(&mut r, 1, &mut events); + assert!(v["error"].as_str().unwrap().contains("control surfaces only"), "{v}"); + send(&mut c, 2, "surface.input", json!({"events": [{"control": "dial", "ticks": 1}]})); + assert_eq!(read(&mut r, 2, &mut events)["ok"], false, "not paired"); + send(&mut c, 3, "surface.pair", json!({"client": "e2e", "name": "E2E Surface"})); + let v = read(&mut r, 3, &mut events); + let request = v["result"]["request"].as_str().unwrap().to_string(); + // wait for the approval (the test approves on the app's thread) + let token = loop { + send(&mut c, 4, "surface.pair", json!({"request": request})); + let v = read(&mut r, 4, &mut events); + if v["result"]["status"] == "approved" { + break v["result"]["token"].as_str().unwrap().to_string(); + } + std::thread::sleep(Duration::from_millis(20)); + }; + drop(c); + let (mut c, mut r) = connect(); + send(&mut c, 5, "surface.hello", json!({"protocol": 1, "client": "e2e", "token": token})); + assert_eq!(read(&mut r, 5, &mut events)["result"]["paired"], true); + send(&mut c, 6, "surface.subscribe", json!({"device": "mx-creative-console"})); + let v = read(&mut r, 6, &mut events); + assert_eq!(v["result"]["layout"]["dials"][1]["binding"]["target"], "light.exposure", "{v}"); + send(&mut c, 7, "surface.input", json!({"events": [{"control": "roller", "ticks": 25}]})); + assert_eq!(read(&mut r, 7, &mut events)["ok"], true); + // the new value arrives as a pushed layout + let t0 = Instant::now(); + loop { + if events.iter().any(|e| e["layout"]["dials"][1]["value"] == "+0.25") { + break; + } + assert!(t0.elapsed() < Duration::from_secs(30), "no pushed value: {events:?}"); + let mut line = String::new(); + if r.read_line(&mut line).is_ok() && !line.trim().is_empty() { + events.push(serde_json::from_str(line.trim()).unwrap()); + } + } + }); + let t0 = Instant::now(); + while !client.is_finished() { + h.step(); + let waiting: Vec = h.app.surface.pairing.waiting().map(|w| w.request.clone()).collect(); + for w in waiting { + let mut s = h.app.surface.settings().clone(); + h.app.surface.pairing.approve(&w, &mut s, 0).unwrap(); + h.app.surface.runtime.settings_mut().paired = s.paired; + } + std::thread::sleep(Duration::from_millis(2)); + assert!(t0.elapsed() < Duration::from_secs(60), "the client didn't finish"); + } + client.join().unwrap(); + let after = h.app.session.develop_of(first).unwrap().light.exposure; + assert!((after - before - 0.25).abs() < 1e-6, "{before} → {after}"); + stop.store(true, Ordering::SeqCst); + } + + /// TEST-NOTES 2026-10-16 item 8: a knob turned fast sends a tick per request, faster than the + /// app draws frames. Ticks used to wait for a frame each (the connection read its next request + /// only after the reply), so they queued in the socket and were applied seconds late, a press + /// behind them "clicking itself" later. Now hundreds of ticks sent at once, with slow frames + /// (40 ms), are all applied within a few frames, the value is their sum, and a press sent + /// after them runs in the same breath. + #[test] + fn a_burst_of_dial_ticks_is_applied_within_a_few_frames_without_a_backlog() { + use std::time::Instant; + + use lightcraft_ui_egui::headless::Headless; + use lightcraft_ui_egui::{LightcraftApp, Services}; + + struct Store(Mutex>); + impl lightcraft_ui_egui::surface::SurfaceStore for Store { + fn load(&self) -> Result, String> { + Ok(self.0.lock().unwrap().clone()) + } + fn save(&self, t: &str) -> Result<(), String> { + *self.0.lock().unwrap() = Some(t.to_string()); + Ok(()) + } + } + const TOKEN: &str = "stress-token"; + let mut settings = lightcraft_surface::SurfaceSettings { enabled: true, ..Default::default() }; + settings.paired.push(lightcraft_surface::settings::PairedClient { + client: "stress".into(), + name: "Stress".into(), + token_sha256: lightcraft_surface::protocol::token_hash(TOKEN), + approved_at: 0, + }); + // no acceleration: every tick is one step (0.01 EV), so the sum is exact + settings.motion.acceleration = 0.1; + let services = Services { png: None, surface_store: Some(Box::new(Store(Mutex::new(Some(settings.to_json()))))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1200.0, 800.0], 1.0); + h.settle(Duration::from_secs(20)); + let first = h.app.session.visible_cloned()[0]; + h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [first.0]}}), Duration::from_secs(20)); + h.app.ui.view = lightcraft_ui_egui::state::ViewMode::Detail; + h.settle(Duration::from_secs(20)); + let before = h.app.session.develop_of(first).unwrap().light.exposure; + let rating_before = h.app.session.catalog.photo(first).unwrap().rating; + let (stop, port) = start_surfaces(0, h.control_sender(), egui::Context::default()).unwrap(); + const TICKS: usize = 300; + let frames = Arc::new(AtomicU64::new(0)); + let client = { + let frames = Arc::clone(&frames); + std::thread::spawn(move || { + let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); + c.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); + let mut r = BufReader::new(c.try_clone().unwrap()); + let mut reply = |id: u64| loop { + let mut line = String::new(); + r.read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(line.trim()).unwrap(); + if v.get("event").is_none() { + assert_eq!(v["id"], id, "replies come in order: {v}"); + return v; + } + }; + writeln!(c, "{}", json!({"id": 1, "method": "surface.hello", "params": {"protocol": 1, "client": "stress", "token": TOKEN}})) + .unwrap(); + assert_eq!(reply(1)["result"]["paired"], true); + // every tick its own request, all at once (as a plugin forwards a fast spin), then a key press + let t0 = Instant::now(); + let f0 = frames.load(Ordering::SeqCst); + let mut burst = String::new(); + for i in 0..TICKS { + burst.push_str( + &json!({"id": 10 + i, "method": "surface.input", "params": {"events": [{"control": "roller", "ticks": 1}]}}).to_string(), + ); + burst.push('\n'); + } + let press = + json!({"id": 9999, "method": "surface.input", "params": {"events": [{"action": "c.photo.rate.rating-5", "press": true}]}}); + burst.push_str(&format!("{press}\n")); + c.write_all(burst.as_bytes()).unwrap(); + for i in 0..TICKS { + assert_eq!(reply(10 + i as u64)["ok"], true); + } + assert_eq!(reply(9999)["ok"], true); + (t0.elapsed(), frames.load(Ordering::SeqCst) - f0) + }) + }; + let t0 = Instant::now(); + while !client.is_finished() { + h.step(); + frames.fetch_add(1, Ordering::SeqCst); + // a slow frame (a busy app): one tick per frame would take 12 s + std::thread::sleep(Duration::from_millis(40)); + assert!(t0.elapsed() < Duration::from_secs(60), "the client didn't finish"); + } + let (took, used) = client.join().unwrap(); + // the last flush and gesture end + for _ in 0..40 { + h.step(); + std::thread::sleep(Duration::from_millis(30)); + } + let after = h.app.session.develop_of(first).unwrap().light.exposure; + assert!((after - before - 0.01 * TICKS as f64).abs() < 1e-6, "{before} → {after}: every tick, once"); + assert!(used <= 10, "{TICKS} ticks took {used} frames ({took:?}): they queued up"); + let rating = h.app.session.catalog.photo(first).unwrap().rating; + assert!(rating == 5 && rating_before != 5, "the key press ran once the ticks were in: {rating_before} → {rating}"); + stop.store(true, Ordering::SeqCst); + } + fn run(input: &[u8]) -> (Vec, Vec) { let mut out = Vec::new(); let mut calls = Vec::new(); serve_lines(input, &mut out, |m, _p| { calls.push(m); - Some(json!({"ok": true, "result": null})) + Some(Reply::Ready(json!({"ok": true, "result": null}))) }); let replies = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str::(l).unwrap()).collect(); (replies, calls) @@ -474,7 +916,7 @@ mod tests { let (tx, _rx) = channel::(); let server = std::thread::spawn(move || { let (s, _) = listener.accept().unwrap(); - serve(s, &tx, &egui::Context::default(), IDLE_TIMEOUT); + serve(s, &tx, &egui::Context::default(), Mode::Full, Some(IDLE_TIMEOUT)); }); let mut c = TcpStream::connect(addr).unwrap(); c.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); @@ -503,7 +945,7 @@ mod tests { let server = std::thread::spawn(move || { let (s, _) = listener.accept().unwrap(); let read = s.try_clone().unwrap(); - serve_lines(read, s, |_, _| Some(json!({"ok": true}))); + serve_lines(read, s, |_, _| Some(Reply::Ready(json!({"ok": true})))); }); let mut c = TcpStream::connect(addr).unwrap(); c.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); diff --git a/apps/lightcraft/src/logi_plugin.rs b/apps/lightcraft/src/logi_plugin.rs new file mode 100644 index 00000000000..81e0fa4731a --- /dev/null +++ b/apps/lightcraft/src/logi_plugin.rs @@ -0,0 +1,175 @@ +//! The LightCraft plugin for Logi Options+ (MX Creative Console): finding it, installing it +//! through Logi's own installer and removing it again (Settings ▸ Controls). +//! +//! The plugin is built from its own repository (C#, the Logi Actions SDK) into +//! `LightCraft.lplug4`. A LightCraft release carries that file next to its executable +//! (`LightCraft.lplug4` or `plugins/LightCraft.lplug4`); `LIGHTCRAFT_LOGI_PLUGIN` points at another +//! copy. Installing hands it to `LogiPluginServiceTool install-plugin` — what double-clicking a +//! `.lplug4` does — so Logi Options+ asks the user to confirm, installs the plugin and its default +//! profiles and reloads its plugin service by itself. Nothing else of Options+ is touched. +//! +//! Windows only for now: elsewhere there is no installer and Settings ▸ Controls says how to +//! install the plugin by hand. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use lightcraft_ui_egui::surface_plugin::{PluginInstaller, PluginStatus}; + +const PACKAGE: &str = "LightCraft.lplug4"; + +/// The installer for this platform, if it has one. +pub fn installer() -> Option> { + if cfg!(windows) { Some(Arc::new(Logi)) } else { None } +} + +struct Logi; + +fn env_dir(name: &str) -> Option { + std::env::var_os(name).filter(|v| !v.is_empty()).map(PathBuf::from) +} + +/// Logi's plugin installer (`LogiPluginServiceTool.exe`). +fn tool() -> Option { + let p = env_dir("ProgramFiles")?.join("Logi").join("LogiPluginService").join("LogiPluginServiceTool.exe"); + p.is_file().then_some(p) +} + +/// `%LOCALAPPDATA%\Logi\LogiPluginService`. +fn service_dir() -> Option { + Some(env_dir("LOCALAPPDATA")?.join("Logi").join("LogiPluginService")) +} + +/// `%LOCALAPPDATA%\Logi\LogiPluginService\PluginData\LightCraft`: the plugin's own data folder +/// (its `config.json` and its trust token, `token.txt`). +fn data_dir() -> Option { + Some(service_dir()?.join("PluginData").join("LightCraft")) +} + +/// The port in a plugin `config.json`. +fn config_port(text: &str) -> Option { + serde_json::from_str::(text).ok()?.get("port")?.as_u64().and_then(|p| u16::try_from(p).ok()) +} + +/// The plugin package that comes with this LightCraft. +fn package() -> Option { + if let Some(p) = env_dir("LIGHTCRAFT_LOGI_PLUGIN").filter(|p| p.is_file()) { + return Some(p); + } + let exe = std::env::current_exe().ok()?; + let dir = exe.parent()?; + [dir.join(PACKAGE), dir.join("plugins").join(PACKAGE)].into_iter().find(|p| p.is_file()) +} + +/// `version:` from a `LoupedeckPackage.yaml`. +fn yaml_version(text: &str) -> Option { + text.lines().find_map(|l| { + let v = l.trim().strip_prefix("version:")?.trim().trim_matches(['\'', '"']); + (!v.is_empty() && v.len() < 40).then(|| v.to_string()) + }) +} + +fn package_version(path: &Path) -> Option { + let len = std::fs::metadata(path).ok()?.len(); + if len > lightcraft_surface::zip::MAX_ARCHIVE as u64 { + return None; + } + let bytes = std::fs::read(path).ok()?; + let yaml = lightcraft_surface::zip::read_member(&bytes, "metadata/LoupedeckPackage.yaml").ok()?; + yaml_version(&String::from_utf8_lossy(&yaml)) +} + +fn run_tool(verb: &str, pkg: &Path) -> Result<(), String> { + let tool = tool().ok_or("Logi Options+ isn't installed on this computer")?; + let mut c = std::process::Command::new(tool); + c.arg(verb).arg(pkg); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + c.creation_flags(CREATE_NO_WINDOW); + } + let status = c.status().map_err(|e| format!("can't start Logi's installer: {e}"))?; + if status.success() { Ok(()) } else { Err(format!("Logi's installer stopped with {status}")) } +} + +impl PluginInstaller for Logi { + fn name(&self) -> String { + "LightCraft plugin for Logi Options+".into() + } + + fn status(&self) -> PluginStatus { + let installed = service_dir() + .map(|d| d.join("Plugins").join("LightCraft").join("metadata").join("LoupedeckPackage.yaml")) + .and_then(|p| std::fs::read_to_string(p).ok()) + .map(|t| yaml_version(&t).unwrap_or_else(|| "?".into())); + let pkg = package(); + PluginStatus { + host: tool().map(|_| "Logi Options+".to_string()), + installed, + package: pkg.as_deref().and_then(package_version), + package_path: pkg.map(|p| p.display().to_string()), + } + } + + fn install(&self, port: u16) -> Result { + let pkg = package().ok_or("this LightCraft has no plugin package with it")?; + // where the plugin finds LightCraft (it reads this before every connection attempt) + self.provision(None, port)?; + run_tool("install-plugin", &pkg)?; + Ok("Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.".into()) + } + + fn plugin_token(&self) -> Option { + let path = data_dir()?.join("token.txt"); + // a token is 64 hex digits; anything big isn't one + if std::fs::metadata(&path).ok()?.len() > 1024 { + return None; + } + std::fs::read_to_string(path).ok().map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) + } + + fn provision(&self, token: Option<&str>, port: u16) -> Result<(), String> { + let dir = data_dir().ok_or("no %LOCALAPPDATA%")?; + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + if let Some(t) = token { + let path = dir.join("token.txt"); + std::fs::write(&path, t).map_err(|e| format!("{}: {e}", path.display()))?; + } + let config = dir.join("config.json"); + let current = std::fs::read_to_string(&config).ok().and_then(|t| config_port(&t)); + if current != Some(port) { + std::fs::write(&config, format!("{{\"port\": {port}}}\n")).map_err(|e| format!("{}: {e}", config.display()))?; + } + Ok(()) + } + + fn uninstall(&self) -> Result { + let pkg = package().ok_or("this LightCraft has no plugin package with it; remove the plugin in Logi Options+")?; + run_tool("uninstall-plugin", &pkg)?; + Ok("Logi Options+ asks to remove the plugin: confirm it there.".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn package_versions_read_from_the_yaml() { + assert_eq!(yaml_version("type: plugin4\nname: LightCraft\nversion: 0.2.0\n"), Some("0.2.0".into())); + assert_eq!(yaml_version("version: '1.0'"), Some("1.0".into())); + assert_eq!(yaml_version("name: x"), None); + assert_eq!(yaml_version("version:"), None); + assert_eq!(config_port("{\"port\": 7981}"), Some(7981)); + assert_eq!(config_port("{\"port\": 70000}"), None); + assert_eq!(config_port("junk"), None); + // a file that isn't a package has no version (and doesn't crash) + let dir = std::env::temp_dir().join(format!("lc-logi-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let f = dir.join("bad.lplug4"); + std::fs::write(&f, b"not a zip").unwrap(); + assert_eq!(package_version(&f), None); + std::fs::remove_dir_all(&dir).ok(); + } +} diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 2193666fd18..45f612a3850 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -33,6 +33,7 @@ mod dialog_filter; mod editors; mod hdr_display; mod logging; +mod logi_plugin; #[cfg(target_os = "macos")] mod native_menu; #[cfg(target_os = "macos")] @@ -734,9 +735,60 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> backup_library: None, restore_library: None, system_theme: appearance::service(), + surface_store: surface_store(), + pick_surface_file: Some(Box::new(|| { + file_dialog() + .set_title(lightcraft_ui_egui::i18n::tr("Import Control Surface Setup")) + .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Control surface setups"), &["json", "lp5", "lcsurface"]) + .pick_file() + .map(|p| vec![p.to_string_lossy().to_string()]) + .unwrap_or_default() + })), + save_surface_file: Some(Box::new(|name: &str| { + file_dialog() + .set_title(lightcraft_ui_egui::i18n::tr("Export Control Surface Layout")) + .add_filter_nocase(lightcraft_ui_egui::i18n::tr("LightCraft surface layout"), &["lcsurface"]) + .set_file_name(name) + .save_file() + .map(|p| p.to_string_lossy().to_string()) + })), + surface_listener: None, + surface_plugin: logi_plugin::installer(), + } +} + +/// `/control-surfaces.json` (Settings, Controls; `docs/control-surfaces.md`). +struct SurfaceFile(std::path::PathBuf); + +/// The largest control-surface settings file read. +const MAX_SURFACE_FILE: u64 = 16 * 1024 * 1024; + +impl lightcraft_ui_egui::surface::SurfaceStore for SurfaceFile { + fn load(&self) -> Result, String> { + match std::fs::metadata(&self.0) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("{}: {e}", self.0.display())), + Ok(m) if m.len() > MAX_SURFACE_FILE => Err(format!("{} is too large", self.0.display())), + Ok(_) => std::fs::read_to_string(&self.0).map(Some).map_err(|e| format!("{}: {e}", self.0.display())), + } + } + + fn save(&self, text: &str) -> Result<(), String> { + if let Some(dir) = self.0.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + lightcraft_engine::export::write_file(&self.0.to_string_lossy(), text.as_bytes()) } } +/// Where control-surface settings live (none with `LIGHTCRAFT_NO_PREFS` or no settings folder). +fn surface_store() -> Option> { + if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() { + return None; + } + config_dir().map(|d| Box::new(SurfaceFile(d.join("control-surfaces.json"))) as Box) +} + /// The library session with the folders face models (`/models`) and slideshow templates /// (`/slideshow-templates`) are kept in. With [`Launch::Ask`] no library is opened yet: /// the window lists the recent ones. @@ -1027,10 +1079,25 @@ fn main() -> eframe::Result { app.ui.settings.gpu = false; app.notices.push(notice); } + // requests from --control and from the control-surface listener + let (control_tx, control_rx) = std::sync::mpsc::channel(); if let Some(port) = control_port { - let rx = control_server::start(port, cc.egui_ctx.clone()); - app = app.with_control(rx); + control_server::start(port, control_tx.clone(), cc.egui_ctx.clone()); + app = app.with_control(control_rx); + } else { + app = app.with_requests(control_rx); } + let listener_ctx = cc.egui_ctx.clone(); + let mut running: Option> = None; + app.services.surface_listener = Some(Box::new(move |port: Option| { + if let Some(stop) = running.take() { + stop.store(true, std::sync::atomic::Ordering::SeqCst); + } + if let Some(port) = port { + running = Some(control_server::start_surfaces(port, control_tx.clone(), listener_ctx.clone())?.0); + } + Ok(()) + })); if let Some(mut p) = problem { // imported once the user has chosen where (into the library, or the temporary session) p.pending_import = files; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 5a1e214dd2c..0e9d152054c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] craft-ui = { workspace = true } +resvg = { workspace = true } lightcraft-geom = { workspace = true } lightcraft-meta = { workspace = true } lightcraft-color = { workspace = true } @@ -21,6 +22,7 @@ lightcraft-catalog = { workspace = true } web-time = { workspace = true } lightcraft-engine = { workspace = true } lightcraft-slideshow = { workspace = true } +lightcraft-surface = { workspace = true } lightcraft-preview = { workspace = true } egui = { workspace = true } serde = { workspace = true } diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d4..92aae1395a1 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "Soubor {name} se nepodařilo přečíst: {e}", "Added {n} photo{}": "Přidáno fotografií: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})", + "Imported into the profile “{name}”": "Importováno do profilu „{name}“", + "Last import: {mapped} brought over, {dropped} left out": "Poslední import: převzato {mapped}, vynecháno {dropped}", + "Listening on 127.0.0.1:{port}": "Naslouchá na 127.0.0.1:{port}", + "Now: {context}": "Nyní: {context}", + "Paired: {name}": "Spárováno: {name}", + "Plugin {version} installed": "Plugin {version} nainstalován", + "Saved {path}": "Uloženo: {path}", + "Show page {name}": "Zobrazit stránku {name}", + "Switch to profile {name}": "Přepnout na profil {name}", + "{name} asks to control LightCraft: see Settings, Controls": "{name} žádá o ovládání LightCraftu: viz Nastavení, Ovladače", + "{name} asks to pair. Code: {code}": "{name} žádá o spárování. Kód: {code}" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 52ca94a524d..f6fa4845f2d 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2408,5 +2408,49 @@ "Import dropped files without review": "Importovat přetažené soubory bez kontroly", "An import is running": "Import už běží", "An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí", - "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky" + "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky", + "Controls": "Ovladače", + "Upright: Vertical": "Upright: Svisle", + "Upright: Level": "Upright: Vodorovně", + "Next Key Page": "Další stránka kláves", + "Previous Key Page": "Předchozí stránka kláves", + "Next Dial Page": "Další stránka kolečka", + "Previous Dial Page": "Předchozí stránka kolečka", + "Reset Dial Value": "Obnovit hodnotu kolečka", + "Show Unrated": "Zobrazit bez hodnocení", + "Any Label": "Libovolný štítek", + "Select Unrated": "Vybrat bez hodnocení", + "Select No Label": "Vybrat bez štítku", + "Reset Straighten": "Obnovit narovnání", + "No Mask": "Žádná maska", + "Previous Mask": "Předchozí maska", + "Next Mask": "Další maska", + "Select Previous Mask": "Vybrat předchozí masku", + "Select Next Mask": "Vybrat další masku", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ funguje přes plugin LightCraft. Každý knoflík a tlačítko dělá to, co říká jeho popisek, dokud ho tu nenastavíte nebo nepřenesete vlastní profil Loupedeck (přenese se jen rozložení).", + "Import a Loupedeck profile…": "Importovat profil Loupedeck…", + "Buttons": "Tlačítka", + "Loupedeck profile": "Profil Loupedeck", + "Up": "Nahoře", + "Touch to find": "Najít dotykem", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Dotkněte se klávesy, tlačítka nebo kolečka na zařízení a vybere se zde. Dokud je tato stránka otevřená, zařízení vaši fotografii nemění.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Přetáhněte akci ze seznamu na klávesu, tlačítko nebo kolečko na obrázku, nebo na některé klikněte (či se ho dotkněte na zařízení) a vyberte, co dělá.", + "A dial turns values: drop a value (or a page turn) on it.": "Kolečko mění hodnoty: přetáhněte na něj hodnotu (nebo listování stránkami).", + "Actions Ring": "Kruh akcí", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Přetáhněte akci ze seznamu na pozici, nebo klikněte na pozici a vyberte její akci. Kruh je stejný na každé stránce.", + "Colour knobs P1–P8": "Barevné knoflíky P1–P8", + "Tone knobs": "Tónové knoflíky", + "Control Dial and arrows": "Ovládací kolečko a šipky", + "Sat": "Syt", + "Lum": "Jas", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "Tlačítka Hue, Sat, Lum a Col/BW na konzoli přepínají, co P1–P8 posílají.", + "P1–P8 pressed": "P1–P8 stisknuté", + "Ring slot 1": "Pozice kruhu 1", + "Ring slot 2": "Pozice kruhu 2", + "Ring slot 3": "Pozice kruhu 3", + "Ring slot 4": "Pozice kruhu 4", + "Ring slot 5": "Pozice kruhu 5", + "Ring slot 6": "Pozice kruhu 6", + "Ring slot 7": "Pozice kruhu 7", + "Ring slot 8": "Pozice kruhu 8" } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f13647..b273320ae5e 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "{name} konnte nicht gelesen werden: {e}", "Added {n} photo{}": "{n} Foto{} hinzugefügt", "Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})", + "{name} asks to control LightCraft: see Settings, Controls": "{name} möchte LightCraft steuern: siehe Einstellungen, Steuerung", + "Now: {context}": "Jetzt: {context}", + "Imported into the profile “{name}”": "In das Profil „{name}“ importiert", + "Last import: {mapped} brought over, {dropped} left out": "Letzter Import: {mapped} übernommen, {dropped} ausgelassen", + "Saved {path}": "Gespeichert: {path}", + "Paired: {name}": "Gekoppelt: {name}", + "{name} asks to pair. Code: {code}": "{name} möchte gekoppelt werden. Code: {code}", + "Listening on 127.0.0.1:{port}": "Wartet auf 127.0.0.1:{port}", + "Plugin {version} installed": "Plugin {version} installiert", + "Show page {name}": "Seite {name} zeigen", + "Switch to profile {name}": "Zu Profil {name} wechseln" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e2205db782f..4fb4c5b9e83 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3440,5 +3440,235 @@ "Import dropped files without review": "Abgelegte Dateien ohne Prüfung importieren", "An import is running": "Ein Import läuft", "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", - "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst" + "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", + "1 Star": "1 Stern", + "2 Stars": "2 Sterne", + "3 Stars": "3 Sterne", + "4 Stars": "4 Sterne", + "5 Stars": "5 Sterne", + "A preset overwrites the tuning of every value.": "Eine Vorgabe überschreibt die Abstimmung aller Werte.", + "Acceleration": "Beschleunigung", + "Add page": "Seite hinzufügen", + "Add the built-in profiles": "Mitgelieferte Profile hinzufügen", + "Also for key presses": "Auch bei Tastendrücken", + "Any dialog": "Jedes Dialogfenster", + "Anywhere": "Überall", + "Apply movement every": "Bewegung anwenden alle", + "Apply to All": "Auf alle", + "Apply to Selected": "Auf Auswahl anwenden", + "Approve": "Erlauben", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "Ausgewogen: normales Reglergefühl mit spürbarer Beschleunigung im mittleren Bereich.", + "Before / After": "Vorher / Nachher", + "Big steps": "Große Schritte", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "Kräftig: schnellere Reaktion mit starker Beschleunigung für dynamische Bearbeitung.", + "Bottom edge": "Unterer Rand", + "Bring over my TactileBridge setup": "Meine TactileBridge-Einrichtung übernehmen", + "Brush Feather": "Pinsel: Weiche Kante", + "Brush Flow": "Pinsel: Fluss", + "Brush Size": "Pinselgröße", + "Cancel Dialog": "Dialog abbrechen", + "Cancel learning": "Lernen abbrechen", + "Coarse": "Grob", + "Colours are #RRGGBB.": "Farben als #RRGGBB.", + "Confirm Dialog": "Dialog bestätigen", + "Control Surface Input": "Eingabe vom Steuergerät", + "Control Surface Profile": "Steuergeräte-Profil", + "Control Surface Settings": "Steuergeräte-Einstellungen", + "Control Surface State": "Steuergeräte-Status", + "Controls": "Steuerung", + "Crop Orient.": "Ausrichtung", + "Deny": "Ablehnen", + "Dial": "Drehregler", + "Dial Feel": "Reglergefühl", + "Dialpad button 1": "Dialpad-Taste 1", + "Dialpad button 2": "Dialpad-Taste 2", + "Dialpad button 3": "Dialpad-Taste 3", + "Dialpad button 4": "Dialpad-Taste 4", + "Dials": "Regler", + "Dials Change All Selected Photos": "Regler ändern alle ausgewählten Fotos", + "Dials change every selected photo (one undo step per turn)": "Regler ändern jedes ausgewählte Foto (ein Rückgängig-Schritt pro Drehung)", + "Edit: Color": "Bearbeiten: Farbe", + "Edit: Detail": "Bearbeiten: Details", + "Edit: Effects": "Bearbeiten: Effekte", + "Edit: Geometry": "Bearbeiten: Geometrie", + "Edit: Light": "Bearbeiten: Licht", + "Edit: Optics": "Bearbeiten: Optik", + "Export Control Surface Layout": "Steuergeräte-Belegung exportieren", + "Export dialog": "Export-Dialog", + "Fashion": "Mode", + "Fast below": "Schnell unter", + "Fast turning": "Schnelles Drehen", + "Fine": "Fein", + "Fine steps": "Feine Schritte", + "Follow Context": "Kontext folgen", + "Forget": "Vergessen", + "Haptic feedback (where the device has it)": "Haptisches Feedback (wo das Gerät es hat)", + "Import Control Surface Setup": "Steuergeräte-Einrichtung importieren", + "Import dialog": "Import-Dialog", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "Importiert werden eine TactileBridge-settings.json (Reglergefühl, Anzeige, Farben, Werkzeug-Belegungen), ein Logi-Profil (.lp5) oder eine LightCraft-Belegungsdatei (.lcsurface).", + "Its acceleration": "Eigene Beschleunigung", + "Its speed": "Eigene Geschwindigkeit", + "Keep the surface's readout steady while turning": "Anzeige am Gerät beim Drehen ruhig halten", + "Key 1": "Taste 1", + "Key 2": "Taste 2", + "Key 3": "Taste 3", + "Key 4": "Taste 4", + "Key 5": "Taste 5", + "Key 6": "Taste 6", + "Key 7": "Taste 7", + "Key 8": "Taste 8", + "Key 9": "Taste 9", + "Key background": "Tastenhintergrund", + "Key text": "Tastentext", + "Keys": "Tasten", + "Learn: touch a control": "Lernen: ein Bedienelement berühren", + "Library (grid)": "Bibliothek (Raster)", + "Linear Grad": "Linearer Verlauf", + "Mask On/Off": "Maske an/aus", + "Masking: a mask selected": "Maskieren: Maske ausgewählt", + "Masking: brush": "Maskieren: Pinsel", + "Masking: gradient": "Maskieren: Verlauf", + "Moire": "Moiré", + "New Brush": "Neuer Pinsel", + "New Mask": "Neue Maske", + "Next": "Weiter", + "Next Page": "Nächste Seite", + "Next Profile": "Nächstes Profil", + "Next Surface Page": "Nächste Steuergeräte-Seite", + "No Rating": "Keine Bewertung", + "No surface is connected.": "Kein Steuergerät verbunden.", + "Nothing": "Nichts", + "On": "Ein", + "On-Screen Readout": "Bildschirmanzeige", + "Pages That Follow the App": "Seiten, die der App folgen", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "Parameter sind ein JSON-Objekt, z. B. {\"rating\": 5}", + "Port": "Port", + "Presets for every value:": "Vorgaben für alle Werte:", + "Press this key to put the value on the dial; press it again to give the dial back.": "Diese Taste legt den Wert auf den Drehregler; erneut drücken gibt den Regler zurück.", + "Previous": "Zurück", + "Previous Page": "Vorherige Seite", + "Previous Surface Page": "Vorherige Steuergeräte-Seite", + "Radial Grad": "Radialer Verlauf", + "Real Estate": "Immobilien", + "Remove Feather": "Entfernen: Weiche Kante", + "Remove Opacity": "Entfernen: Deckkraft", + "Remove Size": "Entfernen: Größe", + "Reset all": "Alle zurücksetzen", + "Roller": "Scrollrad", + "Show Surface Page": "Steuergeräte-Seite zeigen", + "Show the value or command in the window": "Wert oder Befehl im Fenster anzeigen", + "Show values on the keys and the dial display": "Werte auf den Tasten und der Regleranzeige zeigen", + "Shown for": "Anzeigedauer", + "Slow above": "Langsam über", + "Slow turning": "Langsames Drehen", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "Weich, ruhig und präzise: sanfte Beschleunigung für feine, kontrollierte Farbarbeit.", + "Surface Pages Follow the App": "Steuergeräte-Seiten folgen der App", + "Sync": "Synchronisieren", + "Top edge": "Oberer Rand", + "Turn a dial or press a key on the surface…": "Drehen Sie einen Regler oder drücken Sie eine Taste am Gerät…", + "Turn ends after": "Drehung endet nach", + "Turn every dial the other way": "Alle Regler andersherum drehen", + "Turn this value the other way": "Diesen Wert andersherum drehen", + "WB Picker": "WA-Pipette", + "Wedding": "Hochzeit", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "Großer Bereich: langsame Grundgeschwindigkeit mit sehr hoher Spitze für weite Änderungen.", + "Zoom 1:1": "Zoom 1:1", + "Zoom 200%": "Zoom 200 %", + "Zoom 400%": "Zoom 400 %", + "Zoom To Fit": "Einpassen", + "page": "Seite", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "Mit diesem LightCraft kommt ein neueres LightCraft-Plugin für Logi Options+.", + "All commands": "Alle Befehle", + "All pages": "Alle Seiten", + "Browse & Select": "Blättern und Auswählen", + "Check that the keypad shows the same code.": "Prüfen Sie, ob das Keypad denselben Code zeigt.", + "Coming later": "Folgt später", + "Command parameters (advanced)": "Befehlsparameter (erweitert)", + "Connected": "Verbunden", + "Connection": "Verbindung", + "Control Surface": "Bedienoberfläche", + "Install the plugin": "Plugin installieren", + "Installing the surface plugin": "Surface-Plugin wird installiert", + "Installing…": "Wird installiert…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "Tasten- und Radseiten dieses Profils. Eine Werkzeugseite erscheint von selbst, solange ihr Werkzeug offen ist (siehe unten).", + "Keys and Dials": "Tasten und Räder", + "LightCraft plugin for Logi Options+": "LightCraft-Plugin für Logi Options+", + "Logi Options+ Plugin": "Logi Options+-Plugin", + "Logi Options+ found": "Logi Options+ gefunden", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "Logi Options+ ist auf diesem Computer, aber das LightCraft-Plugin ist noch nicht installiert.", + "Logi Options+ not found": "Logi Options+ nicht gefunden", + "Logi Options+ asks to remove the plugin: confirm it there.": "Logi Options+ fragt nach dem Entfernen: Bestätigen Sie es dort.", + "No action matches.": "Keine Aktion passt.", + "Not connected": "Nicht verbunden", + "Nothing — click to set": "Nichts – zum Festlegen klicken", + "Offline": "Offline", + "One Value": "Ein Wert", + "Other": "Sonstiges", + "Pages and Profiles": "Seiten und Profile", + "Pages and Tools": "Seiten und Werkzeuge", + "Plugin not installed": "Plugin nicht installiert", + "Profiles and Setup": "Profile und Einrichtung", + "Rating & Labels": "Bewertung und Farben", + "Readout and Look": "Anzeige und Aussehen", + "Reinstall the plugin": "Plugin neu installieren", + "Remove the plugin": "Plugin entfernen", + "Removing the surface plugin": "Surface-Plugin wird entfernt", + "Removing…": "Wird entfernt…", + "Search actions": "Aktionen suchen", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "Die Unterstützung für dieses Gerät folgt später. Seine Tasten und Räder werden dann hier eingerichtet, wie die der MX Creative Console.", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "Die MX Creative Console spricht über das LightCraft-Plugin für Logi Options+ mit LightCraft. Beim Installieren wird das Plugin an Logi Options+ übergeben, das um Bestätigung bittet.", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "Dieses LightCraft kann es nicht installieren: Öffnen Sie LightCraft.lplug4 aus dem LightCraft-Download, um es in Logi Options+ zu installieren.", + "Tool page": "Werkzeugseite", + "Tool pages": "Werkzeugseiten", + "Type a name, then Add page, or Rename on a page.": "Namen eingeben, dann Seite hinzufügen, oder Umbenennen bei einer Seite.", + "Update the plugin": "Plugin aktualisieren", + "Use control surfaces": "Bedienoberflächen verwenden", + "What a control does on every page that leaves it empty": "Was ein Bedienelement auf jeder Seite tut, die es leer lässt", + "from All pages": "von Alle Seiten", + "Dialogs show their own page (OK, Cancel…)": "Dialogfenster zeigen ihre eigene Seite (OK, Abbrechen …)", + "Switch pages with what LightCraft shows (Crop, Masking…)": "Seiten mit dem wechseln, was LightCraft zeigt (Freistellen, Maskieren …)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "Logi Options+ fragt nach der Installation: Klicken Sie dort auf Fortfahren. Danach funktioniert die Konsole von selbst.", + "Upright: Vertical": "Upright: Vertikal", + "Upright: Level": "Upright: Waagerecht", + "Next Key Page": "Nächste Tastenseite", + "Previous Key Page": "Vorherige Tastenseite", + "Next Dial Page": "Nächste Radseite", + "Previous Dial Page": "Vorherige Radseite", + "Reset Dial Value": "Radwert zurücksetzen", + "Show Unrated": "Unbewertete zeigen", + "Any Label": "Beliebige Farbe", + "Select Unrated": "Unbewertete auswählen", + "Select No Label": "Ohne Farbe auswählen", + "Reset Straighten": "Gerade ausrichten zurücksetzen", + "No Mask": "Keine Maske", + "Previous Mask": "Vorherige Maske", + "Next Mask": "Nächste Maske", + "Select Previous Mask": "Vorherige Maske auswählen", + "Select Next Mask": "Nächste Maske auswählen", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Das Loupedeck+ arbeitet über das LightCraft-Plug-in. Jeder Regler und jede Taste tut, was ihre Beschriftung sagt, bis Sie sie hier einstellen oder Ihr eigenes Loupedeck-Profil übernehmen (nur die Belegung wird übernommen).", + "Import a Loupedeck profile…": "Loupedeck-Profil importieren …", + "Buttons": "Tasten", + "Loupedeck profile": "Loupedeck-Profil", + "Up": "Oben", + "Touch to find": "Durch Berühren finden", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Berühren Sie eine Taste, einen Knopf oder ein Rad am Gerät, um es hier auszuwählen. Solange diese Seite offen ist, ändert das Gerät Ihr Foto nicht.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Ziehen Sie eine Aktion aus der Liste auf eine Taste, einen Knopf oder ein Rad der Zeichnung, oder klicken Sie eines an (oder berühren Sie es am Gerät), um festzulegen, was es tut.", + "A dial turns values: drop a value (or a page turn) on it.": "Ein Rad dreht Werte: Legen Sie einen Wert (oder ein Blättern) darauf ab.", + "Actions Ring": "Aktionsring", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Ziehen Sie eine Aktion aus der Liste auf ein Feld, oder klicken Sie ein Feld an und wählen Sie seine Aktion. Der Ring ist auf jeder Seite gleich.", + "Colour knobs P1–P8": "Farbregler P1–P8", + "Tone knobs": "Tonregler", + "Control Dial and arrows": "Control Dial und Pfeiltasten", + "Sat": "Sätt", + "Lum": "Lum", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "Die Tasten Hue, Sat, Lum und Col/BW der Konsole schalten um, was P1–P8 senden.", + "P1–P8 pressed": "P1–P8 gedrückt", + "Ring slot 1": "Ringfeld 1", + "Ring slot 2": "Ringfeld 2", + "Ring slot 3": "Ringfeld 3", + "Ring slot 4": "Ringfeld 4", + "Ring slot 5": "Ringfeld 5", + "Ring slot 6": "Ringfeld 6", + "Ring slot 7": "Ringfeld 7", + "Ring slot 8": "Ringfeld 8" } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6e..e80546aa7c0 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "No se pudo leer {name}: {e}", "Added {n} photo{}": "{n} foto{0} añadida{0}", "Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})", + "{name} asks to control LightCraft: see Settings, Controls": "{name} pide controlar LightCraft: ve a Ajustes, Controles", + "Now: {context}": "Ahora: {context}", + "Imported into the profile “{name}”": "Importado en el perfil «{name}»", + "Last import: {mapped} brought over, {dropped} left out": "Última importación: {mapped} traídos, {dropped} omitidos", + "Saved {path}": "Guardado: {path}", + "Paired: {name}": "Emparejado: {name}", + "{name} asks to pair. Code: {code}": "{name} pide emparejarse. Código: {code}", + "Listening on 127.0.0.1:{port}": "Escuchando en 127.0.0.1:{port}", + "Plugin {version} installed": "Complemento {version} instalado", + "Show page {name}": "Mostrar la página {name}", + "Switch to profile {name}": "Cambiar al perfil {name}" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 888af077ff2..7d34b77f1c0 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2358,5 +2358,240 @@ "Import dropped files without review": "Importar los archivos soltados sin revisión", "An import is running": "Hay una importación en curso", "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", - "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos" + "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", + "1 Star": "1 estrella", + "2 Stars": "2 estrellas", + "3 Stars": "3 estrellas", + "4 Stars": "4 estrellas", + "5 Stars": "5 estrellas", + "A preset overwrites the tuning of every value.": "Un ajuste predefinido sobrescribe el ajuste de todos los valores.", + "Acceleration": "Aceleración", + "Add page": "Añadir página", + "Add the built-in profiles": "Añadir los perfiles incluidos", + "Also for key presses": "También al pulsar teclas", + "Any dialog": "Cualquier diálogo", + "Anywhere": "En cualquier lugar", + "Apply movement every": "Aplicar el movimiento cada", + "Apply to All": "Aplicar a todas", + "Apply to Selected": "Aplicar a la selección", + "Approve": "Aprobar", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "Equilibrado: un tacto estándar con aceleración ágil en el rango medio.", + "Before / After": "Antes / Después", + "Big steps": "Pasos grandes", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "Audaz: respuesta más rápida con aceleración fuerte para ediciones dinámicas.", + "Bottom edge": "Borde inferior", + "Bring over my TactileBridge setup": "Traer mi configuración de TactileBridge", + "Brush Feather": "Pincel: desvanecimiento", + "Brush Flow": "Pincel: flujo", + "Brush Size": "Tamaño del pincel", + "Cancel Dialog": "Cancelar diálogo", + "Cancel learning": "Cancelar aprendizaje", + "Coarse": "Grueso", + "Colours are #RRGGBB.": "Los colores son #RRGGBB.", + "Confirm Dialog": "Confirmar diálogo", + "Control Surface Input": "Entrada de la superficie de control", + "Control Surface Profile": "Perfil de la superficie de control", + "Control Surface Settings": "Ajustes de la superficie de control", + "Control Surface State": "Estado de la superficie de control", + "Controls": "Controles", + "Crop Orient.": "Orientación", + "Deny": "Rechazar", + "Dial": "Dial", + "Dial Feel": "Tacto del dial", + "Dialpad button 1": "Botón 1 del Dialpad", + "Dialpad button 2": "Botón 2 del Dialpad", + "Dialpad button 3": "Botón 3 del Dialpad", + "Dialpad button 4": "Botón 4 del Dialpad", + "Dials": "Diales", + "Dials Change All Selected Photos": "Los diales cambian todas las fotos seleccionadas", + "Dials change every selected photo (one undo step per turn)": "Los diales cambian cada foto seleccionada (un paso de deshacer por giro)", + "Edit: Color": "Editar: Color", + "Edit: Detail": "Editar: Detalle", + "Edit: Effects": "Editar: Efectos", + "Edit: Geometry": "Editar: Geometría", + "Edit: Light": "Editar: Luz", + "Edit: Optics": "Editar: Óptica", + "Export Control Surface Layout": "Exportar la disposición de la superficie de control", + "Export dialog": "Diálogo de exportación", + "Fashion": "Moda", + "Fast below": "Rápido por debajo de", + "Fast turning": "Giro rápido", + "Fine": "Fino", + "Fine steps": "Pasos finos", + "Follow Context": "Seguir el contexto", + "Forget": "Olvidar", + "Haptic feedback (where the device has it)": "Respuesta háptica (si el dispositivo la tiene)", + "Import Control Surface Setup": "Importar configuración de superficie de control", + "Import dialog": "Diálogo de importación", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "Importa un settings.json de TactileBridge (tacto del dial, indicador, colores, disposiciones por herramienta), un perfil de Logi (.lp5) o un archivo de disposición de LightCraft (.lcsurface).", + "Its acceleration": "Su aceleración", + "Its speed": "Su velocidad", + "Keep the surface's readout steady while turning": "Mantener estable la lectura del dispositivo al girar", + "Key 1": "Tecla 1", + "Key 2": "Tecla 2", + "Key 3": "Tecla 3", + "Key 4": "Tecla 4", + "Key 5": "Tecla 5", + "Key 6": "Tecla 6", + "Key 7": "Tecla 7", + "Key 8": "Tecla 8", + "Key 9": "Tecla 9", + "Key background": "Fondo de las teclas", + "Key text": "Texto de las teclas", + "Keys": "Teclas", + "Learn: touch a control": "Aprender: toca un control", + "Library (grid)": "Biblioteca (cuadrícula)", + "Linear Grad": "Degradado lineal", + "Mask": "Máscara", + "Mask On/Off": "Máscara sí/no", + "Masking: a mask selected": "Máscaras: una máscara seleccionada", + "Masking: brush": "Máscaras: pincel", + "Masking: gradient": "Máscaras: degradado", + "Moire": "Muaré", + "New Brush": "Pincel nuevo", + "New Mask": "Máscara nueva", + "Next": "Siguiente", + "Next Page": "Página siguiente", + "Next Profile": "Perfil siguiente", + "Next Surface Page": "Página siguiente de la superficie", + "Next page": "Página siguiente", + "No Rating": "Sin valoración", + "No surface is connected.": "No hay ninguna superficie conectada.", + "Nothing": "Nada", + "On": "Sí", + "On-Screen Readout": "Indicador en pantalla", + "Page": "Página", + "Pages That Follow the App": "Páginas que siguen a la app", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "Los parámetros son un objeto JSON, p. ej. {\"rating\": 5}", + "Port": "Puerto", + "Presets for every value:": "Ajustes para todos los valores:", + "Press this key to put the value on the dial; press it again to give the dial back.": "Pulsa esta tecla para llevar el valor al dial; púlsala de nuevo para devolverlo.", + "Previous": "Anterior", + "Previous Page": "Página anterior", + "Previous Surface Page": "Página anterior de la superficie", + "Previous page": "Página anterior", + "Radial Grad": "Degradado radial", + "Real Estate": "Inmobiliaria", + "Remove Feather": "Quitar: desvanecimiento", + "Remove Opacity": "Quitar: opacidad", + "Remove Size": "Quitar: tamaño", + "Reset all": "Restablecer todo", + "Roller": "Rueda", + "Show Surface Page": "Mostrar página de la superficie", + "Show the value or command in the window": "Mostrar el valor o comando en la ventana", + "Show values on the keys and the dial display": "Mostrar valores en las teclas y en la pantalla del dial", + "Shown for": "Mostrar durante", + "Slow above": "Lento por encima de", + "Slow turning": "Giro lento", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "Suave y preciso: aceleración delicada para un trabajo de color controlado.", + "Surface Pages Follow the App": "Las páginas de la superficie siguen a la app", + "Sync": "Sincronizar", + "Top edge": "Borde superior", + "Turn a dial or press a key on the surface…": "Gira un dial o pulsa una tecla en la superficie…", + "Turn ends after": "El giro termina tras", + "Turn every dial the other way": "Invertir el sentido de todos los diales", + "Turn this value the other way": "Invertir el sentido de este valor", + "WB Picker": "Selector de BB", + "Wedding": "Boda", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "Amplio rango: velocidad base lenta con un pico muy alto para ajustes amplios.", + "Zoom 1:1": "Zoom 1:1", + "Zoom 200%": "Zoom 200 %", + "Zoom 400%": "Zoom 400 %", + "Zoom To Fit": "Ajustar", + "page": "página", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "Esta versión de LightCraft trae un complemento más reciente para Logi Options+.", + "All commands": "Todos los comandos", + "All pages": "Todas las páginas", + "Browse & Select": "Navegar y seleccionar", + "Check that the keypad shows the same code.": "Comprueba que el teclado muestre el mismo código.", + "Coming later": "Próximamente", + "Command parameters (advanced)": "Parámetros del comando (avanzado)", + "Connected": "Conectado", + "Connection": "Conexión", + "Control Surface": "Superficie de control", + "Install the plugin": "Instalar el complemento", + "Installing the surface plugin": "Instalando el complemento", + "Installing…": "Instalando…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "Páginas de teclas y de diales de este perfil. Una página de herramienta aparece sola mientras su herramienta está abierta (ver abajo).", + "Keys and Dials": "Teclas y diales", + "LightCraft plugin for Logi Options+": "Complemento de LightCraft para Logi Options+", + "Logi Options+ Plugin": "Complemento de Logi Options+", + "Logi Options+ found": "Logi Options+ encontrado", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "Logi Options+ está en este equipo, pero el complemento de LightCraft aún no está instalado.", + "Logi Options+ not found": "Logi Options+ no encontrado", + "Logi Options+ asks to remove the plugin: confirm it there.": "Logi Options+ pide quitar el complemento: confírmalo allí.", + "No action matches.": "Ninguna acción coincide.", + "Not connected": "No conectado", + "Nothing — click to set": "Nada: haz clic para asignar", + "Offline": "Sin conexión", + "One Value": "Un valor", + "Other": "Otros", + "Pages and Profiles": "Páginas y perfiles", + "Pages and Tools": "Páginas y herramientas", + "Plugin not installed": "Complemento no instalado", + "Profiles and Setup": "Perfiles y configuración", + "Rating & Labels": "Valoración y etiquetas", + "Readout and Look": "Indicador y aspecto", + "Reinstall the plugin": "Reinstalar el complemento", + "Remove the plugin": "Quitar el complemento", + "Removing the surface plugin": "Quitando el complemento", + "Removing…": "Quitando…", + "Search actions": "Buscar acciones", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "La compatibilidad con esta superficie llegará más adelante. Sus teclas y diales se configurarán aquí, como los de la MX Creative Console.", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "La MX Creative Console se comunica con LightCraft a través del complemento de LightCraft para Logi Options+. Al instalar, el complemento pasa a Logi Options+, que te pide confirmación.", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "Este LightCraft no puede instalarlo: abre LightCraft.lplug4 de la descarga de LightCraft para instalarlo en Logi Options+.", + "Tool page": "Página de herramienta", + "Tool pages": "Páginas de herramientas", + "Type a name, then Add page, or Rename on a page.": "Escribe un nombre y luego Añadir página, o Renombrar en una página.", + "Update the plugin": "Actualizar el complemento", + "Use control surfaces": "Usar superficies de control", + "What a control does on every page that leaves it empty": "Lo que hace un control en cada página que lo deja vacío", + "from All pages": "de Todas las páginas", + "Dialogs show their own page (OK, Cancel…)": "Los diálogos muestran su propia página (Aceptar, Cancelar…)", + "Switch pages with what LightCraft shows (Crop, Masking…)": "Cambiar de página según lo que muestra LightCraft (Recortar, Máscaras…)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "Logi Options+ pide instalar el complemento: haz clic en Continuar allí. Después la consola funciona sola.", + "Display": "Pantalla", + "Upright: Vertical": "Upright: Vertical", + "Upright: Level": "Upright: Nivelado", + "Next Key Page": "Página de teclas siguiente", + "Previous Key Page": "Página de teclas anterior", + "Next Dial Page": "Página de diales siguiente", + "Previous Dial Page": "Página de diales anterior", + "Reset Dial Value": "Restablecer valor del dial", + "Show Unrated": "Mostrar sin valorar", + "Any Label": "Cualquier etiqueta", + "Select Unrated": "Seleccionar sin valorar", + "Select No Label": "Seleccionar sin etiqueta", + "Reset Straighten": "Restablecer enderezado", + "No Mask": "Sin máscara", + "Previous Mask": "Máscara anterior", + "Next Mask": "Máscara siguiente", + "Select Previous Mask": "Seleccionar la máscara anterior", + "Select Next Mask": "Seleccionar la máscara siguiente", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "El Loupedeck+ funciona a través del complemento de LightCraft. Cada rueda y cada botón hace lo que indica su rótulo hasta que lo configure aquí o traiga su propio perfil de Loupedeck (solo se trae la distribución).", + "Import a Loupedeck profile…": "Importar un perfil de Loupedeck…", + "Buttons": "Botones", + "Loupedeck profile": "Perfil de Loupedeck", + "Up": "Arriba", + "Touch to find": "Buscar tocando", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Toque una tecla, un botón o un dial del dispositivo para seleccionarlo aquí. Mientras esta página esté abierta, el dispositivo no cambia su foto.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Arrastre una acción de la lista a una tecla, botón o dial del dibujo, o haga clic en uno (o tóquelo en el dispositivo) para elegir qué hace.", + "A dial turns values: drop a value (or a page turn) on it.": "Un dial gira valores: suelte en él un valor (o un cambio de página).", + "Actions Ring": "Anillo de acciones", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Arrastre una acción de la lista a una posición, o haga clic en una posición y elija su acción. El anillo es igual en todas las páginas.", + "Colour knobs P1–P8": "Mandos de color P1–P8", + "Tone knobs": "Mandos de tono", + "Control Dial and arrows": "Control Dial y flechas", + "Sat": "Sat", + "Lum": "Lum", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "Los botones Hue, Sat, Lum y Col/BW de la consola cambian lo que envían P1–P8.", + "P1–P8 pressed": "P1–P8 pulsados", + "Ring slot 1": "Posición del anillo 1", + "Ring slot 2": "Posición del anillo 2", + "Ring slot 3": "Posición del anillo 3", + "Ring slot 4": "Posición del anillo 4", + "Ring slot 5": "Posición del anillo 5", + "Ring slot 6": "Posición del anillo 6", + "Ring slot 7": "Posición del anillo 7", + "Ring slot 8": "Posición del anillo 8" } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e0..2458fb1de38 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "Impossible de lire {name} : {e}", "Added {n} photo{}": "{n} photo{} ajoutée(s)", "Where should the Lightroom catalog “{catalog}” go?": "Où importer le catalogue Lightroom « {catalog} » ?", - "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})" + "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})", + "{name} asks to control LightCraft: see Settings, Controls": "{name} demande à piloter LightCraft : voir Réglages, Contrôles", + "Now: {context}": "Maintenant : {context}", + "Imported into the profile “{name}”": "Importé dans le profil « {name} »", + "Last import: {mapped} brought over, {dropped} left out": "Dernier import : {mapped} repris, {dropped} laissés de côté", + "Saved {path}": "Enregistré : {path}", + "Paired: {name}": "Appairé : {name}", + "{name} asks to pair. Code: {code}": "{name} demande l’appairage. Code : {code}", + "Listening on 127.0.0.1:{port}": "À l’écoute sur 127.0.0.1:{port}", + "Plugin {version} installed": "Plugin {version} installé", + "Show page {name}": "Afficher la page {name}", + "Switch to profile {name}": "Passer au profil {name}" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 3278d6ccda6..c332b281a80 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2390,5 +2390,240 @@ "Checking recent libraries": "Vérification des bibliothèques récentes", "The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte", "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", - "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :" + "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", + "1 Star": "1 étoile", + "2 Stars": "2 étoiles", + "3 Stars": "3 étoiles", + "4 Stars": "4 étoiles", + "5 Stars": "5 étoiles", + "A preset overwrites the tuning of every value.": "Un préréglage remplace le réglage de toutes les valeurs.", + "Acceleration": "Accélération", + "Add page": "Ajouter une page", + "Add the built-in profiles": "Ajouter les profils intégrés", + "Also for key presses": "Aussi pour les appuis de touche", + "Any dialog": "Toute boîte de dialogue", + "Anywhere": "Partout", + "Apply movement every": "Appliquer le mouvement toutes les", + "Apply to All": "Appliquer à toutes", + "Apply to Selected": "Appliquer à la sélection", + "Approve": "Approuver", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "Équilibré : un toucher standard avec une accélération vive en milieu de course.", + "Before / After": "Avant / Après", + "Big steps": "Grands pas", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "Affirmé : réponse plus rapide et forte accélération pour des retouches dynamiques.", + "Bottom edge": "Bord inférieur", + "Bring over my TactileBridge setup": "Reprendre ma configuration TactileBridge", + "Brush Feather": "Pinceau : contour progressif", + "Brush Flow": "Pinceau : flux", + "Brush Size": "Taille du pinceau", + "Cancel Dialog": "Annuler la boîte de dialogue", + "Cancel learning": "Annuler l’apprentissage", + "Coarse": "Grossier", + "Colours are #RRGGBB.": "Les couleurs sont au format #RRGGBB.", + "Confirm Dialog": "Valider la boîte de dialogue", + "Control Surface Input": "Saisie de la surface de contrôle", + "Control Surface Profile": "Profil de la surface de contrôle", + "Control Surface Settings": "Réglages de la surface de contrôle", + "Control Surface State": "État de la surface de contrôle", + "Controls": "Contrôles", + "Crop Orient.": "Orientation", + "Deny": "Refuser", + "Dial": "Molette", + "Dial Feel": "Toucher de la molette", + "Dialpad button 1": "Bouton 1 du Dialpad", + "Dialpad button 2": "Bouton 2 du Dialpad", + "Dialpad button 3": "Bouton 3 du Dialpad", + "Dialpad button 4": "Bouton 4 du Dialpad", + "Dials": "Molettes", + "Dials Change All Selected Photos": "Les molettes modifient toutes les photos sélectionnées", + "Dials change every selected photo (one undo step per turn)": "Les molettes modifient chaque photo sélectionnée (une annulation par rotation)", + "Edit: Color": "Modifier : Couleur", + "Edit: Detail": "Modifier : Détail", + "Edit: Effects": "Modifier : Effets", + "Edit: Geometry": "Modifier : Géométrie", + "Edit: Light": "Modifier : Lumière", + "Edit: Optics": "Modifier : Optique", + "Export Control Surface Layout": "Exporter la disposition de la surface de contrôle", + "Export dialog": "Boîte d’exportation", + "Fashion": "Mode", + "Fast below": "Rapide sous", + "Fast turning": "Rotation rapide", + "Fine": "Fin", + "Fine steps": "Pas fins", + "Follow Context": "Suivre le contexte", + "Forget": "Oublier", + "Haptic feedback (where the device has it)": "Retour haptique (si l’appareil en dispose)", + "Import Control Surface Setup": "Importer une configuration de surface de contrôle", + "Import dialog": "Boîte d’importation", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "L’import accepte un settings.json de TactileBridge (toucher, affichage, couleurs, dispositions par outil), un profil Logi (.lp5) ou un fichier de disposition LightCraft (.lcsurface).", + "Its acceleration": "Son accélération", + "Its speed": "Sa vitesse", + "Keep the surface's readout steady while turning": "Garder l’affichage de l’appareil stable pendant la rotation", + "Key 1": "Touche 1", + "Key 2": "Touche 2", + "Key 3": "Touche 3", + "Key 4": "Touche 4", + "Key 5": "Touche 5", + "Key 6": "Touche 6", + "Key 7": "Touche 7", + "Key 8": "Touche 8", + "Key 9": "Touche 9", + "Key background": "Fond des touches", + "Key text": "Texte des touches", + "Keys": "Touches", + "Learn: touch a control": "Apprendre : touchez une commande", + "Library (grid)": "Bibliothèque (grille)", + "Linear Grad": "Dégradé linéaire", + "Mask": "Masque", + "Mask On/Off": "Masque oui/non", + "Masking: a mask selected": "Masquage : un masque sélectionné", + "Masking: brush": "Masquage : pinceau", + "Masking: gradient": "Masquage : dégradé", + "Moire": "Moiré", + "New Brush": "Nouveau pinceau", + "New Mask": "Nouveau masque", + "Next": "Suivante", + "Next Page": "Page suivante", + "Next Profile": "Profil suivant", + "Next Surface Page": "Page suivante de la surface", + "Next page": "Page suivante", + "No Rating": "Sans note", + "No surface is connected.": "Aucune surface n’est connectée.", + "Nothing": "Rien", + "On": "Activé", + "On-Screen Readout": "Affichage à l’écran", + "Page": "Page", + "Pages That Follow the App": "Pages qui suivent l’app", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "Les paramètres sont un objet JSON, p. ex. {\"rating\": 5}", + "Port": "Port", + "Presets for every value:": "Préréglages pour toutes les valeurs :", + "Press this key to put the value on the dial; press it again to give the dial back.": "Appuyez sur cette touche pour mettre la valeur sur la molette ; appuyez à nouveau pour la rendre.", + "Previous": "Précédente", + "Previous Page": "Page précédente", + "Previous Surface Page": "Page précédente de la surface", + "Previous page": "Page précédente", + "Radial Grad": "Dégradé radial", + "Real Estate": "Immobilier", + "Remove Feather": "Supprimer : contour progressif", + "Remove Opacity": "Supprimer : opacité", + "Remove Size": "Supprimer : taille", + "Reset all": "Tout réinitialiser", + "Roller": "Roulette", + "Show Surface Page": "Afficher une page de la surface", + "Show the value or command in the window": "Afficher la valeur ou la commande dans la fenêtre", + "Show values on the keys and the dial display": "Afficher les valeurs sur les touches et l’écran de la molette", + "Shown for": "Affiché pendant", + "Slow above": "Lent au-dessus de", + "Slow turning": "Rotation lente", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "Doux et précis : accélération modérée pour un travail des couleurs délicat et maîtrisé.", + "Surface Pages Follow the App": "Les pages de la surface suivent l’app", + "Sync": "Synchroniser", + "Top edge": "Bord supérieur", + "Turn a dial or press a key on the surface…": "Tournez une molette ou appuyez sur une touche de la surface…", + "Turn ends after": "La rotation se termine après", + "Turn every dial the other way": "Inverser le sens de toutes les molettes", + "Turn this value the other way": "Inverser le sens de cette valeur", + "WB Picker": "Pipette BdB", + "Wedding": "Mariage", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "Grande amplitude : vitesse de base lente et pointe très élevée pour les grands réglages.", + "Zoom 1:1": "Zoom 1:1", + "Zoom 200%": "Zoom 200 %", + "Zoom 400%": "Zoom 400 %", + "Zoom To Fit": "Ajuster", + "page": "page", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "Ce LightCraft contient un plugin plus récent pour Logi Options+.", + "All commands": "Toutes les commandes", + "All pages": "Toutes les pages", + "Browse & Select": "Parcourir et sélectionner", + "Check that the keypad shows the same code.": "Vérifiez que le pavé affiche le même code.", + "Coming later": "À venir", + "Command parameters (advanced)": "Paramètres de la commande (avancé)", + "Connected": "Connecté", + "Connection": "Connexion", + "Control Surface": "Surface de contrôle", + "Install the plugin": "Installer le plugin", + "Installing the surface plugin": "Installation du plugin", + "Installing…": "Installation…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "Pages de touches et de molettes de ce profil. Une page d’outil s’affiche d’elle-même tant que son outil est ouvert (voir plus bas).", + "Keys and Dials": "Touches et molettes", + "LightCraft plugin for Logi Options+": "Plugin LightCraft pour Logi Options+", + "Logi Options+ Plugin": "Plugin Logi Options+", + "Logi Options+ found": "Logi Options+ trouvé", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "Logi Options+ est sur cet ordinateur, mais le plugin LightCraft n’est pas encore installé.", + "Logi Options+ not found": "Logi Options+ introuvable", + "Logi Options+ asks to remove the plugin: confirm it there.": "Logi Options+ demande de retirer le plugin : confirmez-le là-bas.", + "No action matches.": "Aucune action ne correspond.", + "Not connected": "Non connecté", + "Nothing — click to set": "Rien – cliquez pour définir", + "Offline": "Hors ligne", + "One Value": "Une valeur", + "Other": "Autres", + "Pages and Profiles": "Pages et profils", + "Pages and Tools": "Pages et outils", + "Plugin not installed": "Plugin non installé", + "Profiles and Setup": "Profils et configuration", + "Rating & Labels": "Notes et étiquettes", + "Readout and Look": "Affichage et apparence", + "Reinstall the plugin": "Réinstaller le plugin", + "Remove the plugin": "Retirer le plugin", + "Removing the surface plugin": "Retrait du plugin", + "Removing…": "Retrait…", + "Search actions": "Rechercher des actions", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "La prise en charge de cette surface viendra plus tard. Ses touches et molettes se régleront ici, comme celles de la MX Creative Console.", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "La MX Creative Console communique avec LightCraft via le plugin LightCraft pour Logi Options+. L’installation confie le plugin à Logi Options+, qui vous demande de confirmer.", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "Ce LightCraft ne peut pas l’installer : ouvrez LightCraft.lplug4 depuis le téléchargement de LightCraft pour l’installer dans Logi Options+.", + "Tool page": "Page d’outil", + "Tool pages": "Pages d’outils", + "Type a name, then Add page, or Rename on a page.": "Saisissez un nom, puis Ajouter une page, ou Renommer sur une page.", + "Update the plugin": "Mettre à jour le plugin", + "Use control surfaces": "Utiliser des surfaces de contrôle", + "What a control does on every page that leaves it empty": "Ce que fait une commande sur chaque page qui la laisse vide", + "from All pages": "de Toutes les pages", + "Dialogs show their own page (OK, Cancel…)": "Les boîtes de dialogue affichent leur propre page (OK, Annuler…)", + "Switch pages with what LightCraft shows (Crop, Masking…)": "Changer de page selon ce qu’affiche LightCraft (Recadrage, Masquage…)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "Logi Options+ demande d’installer le plugin : cliquez sur Continuer. La console fonctionne ensuite d’elle-même.", + "Display": "Affichage", + "Upright: Vertical": "Upright : Vertical", + "Upright: Level": "Upright : Niveau", + "Next Key Page": "Page de touches suivante", + "Previous Key Page": "Page de touches précédente", + "Next Dial Page": "Page de molettes suivante", + "Previous Dial Page": "Page de molettes précédente", + "Reset Dial Value": "Réinitialiser la valeur de la molette", + "Show Unrated": "Afficher les non notées", + "Any Label": "Toute étiquette", + "Select Unrated": "Sélectionner les non notées", + "Select No Label": "Sélectionner sans étiquette", + "Reset Straighten": "Réinitialiser le redressement", + "No Mask": "Aucun masque", + "Previous Mask": "Masque précédent", + "Next Mask": "Masque suivant", + "Select Previous Mask": "Sélectionner le masque précédent", + "Select Next Mask": "Sélectionner le masque suivant", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Le Loupedeck+ passe par le module LightCraft. Chaque molette et chaque bouton fait ce que dit son étiquette jusqu’à ce que vous le régliez ici ou repreniez votre propre profil Loupedeck (seule la disposition est reprise).", + "Import a Loupedeck profile…": "Importer un profil Loupedeck…", + "Buttons": "Boutons", + "Loupedeck profile": "Profil Loupedeck", + "Up": "En haut", + "Touch to find": "Trouver au toucher", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Touchez une touche, un bouton ou une molette de l'appareil pour la sélectionner ici. Tant que cette page est ouverte, l'appareil ne modifie pas votre photo.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Faites glisser une action de la liste sur une touche, un bouton ou une molette du dessin, ou cliquez-en un (ou touchez-le sur l'appareil) pour choisir ce qu'il fait.", + "A dial turns values: drop a value (or a page turn) on it.": "Une molette fait tourner des valeurs : déposez-y une valeur (ou un changement de page).", + "Actions Ring": "Anneau d'actions", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Faites glisser une action de la liste sur un emplacement, ou cliquez sur un emplacement et choisissez son action. L'anneau est le même sur chaque page.", + "Colour knobs P1–P8": "Boutons de couleur P1–P8", + "Tone knobs": "Boutons de tonalité", + "Control Dial and arrows": "Control Dial et flèches", + "Sat": "Sat", + "Lum": "Lum", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "Les boutons Hue, Sat, Lum et Col/BW de la console changent ce qu'envoient P1–P8.", + "P1–P8 pressed": "P1–P8 enfoncés", + "Ring slot 1": "Emplacement 1 de l'anneau", + "Ring slot 2": "Emplacement 2 de l'anneau", + "Ring slot 3": "Emplacement 3 de l'anneau", + "Ring slot 4": "Emplacement 4 de l'anneau", + "Ring slot 5": "Emplacement 5 de l'anneau", + "Ring slot 6": "Emplacement 6 de l'anneau", + "Ring slot 7": "Emplacement 7 de l'anneau", + "Ring slot 8": "Emplacement 8 de l'anneau" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e945..8f98b88f051 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "Impossibile leggere {name}: {e}", "Added {n} photo{}": "Foto aggiunte: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Dove importare il catalogo Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})", + "{name} asks to control LightCraft: see Settings, Controls": "{name} chiede di controllare LightCraft: vedi Impostazioni, Controlli", + "Now: {context}": "Ora: {context}", + "Imported into the profile “{name}”": "Importato nel profilo «{name}»", + "Last import: {mapped} brought over, {dropped} left out": "Ultima importazione: {mapped} trasferiti, {dropped} esclusi", + "Saved {path}": "Salvato: {path}", + "Paired: {name}": "Associato: {name}", + "{name} asks to pair. Code: {code}": "{name} chiede di associarsi. Codice: {code}", + "Listening on 127.0.0.1:{port}": "In ascolto su 127.0.0.1:{port}", + "Plugin {version} installed": "Plugin {version} installato", + "Show page {name}": "Mostra la pagina {name}", + "Switch to profile {name}": "Passa al profilo {name}" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index e159fd47d15..5656f10c5df 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2361,5 +2361,49 @@ "Import dropped files without review": "Importa i file rilasciati senza revisione", "An import is running": "Un'importazione è in corso", "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", - "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto" + "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", + "Controls": "Controller", + "Upright: Vertical": "Upright: Verticale", + "Upright: Level": "Upright: Livellato", + "Next Key Page": "Pagina tasti successiva", + "Previous Key Page": "Pagina tasti precedente", + "Next Dial Page": "Pagina ghiere successiva", + "Previous Dial Page": "Pagina ghiere precedente", + "Reset Dial Value": "Ripristina valore ghiera", + "Show Unrated": "Mostra senza valutazione", + "Any Label": "Qualsiasi etichetta", + "Select Unrated": "Seleziona senza valutazione", + "Select No Label": "Seleziona senza etichetta", + "Reset Straighten": "Ripristina raddrizzamento", + "No Mask": "Nessuna maschera", + "Previous Mask": "Maschera precedente", + "Next Mask": "Maschera successiva", + "Select Previous Mask": "Seleziona la maschera precedente", + "Select Next Mask": "Seleziona la maschera successiva", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Il Loupedeck+ funziona tramite il plug-in di LightCraft. Ogni manopola e ogni pulsante fa ciò che dice la sua etichetta finché non lo imposti qui o non importi il tuo profilo Loupedeck (viene importata solo la disposizione).", + "Import a Loupedeck profile…": "Importa un profilo Loupedeck…", + "Buttons": "Pulsanti", + "Loupedeck profile": "Profilo Loupedeck", + "Up": "In alto", + "Touch to find": "Trova toccando", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Tocca un tasto, un pulsante o una manopola del dispositivo per selezionarlo qui. Finché questa pagina è aperta, il dispositivo non modifica la foto.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Trascina un'azione dall'elenco su un tasto, un pulsante o una manopola del disegno, oppure fai clic su uno (o toccalo sul dispositivo) per scegliere cosa fa.", + "A dial turns values: drop a value (or a page turn) on it.": "Una manopola regola valori: rilascia su di essa un valore (o un cambio pagina).", + "Actions Ring": "Anello delle azioni", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Trascina un'azione dall'elenco su una posizione, oppure fai clic su una posizione e scegli la sua azione. L'anello è uguale in ogni pagina.", + "Colour knobs P1–P8": "Manopole colore P1–P8", + "Tone knobs": "Manopole di tono", + "Control Dial and arrows": "Control Dial e frecce", + "Sat": "Sat", + "Lum": "Lum", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "I pulsanti Hue, Sat, Lum e Col/BW della console cambiano ciò che inviano P1–P8.", + "P1–P8 pressed": "P1–P8 premuti", + "Ring slot 1": "Posizione anello 1", + "Ring slot 2": "Posizione anello 2", + "Ring slot 3": "Posizione anello 3", + "Ring slot 4": "Posizione anello 4", + "Ring slot 5": "Posizione anello 5", + "Ring slot 6": "Posizione anello 6", + "Ring slot 7": "Posizione anello 7", + "Ring slot 8": "Posizione anello 8" } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16dc..9d9711cf71a 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "{name} を読み取れませんでした: {e}", "Added {n} photo{}": "{n}枚を追加しました{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom カタログ「{catalog}」をどこに読み込みますか?", - "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}", + "{name} asks to control LightCraft: see Settings, Controls": "{name} が LightCraft の操作を求めています:設定の「コントロール」を確認", + "Now: {context}": "現在:{context}", + "Imported into the profile “{name}”": "プロファイル「{name}」に読み込みました", + "Last import: {mapped} brought over, {dropped} left out": "前回の読み込み:{mapped} 件を移行、{dropped} 件は対象外", + "Saved {path}": "保存しました:{path}", + "Paired: {name}": "ペアリング済み:{name}", + "{name} asks to pair. Code: {code}": "{name} がペアリングを求めています。コード:{code}", + "Listening on 127.0.0.1:{port}": "127.0.0.1:{port} で待機中", + "Plugin {version} installed": "プラグイン {version} をインストール済み", + "Show page {name}": "ページ {name} を表示", + "Switch to profile {name}": "プロファイル {name} に切り替え" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index e1834555bd7..6dc169f2145 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2356,5 +2356,240 @@ "Import dropped files without review": "ドロップしたファイルを確認せずに読み込む", "An import is running": "読み込み中です", "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", - "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください" + "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", + "1 Star": "星 1", + "2 Stars": "星 2", + "3 Stars": "星 3", + "4 Stars": "星 4", + "5 Stars": "星 5", + "A preset overwrites the tuning of every value.": "プリセットはすべての値の調整を上書きします。", + "Acceleration": "加速", + "Add page": "ページを追加", + "Add the built-in profiles": "組み込みプロファイルを追加", + "Also for key presses": "キーを押したときも", + "Any dialog": "すべてのダイアログ", + "Anywhere": "どこでも", + "Apply movement every": "動きを適用する間隔", + "Apply to All": "すべてに適用", + "Apply to Selected": "選択写真に適用", + "Approve": "承認", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "バランス型:標準的な操作感で、中速域の加速が素早い。", + "Before / After": "ビフォー / アフター", + "Big steps": "大きなステップ", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "大胆:反応が速く、加速が強めでダイナミックな編集向き。", + "Bottom edge": "下端", + "Bring over my TactileBridge setup": "TactileBridge の設定を引き継ぐ", + "Brush Feather": "ブラシのぼかし", + "Brush Flow": "ブラシの流量", + "Brush Size": "ブラシサイズ", + "Cancel Dialog": "ダイアログをキャンセル", + "Cancel learning": "学習をキャンセル", + "Coarse": "粗く", + "Colours are #RRGGBB.": "色は #RRGGBB 形式です。", + "Confirm Dialog": "ダイアログを確定", + "Control Surface Input": "コントロールデバイスの入力", + "Control Surface Profile": "コントロールデバイスのプロファイル", + "Control Surface Settings": "コントロールデバイスの設定", + "Control Surface State": "コントロールデバイスの状態", + "Controls": "コントロール", + "Crop Orient.": "向き", + "Deny": "拒否", + "Dial": "ダイヤル", + "Dial Feel": "ダイヤルの操作感", + "Dialpad button 1": "Dialpad ボタン 1", + "Dialpad button 2": "Dialpad ボタン 2", + "Dialpad button 3": "Dialpad ボタン 3", + "Dialpad button 4": "Dialpad ボタン 4", + "Dials": "ダイヤル", + "Dials Change All Selected Photos": "ダイヤルで選択したすべての写真を変更", + "Dials change every selected photo (one undo step per turn)": "ダイヤルで選択した各写真を変更(1 回転ごとに 1 回の取り消し)", + "Edit: Color": "編集:カラー", + "Edit: Detail": "編集:ディテール", + "Edit: Effects": "編集:効果", + "Edit: Geometry": "編集:ジオメトリ", + "Edit: Light": "編集:ライト", + "Edit: Optics": "編集:光学", + "Export Control Surface Layout": "コントロールデバイスのレイアウトを書き出す", + "Export dialog": "書き出しダイアログ", + "Fashion": "ファッション", + "Fast below": "高速とみなす間隔", + "Fast turning": "速く回したとき", + "Fine": "細かく", + "Fine steps": "細かいステップ", + "Follow Context": "状況に追従", + "Forget": "削除", + "Haptic feedback (where the device has it)": "触覚フィードバック(対応デバイスのみ)", + "Import Control Surface Setup": "コントロールデバイスの設定を読み込む", + "Import dialog": "読み込みダイアログ", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "TactileBridge の settings.json(操作感、表示、色、ツール別レイアウト)、Logi プロファイル(.lp5)、LightCraft のレイアウトファイル(.lcsurface)を読み込めます。", + "Its acceleration": "この値の加速", + "Its speed": "この値の速度", + "Keep the surface's readout steady while turning": "回している間はデバイスの表示を安定させる", + "Key 1": "キー 1", + "Key 2": "キー 2", + "Key 3": "キー 3", + "Key 4": "キー 4", + "Key 5": "キー 5", + "Key 6": "キー 6", + "Key 7": "キー 7", + "Key 8": "キー 8", + "Key 9": "キー 9", + "Key background": "キーの背景", + "Key text": "キーの文字", + "Keys": "キー", + "Learn: touch a control": "学習:操作部に触れる", + "Library (grid)": "ライブラリ(グリッド)", + "Linear Grad": "線形グラデーション", + "Mask": "マスク", + "Mask On/Off": "マスク オン/オフ", + "Masking: a mask selected": "マスク:マスクを選択中", + "Masking: brush": "マスク:ブラシ", + "Masking: gradient": "マスク:グラデーション", + "Moire": "モアレ", + "New Brush": "新規ブラシ", + "New Mask": "新規マスク", + "Next": "次へ", + "Next Page": "次のページ", + "Next Profile": "次のプロファイル", + "Next Surface Page": "デバイスの次のページ", + "Next page": "次のページ", + "No Rating": "レーティングなし", + "No surface is connected.": "接続中のデバイスはありません。", + "Nothing": "なし", + "On": "オン", + "On-Screen Readout": "画面表示", + "Page": "ページ", + "Pages That Follow the App": "アプリに追従するページ", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "パラメーターは JSON オブジェクトです(例:{\"rating\": 5})", + "Port": "ポート", + "Presets for every value:": "全値向けプリセット:", + "Press this key to put the value on the dial; press it again to give the dial back.": "このキーで値をダイヤルに割り当て、もう一度押すと元に戻します。", + "Previous": "前へ", + "Previous Page": "前のページ", + "Previous Surface Page": "デバイスの前のページ", + "Previous page": "前のページ", + "Radial Grad": "円形グラデーション", + "Real Estate": "不動産", + "Remove Feather": "削除のぼかし", + "Remove Opacity": "削除の不透明度", + "Remove Size": "削除のサイズ", + "Reset all": "すべてリセット", + "Roller": "ローラー", + "Show Surface Page": "デバイスのページを表示", + "Show the value or command in the window": "ウィンドウに値やコマンドを表示", + "Show values on the keys and the dial display": "キーとダイヤル表示に値を表示", + "Shown for": "表示時間", + "Slow above": "低速とみなす間隔", + "Slow turning": "ゆっくり回したとき", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "ソフトで精密:繊細で丁寧な色調整向けの穏やかな加速。", + "Surface Pages Follow the App": "デバイスのページをアプリに追従", + "Sync": "同期", + "Top edge": "上端", + "Turn a dial or press a key on the surface…": "デバイスのダイヤルを回すかキーを押してください…", + "Turn ends after": "回転の終了まで", + "Turn every dial the other way": "すべてのダイヤルを逆方向に", + "Turn this value the other way": "この値を逆方向に", + "WB Picker": "WB ピッカー", + "Wedding": "ウェディング", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "広範囲:基本速度は遅く、最大加速が非常に高い大きな調整向き。", + "Zoom 1:1": "ズーム 1:1", + "Zoom 200%": "ズーム 200%", + "Zoom 400%": "ズーム 400%", + "Zoom To Fit": "全体表示", + "page": "ページ", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "この LightCraft には新しい Logi Options+ 用プラグインが付属しています。", + "All commands": "すべてのコマンド", + "All pages": "全ページ", + "Browse & Select": "移動と選択", + "Check that the keypad shows the same code.": "キーパッドに同じコードが表示されていることを確認してください。", + "Coming later": "今後対応", + "Command parameters (advanced)": "コマンドのパラメーター(詳細)", + "Connected": "接続中", + "Connection": "接続", + "Control Surface": "コントロールサーフェス", + "Install the plugin": "プラグインをインストール", + "Installing the surface plugin": "プラグインをインストール中", + "Installing…": "インストール中…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "このプロファイルのキーページとダイヤルページ。ツールページはそのツールを開いている間、自動で表示されます(下記参照)。", + "Keys and Dials": "キーとダイヤル", + "LightCraft plugin for Logi Options+": "Logi Options+ 用 LightCraft プラグイン", + "Logi Options+ Plugin": "Logi Options+ プラグイン", + "Logi Options+ found": "Logi Options+ を検出", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "このコンピューターには Logi Options+ がありますが、LightCraft プラグインはまだインストールされていません。", + "Logi Options+ not found": "Logi Options+ が見つかりません", + "Logi Options+ asks to remove the plugin: confirm it there.": "Logi Options+ が削除を確認します。そこで確定してください。", + "No action matches.": "一致するアクションはありません。", + "Not connected": "未接続", + "Nothing — click to set": "未設定 — クリックして設定", + "Offline": "オフライン", + "One Value": "個別の値", + "Other": "その他", + "Pages and Profiles": "ページとプロファイル", + "Pages and Tools": "ページとツール", + "Plugin not installed": "プラグイン未インストール", + "Profiles and Setup": "プロファイルと設定", + "Rating & Labels": "レーティングとラベル", + "Readout and Look": "表示と外観", + "Reinstall the plugin": "プラグインを再インストール", + "Remove the plugin": "プラグインを削除", + "Removing the surface plugin": "プラグインを削除中", + "Removing…": "削除中…", + "Search actions": "アクションを検索", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "このデバイスへの対応は今後予定しています。キーとダイヤルは MX Creative Console と同じくここで設定します。", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console は Logi Options+ 用 LightCraft プラグインを通じて LightCraft と通信します。インストールするとプラグインが Logi Options+ に渡され、確認を求められます。", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "この LightCraft ではインストールできません。LightCraft のダウンロードに含まれる LightCraft.lplug4 を開いて Logi Options+ にインストールしてください。", + "Tool page": "ツールページ", + "Tool pages": "ツールページ", + "Type a name, then Add page, or Rename on a page.": "名前を入力して「ページを追加」、またはページの「名前を変更」を押します。", + "Update the plugin": "プラグインを更新", + "Use control surfaces": "コントロールサーフェスを使う", + "What a control does on every page that leaves it empty": "そのコントロールを空のままにしているすべてのページでの動作", + "from All pages": "全ページから", + "Dialogs show their own page (OK, Cancel…)": "ダイアログでは専用ページ(OK、キャンセルなど)を表示", + "Switch pages with what LightCraft shows (Crop, Masking…)": "LightCraft の表示に合わせてページを切り替え(切り抜き、マスクなど)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "Logi Options+ がインストールを確認します。そこで「続行」をクリックすると、コンソールはそのまま使えます。", + "Display": "ディスプレイ", + "Upright: Vertical": "Upright: 垂直", + "Upright: Level": "Upright: 水平", + "Next Key Page": "次のキーページ", + "Previous Key Page": "前のキーページ", + "Next Dial Page": "次のダイヤルページ", + "Previous Dial Page": "前のダイヤルページ", + "Reset Dial Value": "ダイヤルの値をリセット", + "Show Unrated": "未評価を表示", + "Any Label": "すべてのラベル", + "Select Unrated": "未評価を選択", + "Select No Label": "ラベルなしを選択", + "Reset Straighten": "角度補正をリセット", + "No Mask": "マスクなし", + "Previous Mask": "前のマスク", + "Next Mask": "次のマスク", + "Select Previous Mask": "前のマスクを選択", + "Select Next Mask": "次のマスクを選択", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ は LightCraft プラグインを通して動作します。ここで設定するか、自分の Loupedeck プロファイルを読み込むまでは、各ノブとボタンは表示どおりの働きをします(読み込まれるのは配置だけです)。", + "Import a Loupedeck profile…": "Loupedeck プロファイルを読み込む…", + "Buttons": "ボタン", + "Loupedeck profile": "Loupedeck プロファイル", + "Up": "上", + "Touch to find": "触れて探す", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "デバイスのキー、ボタン、ダイヤルに触れると、ここで選択されます。このページを開いている間、デバイスは写真を変更しません。", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "一覧からアクションを図のキー、ボタン、ダイヤルへドラッグするか、クリック(またはデバイスで触れて)して動作を選びます。", + "A dial turns values: drop a value (or a page turn) on it.": "ダイヤルは値を回します:値(またはページ切り替え)をドロップしてください。", + "Actions Ring": "アクションリング", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "一覧からアクションをスロットへドラッグするか、スロットをクリックしてアクションを選びます。リングはどのページでも同じです。", + "Colour knobs P1–P8": "カラーノブ P1–P8", + "Tone knobs": "トーンノブ", + "Control Dial and arrows": "コントロールダイヤルと矢印", + "Sat": "彩度", + "Lum": "輝度", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "コンソールの Hue、Sat、Lum、Col/BW ボタンで P1–P8 が送る内容が切り替わります。", + "P1–P8 pressed": "P1–P8 押下", + "Ring slot 1": "リングのスロット 1", + "Ring slot 2": "リングのスロット 2", + "Ring slot 3": "リングのスロット 3", + "Ring slot 4": "リングのスロット 4", + "Ring slot 5": "リングのスロット 5", + "Ring slot 6": "リングのスロット 6", + "Ring slot 7": "リングのスロット 7", + "Ring slot 8": "リングのスロット 8" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 46036826186..1d08d9d23bc 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "ვერ წაიკითხა {name}: {e}", "Added {n} photo{}": "დაემატა ფოტო: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "სად გადავიტანოთ Lightroom-ის კატალოგი „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}", + "Imported into the profile “{name}”": "Imported into the profile “{name}”", + "Last import: {mapped} brought over, {dropped} left out": "Last import: {mapped} brought over, {dropped} left out", + "Listening on 127.0.0.1:{port}": "Listening on 127.0.0.1:{port}", + "Now: {context}": "Now: {context}", + "Paired: {name}": "Paired: {name}", + "Plugin {version} installed": "Plugin {version} installed", + "Saved {path}": "Saved {path}", + "Show page {name}": "Show page {name}", + "Switch to profile {name}": "Switch to profile {name}", + "{name} asks to control LightCraft: see Settings, Controls": "{name} asks to control LightCraft: see Settings, Controls", + "{name} asks to pair. Code: {code}": "{name} asks to pair. Code: {code}" } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6e..2478d61da21 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -305,5 +305,16 @@ "Added {n} photo{}": "Dodano zdjęcia: {n}{:.0}", "Inside: {names}": "Wewnątrz: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Dokąd zaimportować katalog Lightroom „{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}", + "Imported into the profile “{name}”": "Zaimportowano do profilu „{name}”", + "Last import: {mapped} brought over, {dropped} left out": "Ostatni import: przeniesiono {mapped}, pominięto {dropped}", + "Listening on 127.0.0.1:{port}": "Nasłuchuje na 127.0.0.1:{port}", + "Now: {context}": "Teraz: {context}", + "Paired: {name}": "Sparowano: {name}", + "Plugin {version} installed": "Zainstalowano wtyczkę {version}", + "Saved {path}": "Zapisano: {path}", + "Show page {name}": "Pokaż stronę {name}", + "Switch to profile {name}": "Przełącz na profil {name}", + "{name} asks to control LightCraft: see Settings, Controls": "{name} prosi o sterowanie LightCraft: zobacz Ustawienia, Sterowanie", + "{name} asks to pair. Code: {code}": "{name} prosi o sparowanie. Kod: {code}" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index adac22e62ad..95a356d7549 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2283,5 +2283,50 @@ "Import dropped files without review": "Importuj upuszczone pliki bez przeglądu", "An import is running": "Import jest w toku", "An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy", - "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia" + "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia", + "Display": "Ekran", + "Controls": "Kontrolery", + "Upright: Vertical": "Upright: Pionowo", + "Upright: Level": "Upright: Poziom", + "Next Key Page": "Następna strona klawiszy", + "Previous Key Page": "Poprzednia strona klawiszy", + "Next Dial Page": "Następna strona pokręteł", + "Previous Dial Page": "Poprzednia strona pokręteł", + "Reset Dial Value": "Resetuj wartość pokrętła", + "Show Unrated": "Pokaż bez oceny", + "Any Label": "Dowolna etykieta", + "Select Unrated": "Zaznacz bez oceny", + "Select No Label": "Zaznacz bez etykiety", + "Reset Straighten": "Resetuj prostowanie", + "No Mask": "Brak maski", + "Previous Mask": "Poprzednia maska", + "Next Mask": "Następna maska", + "Select Previous Mask": "Zaznacz poprzednią maskę", + "Select Next Mask": "Zaznacz następną maskę", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ działa przez wtyczkę LightCraft. Każde pokrętło i przycisk robi to, co mówi jego opis, dopóki nie ustawisz go tutaj albo nie przeniesiesz własnego profilu Loupedeck (przenoszony jest tylko układ).", + "Import a Loupedeck profile…": "Importuj profil Loupedeck…", + "Buttons": "Przyciski", + "Loupedeck profile": "Profil Loupedeck", + "Up": "Na górze", + "Touch to find": "Znajdź dotykiem", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Dotknij klawisza, przycisku lub pokrętła na urządzeniu, aby go tu zaznaczyć. Gdy ta strona jest otwarta, urządzenie nie zmienia zdjęcia.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Przeciągnij akcję z listy na klawisz, przycisk lub pokrętło na rysunku albo kliknij je (lub dotknij na urządzeniu), aby wybrać, co robi.", + "A dial turns values: drop a value (or a page turn) on it.": "Pokrętło zmienia wartości: upuść na nie wartość (lub przewijanie stron).", + "Actions Ring": "Pierścień akcji", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Przeciągnij akcję z listy na miejsce albo kliknij miejsce i wybierz jego akcję. Pierścień jest taki sam na każdej stronie.", + "Colour knobs P1–P8": "Pokrętła kolorów P1–P8", + "Tone knobs": "Pokrętła tonów", + "Control Dial and arrows": "Control Dial i strzałki", + "Sat": "Nas", + "Lum": "Lum", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "Przyciski Hue, Sat, Lum i Col/BW na konsoli przełączają, co wysyłają P1–P8.", + "P1–P8 pressed": "P1–P8 wciśnięte", + "Ring slot 1": "Miejsce pierścienia 1", + "Ring slot 2": "Miejsce pierścienia 2", + "Ring slot 3": "Miejsce pierścienia 3", + "Ring slot 4": "Miejsce pierścienia 4", + "Ring slot 5": "Miejsce pierścienia 5", + "Ring slot 6": "Miejsce pierścienia 6", + "Ring slot 7": "Miejsce pierścienia 7", + "Ring slot 8": "Miejsce pierścienia 8" } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4b..b0289920b8b 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "Não foi possível ler {name}: {e}", "Added {n} photo{}": "{n} foto{0} adicionada{0}", "Where should the Lightroom catalog “{catalog}” go?": "Para onde vai o catálogo do Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})", + "{name} asks to control LightCraft: see Settings, Controls": "{name} pede para controlar o LightCraft: veja Configurações, Controles", + "Now: {context}": "Agora: {context}", + "Imported into the profile “{name}”": "Importado para o perfil “{name}”", + "Last import: {mapped} brought over, {dropped} left out": "Última importação: {mapped} trazidos, {dropped} deixados de fora", + "Saved {path}": "Salvo: {path}", + "Paired: {name}": "Pareado: {name}", + "{name} asks to pair. Code: {code}": "{name} pede pareamento. Código: {code}", + "Listening on 127.0.0.1:{port}": "Aguardando em 127.0.0.1:{port}", + "Plugin {version} installed": "Plugin {version} instalado", + "Show page {name}": "Mostrar a página {name}", + "Switch to profile {name}": "Mudar para o perfil {name}" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e84fb7615b7..5507623c281 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2202,5 +2202,240 @@ "Import dropped files without review": "Importar arquivos soltos sem revisão", "An import is running": "Uma importação está em andamento", "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", - "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos" + "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", + "1 Star": "1 estrela", + "2 Stars": "2 estrelas", + "3 Stars": "3 estrelas", + "4 Stars": "4 estrelas", + "5 Stars": "5 estrelas", + "A preset overwrites the tuning of every value.": "Uma predefinição substitui o ajuste de todos os valores.", + "Acceleration": "Aceleração", + "Add page": "Adicionar página", + "Add the built-in profiles": "Adicionar os perfis incluídos", + "Also for key presses": "Também ao pressionar teclas", + "Any dialog": "Qualquer diálogo", + "Anywhere": "Em qualquer lugar", + "Apply movement every": "Aplicar o movimento a cada", + "Apply to All": "Aplicar a todas", + "Apply to Selected": "Aplicar à seleção", + "Approve": "Aprovar", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "Equilibrado: toque padrão com aceleração ágil na faixa média.", + "Before / After": "Antes / Depois", + "Big steps": "Passos grandes", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "Ousado: resposta mais rápida e aceleração forte para edições dinâmicas.", + "Bottom edge": "Borda inferior", + "Bring over my TactileBridge setup": "Trazer minha configuração do TactileBridge", + "Brush Feather": "Pincel: desfoque", + "Brush Flow": "Pincel: fluxo", + "Brush Size": "Tamanho do pincel", + "Cancel Dialog": "Cancelar diálogo", + "Cancel learning": "Cancelar aprendizado", + "Coarse": "Grosso", + "Colours are #RRGGBB.": "As cores são #RRGGBB.", + "Confirm Dialog": "Confirmar diálogo", + "Control Surface Input": "Entrada da superfície de controle", + "Control Surface Profile": "Perfil da superfície de controle", + "Control Surface Settings": "Configurações da superfície de controle", + "Control Surface State": "Estado da superfície de controle", + "Controls": "Controles", + "Crop Orient.": "Orientação", + "Deny": "Recusar", + "Dial": "Dial", + "Dial Feel": "Toque do dial", + "Dialpad button 1": "Botão 1 do Dialpad", + "Dialpad button 2": "Botão 2 do Dialpad", + "Dialpad button 3": "Botão 3 do Dialpad", + "Dialpad button 4": "Botão 4 do Dialpad", + "Dials": "Dials", + "Dials Change All Selected Photos": "Os dials alteram todas as fotos selecionadas", + "Dials change every selected photo (one undo step per turn)": "Os dials alteram cada foto selecionada (um passo de desfazer por giro)", + "Edit: Color": "Editar: Cor", + "Edit: Detail": "Editar: Detalhe", + "Edit: Effects": "Editar: Efeitos", + "Edit: Geometry": "Editar: Geometria", + "Edit: Light": "Editar: Luz", + "Edit: Optics": "Editar: Óptica", + "Export Control Surface Layout": "Exportar o layout da superfície de controle", + "Export dialog": "Diálogo de exportação", + "Fashion": "Moda", + "Fast below": "Rápido abaixo de", + "Fast turning": "Giro rápido", + "Fine": "Fino", + "Fine steps": "Passos finos", + "Follow Context": "Seguir o contexto", + "Forget": "Esquecer", + "Haptic feedback (where the device has it)": "Resposta tátil (se o dispositivo tiver)", + "Import Control Surface Setup": "Importar configuração da superfície de controle", + "Import dialog": "Diálogo de importação", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "Importa um settings.json do TactileBridge (toque, indicador, cores, layouts por ferramenta), um perfil Logi (.lp5) ou um arquivo de layout do LightCraft (.lcsurface).", + "Its acceleration": "Sua aceleração", + "Its speed": "Sua velocidade", + "Keep the surface's readout steady while turning": "Manter estável a leitura do dispositivo ao girar", + "Key 1": "Tecla 1", + "Key 2": "Tecla 2", + "Key 3": "Tecla 3", + "Key 4": "Tecla 4", + "Key 5": "Tecla 5", + "Key 6": "Tecla 6", + "Key 7": "Tecla 7", + "Key 8": "Tecla 8", + "Key 9": "Tecla 9", + "Key background": "Fundo das teclas", + "Key text": "Texto das teclas", + "Keys": "Teclas", + "Learn: touch a control": "Aprender: toque um controle", + "Library (grid)": "Biblioteca (grade)", + "Linear Grad": "Gradiente linear", + "Mask": "Máscara", + "Mask On/Off": "Máscara lig./desl.", + "Masking: a mask selected": "Máscaras: uma máscara selecionada", + "Masking: brush": "Máscaras: pincel", + "Masking: gradient": "Máscaras: gradiente", + "Moire": "Moiré", + "New Brush": "Novo pincel", + "New Mask": "Nova máscara", + "Next": "Próxima", + "Next Page": "Próxima página", + "Next Profile": "Próximo perfil", + "Next Surface Page": "Próxima página da superfície", + "Next page": "Próxima página", + "No Rating": "Sem classificação", + "No surface is connected.": "Nenhuma superfície conectada.", + "Nothing": "Nada", + "On": "Ligado", + "On-Screen Readout": "Indicador na tela", + "Page": "Página", + "Pages That Follow the App": "Páginas que seguem o app", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "Os parâmetros são um objeto JSON, ex.: {\"rating\": 5}", + "Port": "Porta", + "Presets for every value:": "Predefinições para todos os valores:", + "Press this key to put the value on the dial; press it again to give the dial back.": "Pressione esta tecla para levar o valor ao dial; pressione de novo para devolvê-lo.", + "Previous": "Anterior", + "Previous Page": "Página anterior", + "Previous Surface Page": "Página anterior da superfície", + "Previous page": "Página anterior", + "Radial Grad": "Gradiente radial", + "Real Estate": "Imóveis", + "Remove Feather": "Remover: desfoque", + "Remove Opacity": "Remover: opacidade", + "Remove Size": "Remover: tamanho", + "Reset all": "Redefinir tudo", + "Roller": "Roda", + "Show Surface Page": "Mostrar página da superfície", + "Show the value or command in the window": "Mostrar o valor ou comando na janela", + "Show values on the keys and the dial display": "Mostrar valores nas teclas e na tela do dial", + "Shown for": "Exibido por", + "Slow above": "Lento acima de", + "Slow turning": "Giro lento", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "Suave e preciso: aceleração delicada para um trabalho de cor controlado.", + "Surface Pages Follow the App": "As páginas da superfície seguem o app", + "Sync": "Sincronizar", + "Top edge": "Borda superior", + "Turn a dial or press a key on the surface…": "Gire um dial ou pressione uma tecla na superfície…", + "Turn ends after": "O giro termina após", + "Turn every dial the other way": "Inverter o sentido de todos os dials", + "Turn this value the other way": "Inverter o sentido deste valor", + "WB Picker": "Seletor de BB", + "Wedding": "Casamento", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "Ampla faixa: velocidade base lenta com pico muito alto para ajustes amplos.", + "Zoom 1:1": "Zoom 1:1", + "Zoom 200%": "Zoom 200%", + "Zoom 400%": "Zoom 400%", + "Zoom To Fit": "Ajustar", + "page": "página", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "Este LightCraft traz um plugin mais novo para o Logi Options+.", + "All commands": "Todos os comandos", + "All pages": "Todas as páginas", + "Browse & Select": "Navegar e selecionar", + "Check that the keypad shows the same code.": "Confira se o teclado mostra o mesmo código.", + "Coming later": "Em breve", + "Command parameters (advanced)": "Parâmetros do comando (avançado)", + "Connected": "Conectado", + "Connection": "Conexão", + "Control Surface": "Superfície de controle", + "Install the plugin": "Instalar o plugin", + "Installing the surface plugin": "Instalando o plugin", + "Installing…": "Instalando…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "Páginas de teclas e de dials deste perfil. Uma página de ferramenta aparece sozinha enquanto a ferramenta está aberta (veja abaixo).", + "Keys and Dials": "Teclas e dials", + "LightCraft plugin for Logi Options+": "Plugin do LightCraft para Logi Options+", + "Logi Options+ Plugin": "Plugin do Logi Options+", + "Logi Options+ found": "Logi Options+ encontrado", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "O Logi Options+ está neste computador, mas o plugin do LightCraft ainda não foi instalado.", + "Logi Options+ not found": "Logi Options+ não encontrado", + "Logi Options+ asks to remove the plugin: confirm it there.": "O Logi Options+ pede para remover o plugin: confirme lá.", + "No action matches.": "Nenhuma ação corresponde.", + "Not connected": "Não conectado", + "Nothing — click to set": "Nada — clique para definir", + "Offline": "Offline", + "One Value": "Um valor", + "Other": "Outros", + "Pages and Profiles": "Páginas e perfis", + "Pages and Tools": "Páginas e ferramentas", + "Plugin not installed": "Plugin não instalado", + "Profiles and Setup": "Perfis e configuração", + "Rating & Labels": "Classificação e rótulos", + "Readout and Look": "Indicador e aparência", + "Reinstall the plugin": "Reinstalar o plugin", + "Remove the plugin": "Remover o plugin", + "Removing the surface plugin": "Removendo o plugin", + "Removing…": "Removendo…", + "Search actions": "Pesquisar ações", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "O suporte a esta superfície virá depois. Suas teclas e dials serão configurados aqui, como os do MX Creative Console.", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "O MX Creative Console fala com o LightCraft pelo plugin do LightCraft para o Logi Options+. Instalar entrega o plugin ao Logi Options+, que pede sua confirmação.", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "Este LightCraft não consegue instalá-lo: abra o LightCraft.lplug4 do download do LightCraft para instalá-lo no Logi Options+.", + "Tool page": "Página de ferramenta", + "Tool pages": "Páginas de ferramentas", + "Type a name, then Add page, or Rename on a page.": "Digite um nome e depois Adicionar página, ou Renomear em uma página.", + "Update the plugin": "Atualizar o plugin", + "Use control surfaces": "Usar superfícies de controle", + "What a control does on every page that leaves it empty": "O que um controle faz em toda página que o deixa vazio", + "from All pages": "de Todas as páginas", + "Dialogs show their own page (OK, Cancel…)": "Os diálogos mostram a própria página (OK, Cancelar…)", + "Switch pages with what LightCraft shows (Crop, Masking…)": "Trocar de página conforme o que o LightCraft mostra (Corte, Máscaras…)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "O Logi Options+ pede para instalar o plugin: clique em Continuar lá. Depois o console funciona sozinho.", + "Display": "Tela", + "Upright: Vertical": "Upright: Vertical", + "Upright: Level": "Upright: Nivelado", + "Next Key Page": "Próxima página de teclas", + "Previous Key Page": "Página de teclas anterior", + "Next Dial Page": "Próxima página de dials", + "Previous Dial Page": "Página de dials anterior", + "Reset Dial Value": "Redefinir valor do dial", + "Show Unrated": "Mostrar sem classificação", + "Any Label": "Qualquer rótulo", + "Select Unrated": "Selecionar sem classificação", + "Select No Label": "Selecionar sem rótulo", + "Reset Straighten": "Redefinir endireitamento", + "No Mask": "Sem máscara", + "Previous Mask": "Máscara anterior", + "Next Mask": "Próxima máscara", + "Select Previous Mask": "Selecionar a máscara anterior", + "Select Next Mask": "Selecionar a próxima máscara", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "O Loupedeck+ funciona pelo plug-in do LightCraft. Cada botão giratório e cada botão faz o que diz o seu rótulo até você configurá-lo aqui ou trazer o seu próprio perfil do Loupedeck (só o layout é trazido).", + "Import a Loupedeck profile…": "Importar um perfil do Loupedeck…", + "Buttons": "Botões", + "Loupedeck profile": "Perfil do Loupedeck", + "Up": "Em cima", + "Touch to find": "Encontrar ao tocar", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Toque uma tecla, um botão ou um dial do dispositivo para selecioná-lo aqui. Enquanto esta página estiver aberta, o dispositivo não muda a sua foto.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Arraste uma ação da lista para uma tecla, botão ou dial do desenho, ou clique em um (ou toque nele no dispositivo) para escolher o que ele faz.", + "A dial turns values: drop a value (or a page turn) on it.": "Um dial gira valores: solte nele um valor (ou uma troca de página).", + "Actions Ring": "Anel de ações", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Arraste uma ação da lista para uma posição, ou clique numa posição e escolha a ação. O anel é o mesmo em todas as páginas.", + "Colour knobs P1–P8": "Botões de cor P1–P8", + "Tone knobs": "Botões de tom", + "Control Dial and arrows": "Control Dial e setas", + "Sat": "Sat", + "Lum": "Lum", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "Os botões Hue, Sat, Lum e Col/BW do console trocam o que P1–P8 enviam.", + "P1–P8 pressed": "P1–P8 pressionados", + "Ring slot 1": "Posição do anel 1", + "Ring slot 2": "Posição do anel 2", + "Ring slot 3": "Posição do anel 3", + "Ring slot 4": "Posição do anel 4", + "Ring slot 5": "Posição do anel 5", + "Ring slot 6": "Posição do anel 6", + "Ring slot 7": "Posição do anel 7", + "Ring slot 8": "Posição do anel 8" } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af42764..811f6c52196 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "Не удалось прочитать {name}: {e}", "Added {n} photo{}": "Добавлено фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куда импортировать каталог Lightroom «{catalog}»?", - "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}", + "{name} asks to control LightCraft: see Settings, Controls": "{name} просит доступ к управлению LightCraft: см. Настройки, Управление", + "Now: {context}": "Сейчас: {context}", + "Imported into the profile “{name}”": "Импортировано в профиль «{name}»", + "Last import: {mapped} brought over, {dropped} left out": "Последний импорт: перенесено {mapped}, пропущено {dropped}", + "Saved {path}": "Сохранено: {path}", + "Paired: {name}": "Сопряжено: {name}", + "{name} asks to pair. Code: {code}": "{name} просит сопряжение. Код: {code}", + "Listening on 127.0.0.1:{port}": "Ожидает на 127.0.0.1:{port}", + "Plugin {version} installed": "Плагин {version} установлен", + "Show page {name}": "Показать страницу {name}", + "Switch to profile {name}": "Переключить на профиль {name}" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 306804df045..ad695094083 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2349,5 +2349,240 @@ "Import dropped files without review": "Импортировать перетащенные файлы без проверки", "An import is running": "Импорт уже выполняется", "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", - "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото" + "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", + "1 Star": "1 звезда", + "2 Stars": "2 звезды", + "3 Stars": "3 звезды", + "4 Stars": "4 звезды", + "5 Stars": "5 звёзд", + "A preset overwrites the tuning of every value.": "Пресет заменяет настройку всех значений.", + "Acceleration": "Ускорение", + "Add page": "Добавить страницу", + "Add the built-in profiles": "Добавить встроенные профили", + "Also for key presses": "И при нажатии клавиш", + "Any dialog": "Любой диалог", + "Anywhere": "Везде", + "Apply movement every": "Применять движение каждые", + "Apply to All": "Ко всем", + "Apply to Selected": "К выбранным", + "Approve": "Разрешить", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "Сбалансированно: обычный ход с отзывчивым ускорением на средней скорости.", + "Before / After": "До / После", + "Big steps": "Крупный шаг", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "Смело: быстрый отклик и сильное ускорение для динамичной обработки.", + "Bottom edge": "У нижнего края", + "Bring over my TactileBridge setup": "Перенести мои настройки TactileBridge", + "Brush Feather": "Растушёвка кисти", + "Brush Flow": "Поток кисти", + "Brush Size": "Размер кисти", + "Cancel Dialog": "Отменить диалог", + "Cancel learning": "Отменить обучение", + "Coarse": "Грубо", + "Colours are #RRGGBB.": "Цвета в формате #RRGGBB.", + "Confirm Dialog": "Подтвердить диалог", + "Control Surface Input": "Ввод с пульта", + "Control Surface Profile": "Профиль пульта", + "Control Surface Settings": "Настройки пульта", + "Control Surface State": "Состояние пульта", + "Controls": "Управление", + "Crop Orient.": "Ориентация", + "Deny": "Отклонить", + "Dial": "Регулятор", + "Dial Feel": "Отклик регулятора", + "Dialpad button 1": "Кнопка 1 Dialpad", + "Dialpad button 2": "Кнопка 2 Dialpad", + "Dialpad button 3": "Кнопка 3 Dialpad", + "Dialpad button 4": "Кнопка 4 Dialpad", + "Dials": "Регуляторы", + "Dials Change All Selected Photos": "Регуляторы меняют все выбранные фото", + "Dials change every selected photo (one undo step per turn)": "Регуляторы меняют каждое выбранное фото (один шаг отмены на поворот)", + "Edit: Color": "Правка: Цвет", + "Edit: Detail": "Правка: Детали", + "Edit: Effects": "Правка: Эффекты", + "Edit: Geometry": "Правка: Геометрия", + "Edit: Light": "Правка: Свет", + "Edit: Optics": "Правка: Оптика", + "Export Control Surface Layout": "Экспорт раскладки пульта", + "Export dialog": "Диалог экспорта", + "Fashion": "Мода", + "Fast below": "Быстро, если меньше", + "Fast turning": "Быстрый поворот", + "Fine": "Точно", + "Fine steps": "Мелкий шаг", + "Follow Context": "Следовать контексту", + "Forget": "Забыть", + "Haptic feedback (where the device has it)": "Тактильный отклик (если есть у устройства)", + "Import Control Surface Setup": "Импорт настроек пульта", + "Import dialog": "Диалог импорта", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "Импортируются settings.json TactileBridge (отклик, индикатор, цвета, раскладки инструментов), профиль Logi (.lp5) или файл раскладки LightCraft (.lcsurface).", + "Its acceleration": "Своё ускорение", + "Its speed": "Своя скорость", + "Keep the surface's readout steady while turning": "Не дёргать показания на пульте во время поворота", + "Key 1": "Клавиша 1", + "Key 2": "Клавиша 2", + "Key 3": "Клавиша 3", + "Key 4": "Клавиша 4", + "Key 5": "Клавиша 5", + "Key 6": "Клавиша 6", + "Key 7": "Клавиша 7", + "Key 8": "Клавиша 8", + "Key 9": "Клавиша 9", + "Key background": "Фон клавиш", + "Key text": "Текст клавиш", + "Keys": "Клавиши", + "Learn: touch a control": "Обучение: коснитесь элемента", + "Library (grid)": "Библиотека (сетка)", + "Linear Grad": "Линейный градиент", + "Mask": "Маска", + "Mask On/Off": "Маска вкл/выкл", + "Masking: a mask selected": "Маски: маска выбрана", + "Masking: brush": "Маски: кисть", + "Masking: gradient": "Маски: градиент", + "Moire": "Муар", + "New Brush": "Новая кисть", + "New Mask": "Новая маска", + "Next": "Далее", + "Next Page": "Следующая страница", + "Next Profile": "Следующий профиль", + "Next Surface Page": "Следующая страница пульта", + "Next page": "Следующая страница", + "No Rating": "Без оценки", + "No surface is connected.": "Пульт не подключён.", + "Nothing": "Ничего", + "On": "Вкл.", + "On-Screen Readout": "Экранная подсказка", + "Page": "Страница", + "Pages That Follow the App": "Страницы, следующие за приложением", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "Параметры — объект JSON, например {\"rating\": 5}", + "Port": "Порт", + "Presets for every value:": "Пресеты для всех значений:", + "Press this key to put the value on the dial; press it again to give the dial back.": "Нажмите клавишу, чтобы назначить значение регулятору; нажмите снова, чтобы вернуть.", + "Previous": "Назад", + "Previous Page": "Предыдущая страница", + "Previous Surface Page": "Предыдущая страница пульта", + "Previous page": "Предыдущая страница", + "Radial Grad": "Радиальный градиент", + "Real Estate": "Недвижимость", + "Remove Feather": "Удаление: растушёвка", + "Remove Opacity": "Удаление: непрозрачность", + "Remove Size": "Удаление: размер", + "Reset all": "Сбросить всё", + "Roller": "Колесо", + "Show Surface Page": "Показать страницу пульта", + "Show the value or command in the window": "Показывать значение или команду в окне", + "Show values on the keys and the dial display": "Показывать значения на клавишах и дисплее регулятора", + "Shown for": "Показывать", + "Slow above": "Медленно, если больше", + "Slow turning": "Медленный поворот", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "Мягко и точно: плавное ускорение для тонкой работы с цветом.", + "Surface Pages Follow the App": "Страницы пульта следуют за приложением", + "Sync": "Синхр.", + "Top edge": "У верхнего края", + "Turn a dial or press a key on the surface…": "Поверните регулятор или нажмите клавишу на пульте…", + "Turn ends after": "Поворот завершается через", + "Turn every dial the other way": "Обратное направление для всех регуляторов", + "Turn this value the other way": "Обратное направление для этого значения", + "WB Picker": "Пипетка ББ", + "Wedding": "Свадьба", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "Широкий диапазон: медленная база и очень высокий пик для больших изменений.", + "Zoom 1:1": "Масштаб 1:1", + "Zoom 200%": "Масштаб 200%", + "Zoom 400%": "Масштаб 400%", + "Zoom To Fit": "По размеру", + "page": "страница", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "С этим LightCraft поставляется более новый плагин для Logi Options+.", + "All commands": "Все команды", + "All pages": "Все страницы", + "Browse & Select": "Просмотр и выбор", + "Check that the keypad shows the same code.": "Проверьте, что на клавиатуре тот же код.", + "Coming later": "Позже", + "Command parameters (advanced)": "Параметры команды (дополнительно)", + "Connected": "Подключено", + "Connection": "Подключение", + "Control Surface": "Пульт управления", + "Install the plugin": "Установить плагин", + "Installing the surface plugin": "Установка плагина", + "Installing…": "Установка…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "Страницы клавиш и колёс этого профиля. Страница инструмента появляется сама, пока открыт её инструмент (см. ниже).", + "Keys and Dials": "Клавиши и колёса", + "LightCraft plugin for Logi Options+": "Плагин LightCraft для Logi Options+", + "Logi Options+ Plugin": "Плагин Logi Options+", + "Logi Options+ found": "Logi Options+ найден", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "Logi Options+ установлен, но плагин LightCraft ещё нет.", + "Logi Options+ not found": "Logi Options+ не найден", + "Logi Options+ asks to remove the plugin: confirm it there.": "Logi Options+ запросит удаление плагина: подтвердите его там.", + "No action matches.": "Нет подходящих действий.", + "Not connected": "Не подключено", + "Nothing — click to set": "Ничего — нажмите, чтобы задать", + "Offline": "Не в сети", + "One Value": "Одно значение", + "Other": "Другое", + "Pages and Profiles": "Страницы и профили", + "Pages and Tools": "Страницы и инструменты", + "Plugin not installed": "Плагин не установлен", + "Profiles and Setup": "Профили и настройка", + "Rating & Labels": "Рейтинг и метки", + "Readout and Look": "Индикация и вид", + "Reinstall the plugin": "Переустановить плагин", + "Remove the plugin": "Удалить плагин", + "Removing the surface plugin": "Удаление плагина", + "Removing…": "Удаление…", + "Search actions": "Поиск действий", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "Поддержка этого пульта появится позже. Его клавиши и колёса будут настраиваться здесь, как у MX Creative Console.", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console связывается с LightCraft через плагин LightCraft для Logi Options+. При установке плагин передаётся в Logi Options+, который попросит подтверждение.", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "Этот LightCraft не может его установить: откройте LightCraft.lplug4 из загрузки LightCraft, чтобы установить его в Logi Options+.", + "Tool page": "Страница инструмента", + "Tool pages": "Страницы инструментов", + "Type a name, then Add page, or Rename on a page.": "Введите имя и нажмите «Добавить страницу» или «Переименовать» у страницы.", + "Update the plugin": "Обновить плагин", + "Use control surfaces": "Использовать пульты управления", + "What a control does on every page that leaves it empty": "Что делает элемент на каждой странице, где он не задан", + "from All pages": "со всех страниц", + "Dialogs show their own page (OK, Cancel…)": "Диалоги показывают свою страницу (OK, Отмена…)", + "Switch pages with what LightCraft shows (Crop, Masking…)": "Переключать страницы по тому, что показывает LightCraft (Кадрирование, Маски…)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "Logi Options+ запросит установку: нажмите там «Продолжить». После этого консоль заработает сама.", + "Display": "Дисплей", + "Upright: Vertical": "Upright: По вертикали", + "Upright: Level": "Upright: Горизонт", + "Next Key Page": "Следующая страница клавиш", + "Previous Key Page": "Предыдущая страница клавиш", + "Next Dial Page": "Следующая страница колёс", + "Previous Dial Page": "Предыдущая страница колёс", + "Reset Dial Value": "Сбросить значение колеса", + "Show Unrated": "Показать без рейтинга", + "Any Label": "Любая метка", + "Select Unrated": "Выбрать без рейтинга", + "Select No Label": "Выбрать без метки", + "Reset Straighten": "Сбросить выравнивание", + "No Mask": "Без маски", + "Previous Mask": "Предыдущая маска", + "Next Mask": "Следующая маска", + "Select Previous Mask": "Выбрать предыдущую маску", + "Select Next Mask": "Выбрать следующую маску", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ работает через плагин LightCraft. Каждая ручка и кнопка делает то, что на ней написано, пока вы не настроите её здесь или не перенесёте свой профиль Loupedeck (переносится только раскладка).", + "Import a Loupedeck profile…": "Импортировать профиль Loupedeck…", + "Buttons": "Кнопки", + "Loupedeck profile": "Профиль Loupedeck", + "Up": "Вверху", + "Touch to find": "Найти касанием", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Коснитесь клавиши, кнопки или колеса на устройстве, чтобы выбрать их здесь. Пока эта страница открыта, устройство не меняет фото.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Перетащите действие из списка на клавишу, кнопку или колесо на рисунке либо щёлкните по нему (или коснитесь его на устройстве), чтобы выбрать, что оно делает.", + "A dial turns values: drop a value (or a page turn) on it.": "Колесо крутит значения: перетащите на него значение (или перелистывание страниц).", + "Actions Ring": "Кольцо действий", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Перетащите действие из списка на ячейку или щёлкните ячейку и выберите действие. Кольцо одинаково на всех страницах.", + "Colour knobs P1–P8": "Цветовые ручки P1–P8", + "Tone knobs": "Тоновые ручки", + "Control Dial and arrows": "Control Dial и стрелки", + "Sat": "Нас", + "Lum": "Ярк", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "Кнопки Hue, Sat, Lum и Col/BW на консоли переключают, что посылают P1–P8.", + "P1–P8 pressed": "P1–P8 нажатием", + "Ring slot 1": "Ячейка кольца 1", + "Ring slot 2": "Ячейка кольца 2", + "Ring slot 3": "Ячейка кольца 3", + "Ring slot 4": "Ячейка кольца 4", + "Ring slot 5": "Ячейка кольца 5", + "Ring slot 6": "Ячейка кольца 6", + "Ring slot 7": "Ячейка кольца 7", + "Ring slot 8": "Ячейка кольца 8" } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a25..cf86f85d2af 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "Не вдалося прочитати {name}: {e}", "Added {n} photo{}": "Додано фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куди імпортувати каталог Lightroom «{catalog}»?", - "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}", + "{name} asks to control LightCraft: see Settings, Controls": "{name} просить доступ до керування LightCraft: див. Налаштування, Керування", + "Now: {context}": "Зараз: {context}", + "Imported into the profile “{name}”": "Імпортовано в профіль «{name}»", + "Last import: {mapped} brought over, {dropped} left out": "Останній імпорт: перенесено {mapped}, пропущено {dropped}", + "Saved {path}": "Збережено: {path}", + "Paired: {name}": "Сполучено: {name}", + "{name} asks to pair. Code: {code}": "{name} просить сполучення. Код: {code}", + "Listening on 127.0.0.1:{port}": "Очікує на 127.0.0.1:{port}", + "Plugin {version} installed": "Плагін {version} встановлено", + "Show page {name}": "Показати сторінку {name}", + "Switch to profile {name}": "Перемкнути на профіль {name}" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index ee694ed4fe0..a6711a3cef3 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2354,5 +2354,240 @@ "Import dropped files without review": "Імпортувати перетягнуті файли без перегляду", "An import is running": "Імпорт уже виконується", "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", - "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото" + "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", + "1 Star": "1 зірка", + "2 Stars": "2 зірки", + "3 Stars": "3 зірки", + "4 Stars": "4 зірки", + "5 Stars": "5 зірок", + "A preset overwrites the tuning of every value.": "Пресет замінює налаштування всіх значень.", + "Acceleration": "Прискорення", + "Add page": "Додати сторінку", + "Add the built-in profiles": "Додати вбудовані профілі", + "Also for key presses": "І під час натискання клавіш", + "Any dialog": "Будь-який діалог", + "Anywhere": "Будь-де", + "Apply movement every": "Застосовувати рух кожні", + "Apply to All": "До всіх", + "Apply to Selected": "До вибраних", + "Approve": "Дозволити", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "Збалансовано: звичайний хід із чутливим прискоренням на середній швидкості.", + "Before / After": "До / Після", + "Big steps": "Великий крок", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "Сміливо: швидкий відгук і сильне прискорення для динамічної обробки.", + "Bottom edge": "Біля нижнього краю", + "Bring over my TactileBridge setup": "Перенести мої налаштування TactileBridge", + "Brush Feather": "Розтушовування пензля", + "Brush Flow": "Потік пензля", + "Brush Size": "Розмір пензля", + "Cancel Dialog": "Скасувати діалог", + "Cancel learning": "Скасувати навчання", + "Coarse": "Грубо", + "Colours are #RRGGBB.": "Кольори у форматі #RRGGBB.", + "Confirm Dialog": "Підтвердити діалог", + "Control Surface Input": "Введення з пульта", + "Control Surface Profile": "Профіль пульта", + "Control Surface Settings": "Налаштування пульта", + "Control Surface State": "Стан пульта", + "Controls": "Керування", + "Crop Orient.": "Орієнтація", + "Deny": "Відхилити", + "Dial": "Регулятор", + "Dial Feel": "Відгук регулятора", + "Dialpad button 1": "Кнопка 1 Dialpad", + "Dialpad button 2": "Кнопка 2 Dialpad", + "Dialpad button 3": "Кнопка 3 Dialpad", + "Dialpad button 4": "Кнопка 4 Dialpad", + "Dials": "Регулятори", + "Dials Change All Selected Photos": "Регулятори змінюють усі вибрані фото", + "Dials change every selected photo (one undo step per turn)": "Регулятори змінюють кожне вибране фото (один крок скасування на поворот)", + "Edit: Color": "Редагування: Колір", + "Edit: Detail": "Редагування: Деталі", + "Edit: Effects": "Редагування: Ефекти", + "Edit: Geometry": "Редагування: Геометрія", + "Edit: Light": "Редагування: Світло", + "Edit: Optics": "Редагування: Оптика", + "Export Control Surface Layout": "Експорт розкладки пульта", + "Export dialog": "Діалог експорту", + "Fashion": "Мода", + "Fast below": "Швидко, якщо менше", + "Fast turning": "Швидкий поворот", + "Fine": "Точно", + "Fine steps": "Дрібний крок", + "Follow Context": "Стежити за контекстом", + "Forget": "Забути", + "Haptic feedback (where the device has it)": "Тактильний відгук (якщо є в пристрої)", + "Import Control Surface Setup": "Імпорт налаштувань пульта", + "Import dialog": "Діалог імпорту", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "Імпортуються settings.json TactileBridge (відгук, індикатор, кольори, розкладки інструментів), профіль Logi (.lp5) або файл розкладки LightCraft (.lcsurface).", + "Its acceleration": "Власне прискорення", + "Its speed": "Власна швидкість", + "Keep the surface's readout steady while turning": "Не смикати показ на пульті під час повороту", + "Key 1": "Клавіша 1", + "Key 2": "Клавіша 2", + "Key 3": "Клавіша 3", + "Key 4": "Клавіша 4", + "Key 5": "Клавіша 5", + "Key 6": "Клавіша 6", + "Key 7": "Клавіша 7", + "Key 8": "Клавіша 8", + "Key 9": "Клавіша 9", + "Key background": "Тло клавіш", + "Key text": "Текст клавіш", + "Keys": "Клавіші", + "Learn: touch a control": "Навчання: торкніться елемента", + "Library (grid)": "Бібліотека (сітка)", + "Linear Grad": "Лінійний градієнт", + "Mask": "Маска", + "Mask On/Off": "Маска увімк/вимк", + "Masking: a mask selected": "Маски: маску вибрано", + "Masking: brush": "Маски: пензель", + "Masking: gradient": "Маски: градієнт", + "Moire": "Муар", + "New Brush": "Новий пензель", + "New Mask": "Нова маска", + "Next": "Далі", + "Next Page": "Наступна сторінка", + "Next Profile": "Наступний профіль", + "Next Surface Page": "Наступна сторінка пульта", + "Next page": "Наступна сторінка", + "No Rating": "Без оцінки", + "No surface is connected.": "Пульт не під’єднано.", + "Nothing": "Нічого", + "On": "Увімк.", + "On-Screen Readout": "Екранна підказка", + "Page": "Сторінка", + "Pages That Follow the App": "Сторінки, що стежать за застосунком", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "Параметри — об’єкт JSON, наприклад {\"rating\": 5}", + "Port": "Порт", + "Presets for every value:": "Пресети для всіх значень:", + "Press this key to put the value on the dial; press it again to give the dial back.": "Натисніть клавішу, щоб призначити значення регулятору; натисніть ще раз, щоб повернути.", + "Previous": "Назад", + "Previous Page": "Попередня сторінка", + "Previous Surface Page": "Попередня сторінка пульта", + "Previous page": "Попередня сторінка", + "Radial Grad": "Радіальний градієнт", + "Real Estate": "Нерухомість", + "Remove Feather": "Видалення: розтушовування", + "Remove Opacity": "Видалення: непрозорість", + "Remove Size": "Видалення: розмір", + "Reset all": "Скинути все", + "Roller": "Колесо", + "Show Surface Page": "Показати сторінку пульта", + "Show the value or command in the window": "Показувати значення або команду у вікні", + "Show values on the keys and the dial display": "Показувати значення на клавішах і дисплеї регулятора", + "Shown for": "Показувати", + "Slow above": "Повільно, якщо більше", + "Slow turning": "Повільний поворот", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "М’яко й точно: плавне прискорення для тонкої роботи з кольором.", + "Surface Pages Follow the App": "Сторінки пульта стежать за застосунком", + "Sync": "Синхр.", + "Top edge": "Біля верхнього краю", + "Turn a dial or press a key on the surface…": "Поверніть регулятор або натисніть клавішу на пульті…", + "Turn ends after": "Поворот завершується через", + "Turn every dial the other way": "Зворотний напрямок для всіх регуляторів", + "Turn this value the other way": "Зворотний напрямок для цього значення", + "WB Picker": "Піпетка ББ", + "Wedding": "Весілля", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "Широкий діапазон: повільна база й дуже високий пік для великих змін.", + "Zoom 1:1": "Масштаб 1:1", + "Zoom 200%": "Масштаб 200%", + "Zoom 400%": "Масштаб 400%", + "Zoom To Fit": "За розміром", + "page": "сторінка", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "З цим LightCraft постачається новіший плагін для Logi Options+.", + "All commands": "Усі команди", + "All pages": "Усі сторінки", + "Browse & Select": "Перегляд і вибір", + "Check that the keypad shows the same code.": "Перевірте, що на клавіатурі той самий код.", + "Coming later": "Згодом", + "Command parameters (advanced)": "Параметри команди (додатково)", + "Connected": "Підключено", + "Connection": "Підключення", + "Control Surface": "Пульт керування", + "Install the plugin": "Встановити плагін", + "Installing the surface plugin": "Встановлення плагіна", + "Installing…": "Встановлення…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "Сторінки клавіш і коліщаток цього профілю. Сторінка інструмента з’являється сама, поки відкритий її інструмент (див. нижче).", + "Keys and Dials": "Клавіші та коліщатка", + "LightCraft plugin for Logi Options+": "Плагін LightCraft для Logi Options+", + "Logi Options+ Plugin": "Плагін Logi Options+", + "Logi Options+ found": "Logi Options+ знайдено", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "Logi Options+ встановлено, але плагін LightCraft ще ні.", + "Logi Options+ not found": "Logi Options+ не знайдено", + "Logi Options+ asks to remove the plugin: confirm it there.": "Logi Options+ запитає про видалення плагіна: підтвердьте там.", + "No action matches.": "Немає відповідних дій.", + "Not connected": "Не підключено", + "Nothing — click to set": "Нічого — натисніть, щоб задати", + "Offline": "Офлайн", + "One Value": "Одне значення", + "Other": "Інше", + "Pages and Profiles": "Сторінки та профілі", + "Pages and Tools": "Сторінки та інструменти", + "Plugin not installed": "Плагін не встановлено", + "Profiles and Setup": "Профілі та налаштування", + "Rating & Labels": "Рейтинг і мітки", + "Readout and Look": "Індикація та вигляд", + "Reinstall the plugin": "Перевстановити плагін", + "Remove the plugin": "Видалити плагін", + "Removing the surface plugin": "Видалення плагіна", + "Removing…": "Видалення…", + "Search actions": "Пошук дій", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "Підтримка цього пульта з’явиться згодом. Його клавіші й коліщатка налаштовуватимуться тут, як у MX Creative Console.", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console зв’язується з LightCraft через плагін LightCraft для Logi Options+. Під час встановлення плагін передається в Logi Options+, який попросить підтвердження.", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "Цей LightCraft не може його встановити: відкрийте LightCraft.lplug4 із завантаження LightCraft, щоб встановити його в Logi Options+.", + "Tool page": "Сторінка інструмента", + "Tool pages": "Сторінки інструментів", + "Type a name, then Add page, or Rename on a page.": "Введіть назву й натисніть «Додати сторінку» або «Перейменувати» біля сторінки.", + "Update the plugin": "Оновити плагін", + "Use control surfaces": "Використовувати пульти керування", + "What a control does on every page that leaves it empty": "Що робить елемент на кожній сторінці, де його не задано", + "from All pages": "з усіх сторінок", + "Dialogs show their own page (OK, Cancel…)": "Діалоги показують власну сторінку (OK, Скасувати…)", + "Switch pages with what LightCraft shows (Crop, Masking…)": "Перемикати сторінки за тим, що показує LightCraft (Кадрування, Маски…)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "Logi Options+ запитає про встановлення: натисніть там «Продовжити». Після цього консоль запрацює сама.", + "Display": "Дисплей", + "Upright: Vertical": "Upright: По вертикалі", + "Upright: Level": "Upright: Горизонт", + "Next Key Page": "Наступна сторінка клавіш", + "Previous Key Page": "Попередня сторінка клавіш", + "Next Dial Page": "Наступна сторінка коліщаток", + "Previous Dial Page": "Попередня сторінка коліщаток", + "Reset Dial Value": "Скинути значення коліщатка", + "Show Unrated": "Показати без рейтингу", + "Any Label": "Будь-яка мітка", + "Select Unrated": "Вибрати без рейтингу", + "Select No Label": "Вибрати без мітки", + "Reset Straighten": "Скинути вирівнювання", + "No Mask": "Без маски", + "Previous Mask": "Попередня маска", + "Next Mask": "Наступна маска", + "Select Previous Mask": "Вибрати попередню маску", + "Select Next Mask": "Вибрати наступну маску", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ працює через плагін LightCraft. Кожна ручка й кнопка робить те, що на ній написано, доки ви не налаштуєте її тут або не перенесете свій профіль Loupedeck (переноситься лише розкладка).", + "Import a Loupedeck profile…": "Імпортувати профіль Loupedeck…", + "Buttons": "Кнопки", + "Loupedeck profile": "Профіль Loupedeck", + "Up": "Вгорі", + "Touch to find": "Знайти дотиком", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "Торкніться клавіші, кнопки чи колеса на пристрої, щоб вибрати їх тут. Поки ця сторінка відкрита, пристрій не змінює фото.", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "Перетягніть дію зі списку на клавішу, кнопку чи колесо на малюнку або клацніть його (чи торкніться на пристрої), щоб вибрати, що воно робить.", + "A dial turns values: drop a value (or a page turn) on it.": "Колесо крутить значення: перетягніть на нього значення (або гортання сторінок).", + "Actions Ring": "Кільце дій", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "Перетягніть дію зі списку на комірку або клацніть комірку й виберіть дію. Кільце однакове на всіх сторінках.", + "Colour knobs P1–P8": "Кольорові ручки P1–P8", + "Tone knobs": "Тонові ручки", + "Control Dial and arrows": "Control Dial і стрілки", + "Sat": "Нас", + "Lum": "Яскр", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "Кнопки Hue, Sat, Lum і Col/BW на консолі перемикають, що надсилають P1–P8.", + "P1–P8 pressed": "P1–P8 натисканням", + "Ring slot 1": "Комірка кільця 1", + "Ring slot 2": "Комірка кільця 2", + "Ring slot 3": "Комірка кільця 3", + "Ring slot 4": "Комірка кільця 4", + "Ring slot 5": "Комірка кільця 5", + "Ring slot 6": "Комірка кільця 6", + "Ring slot 7": "Комірка кільця 7", + "Ring slot 8": "Комірка кільця 8" } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b866..c93b4821933 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "无法读取 {name}:{e}", "Added {n} photo{}": "已添加 {n} 张照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目录“{catalog}”要导入到哪里?", - "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}", + "{name} asks to control LightCraft: see Settings, Controls": "{name} 请求控制 LightCraft:请查看“设置 - 控制设备”", + "Now: {context}": "当前:{context}", + "Imported into the profile “{name}”": "已导入到配置“{name}”", + "Last import: {mapped} brought over, {dropped} left out": "上次导入:迁移 {mapped} 项,略过 {dropped} 项", + "Saved {path}": "已保存:{path}", + "Paired: {name}": "已配对:{name}", + "{name} asks to pair. Code: {code}": "{name} 请求配对。代码:{code}", + "Listening on 127.0.0.1:{port}": "正在 127.0.0.1:{port} 上监听", + "Plugin {version} installed": "已安装插件 {version}", + "Show page {name}": "显示页面 {name}", + "Switch to profile {name}": "切换到配置 {name}" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 270af8a6251..ebe3fdc7b9c 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2200,5 +2200,240 @@ "Import dropped files without review": "不经检查直接导入拖入的文件", "An import is running": "正在导入", "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", - "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入" + "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", + "1 Star": "1 星", + "2 Stars": "2 星", + "3 Stars": "3 星", + "4 Stars": "4 星", + "5 Stars": "5 星", + "A preset overwrites the tuning of every value.": "预设会覆盖所有数值的调校。", + "Acceleration": "加速", + "Add page": "添加页面", + "Add the built-in profiles": "添加内置配置", + "Also for key presses": "按键时也显示", + "Any dialog": "任意对话框", + "Anywhere": "任何位置", + "Apply movement every": "应用转动的间隔", + "Apply to All": "应用到全部", + "Apply to Selected": "应用到所选", + "Approve": "批准", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "均衡:标准手感,中速时加速灵敏。", + "Before / After": "修改前 / 修改后", + "Big steps": "大步长", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "大胆:响应更快、加速更强,适合动感编辑。", + "Bottom edge": "底部边缘", + "Bring over my TactileBridge setup": "迁移我的 TactileBridge 设置", + "Brush Feather": "画笔羽化", + "Brush Flow": "画笔流量", + "Brush Size": "画笔大小", + "Cancel Dialog": "取消对话框", + "Cancel learning": "取消学习", + "Coarse": "粗调", + "Colours are #RRGGBB.": "颜色格式为 #RRGGBB。", + "Confirm Dialog": "确认对话框", + "Control Surface Input": "控制设备输入", + "Control Surface Profile": "控制设备配置", + "Control Surface Settings": "控制设备设置", + "Control Surface State": "控制设备状态", + "Controls": "控制设备", + "Crop Orient.": "裁剪方向", + "Deny": "拒绝", + "Dial": "旋钮", + "Dial Feel": "旋钮手感", + "Dialpad button 1": "Dialpad 按钮 1", + "Dialpad button 2": "Dialpad 按钮 2", + "Dialpad button 3": "Dialpad 按钮 3", + "Dialpad button 4": "Dialpad 按钮 4", + "Dials": "旋钮", + "Dials Change All Selected Photos": "旋钮更改所有所选照片", + "Dials change every selected photo (one undo step per turn)": "旋钮更改每张所选照片(每次转动一个撤销步骤)", + "Edit: Color": "编辑:颜色", + "Edit: Detail": "编辑:细节", + "Edit: Effects": "编辑:效果", + "Edit: Geometry": "编辑:几何", + "Edit: Light": "编辑:光线", + "Edit: Optics": "编辑:光学", + "Export Control Surface Layout": "导出控制设备布局", + "Export dialog": "导出对话框", + "Fashion": "时尚", + "Fast below": "快速阈值", + "Fast turning": "快速转动", + "Fine": "微调", + "Fine steps": "小步长", + "Follow Context": "跟随情境", + "Forget": "忘记", + "Haptic feedback (where the device has it)": "触觉反馈(设备支持时)", + "Import Control Surface Setup": "导入控制设备设置", + "Import dialog": "导入对话框", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "可导入 TactileBridge 的 settings.json(旋钮手感、读数、颜色、工具布局)、Logi 配置(.lp5)或 LightCraft 布局文件(.lcsurface)。", + "Its acceleration": "其加速", + "Its speed": "其速度", + "Keep the surface's readout steady while turning": "转动时保持设备读数稳定", + "Key 1": "按键 1", + "Key 2": "按键 2", + "Key 3": "按键 3", + "Key 4": "按键 4", + "Key 5": "按键 5", + "Key 6": "按键 6", + "Key 7": "按键 7", + "Key 8": "按键 8", + "Key 9": "按键 9", + "Key background": "按键背景", + "Key text": "按键文字", + "Keys": "按键", + "Learn: touch a control": "学习:触碰一个控件", + "Library (grid)": "图库(网格)", + "Linear Grad": "线性渐变", + "Mask": "蒙版", + "Mask On/Off": "蒙版开/关", + "Masking: a mask selected": "蒙版:已选蒙版", + "Masking: brush": "蒙版:画笔", + "Masking: gradient": "蒙版:渐变", + "Moire": "摩尔纹", + "New Brush": "新画笔", + "New Mask": "新蒙版", + "Next": "下一张", + "Next Page": "下一页", + "Next Profile": "下一个配置", + "Next Surface Page": "控制设备下一页", + "Next page": "下一页", + "No Rating": "无星级", + "No surface is connected.": "未连接控制设备。", + "Nothing": "无", + "On": "开", + "On-Screen Readout": "屏幕读数", + "Page": "页面", + "Pages That Follow the App": "跟随应用切换的页面", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "参数为 JSON 对象,例如 {\"rating\": 5}", + "Port": "端口", + "Presets for every value:": "适用于所有数值的预设:", + "Press this key to put the value on the dial; press it again to give the dial back.": "按下此键将该值交给旋钮;再按一次交还旋钮。", + "Previous": "上一张", + "Previous Page": "上一页", + "Previous Surface Page": "控制设备上一页", + "Previous page": "上一页", + "Radial Grad": "径向渐变", + "Real Estate": "房地产", + "Remove Feather": "移除羽化", + "Remove Opacity": "移除不透明度", + "Remove Size": "移除大小", + "Reset all": "全部重置", + "Roller": "滚轮", + "Show Surface Page": "显示控制设备页面", + "Show the value or command in the window": "在窗口中显示数值或命令", + "Show values on the keys and the dial display": "在按键和旋钮显示上显示数值", + "Shown for": "显示时长", + "Slow above": "慢速阈值", + "Slow turning": "慢速转动", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "柔和精准:加速平缓,适合细腻可控的色彩调整。", + "Surface Pages Follow the App": "控制设备页面跟随应用", + "Sync": "同步", + "Top edge": "顶部边缘", + "Turn a dial or press a key on the surface…": "在设备上转动旋钮或按下按键…", + "Turn ends after": "转动结束于", + "Turn every dial the other way": "所有旋钮反向", + "Turn this value the other way": "此数值反向", + "WB Picker": "白平衡吸管", + "Wedding": "婚礼", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "大范围:基础速度慢,峰值极高,适合大幅调整。", + "Zoom 1:1": "缩放 1:1", + "Zoom 200%": "缩放 200%", + "Zoom 400%": "缩放 400%", + "Zoom To Fit": "适合窗口", + "page": "页面", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "此 LightCraft 附带了更新的 Logi Options+ 插件。", + "All commands": "所有命令", + "All pages": "所有页面", + "Browse & Select": "浏览与选择", + "Check that the keypad shows the same code.": "请确认键盘上显示的是同一个代码。", + "Coming later": "即将支持", + "Command parameters (advanced)": "命令参数(高级)", + "Connected": "已连接", + "Connection": "连接", + "Control Surface": "控制设备", + "Install the plugin": "安装插件", + "Installing the surface plugin": "正在安装插件", + "Installing…": "正在安装…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "此配置的按键页和旋钮页。工具页会在其工具打开时自动出现(见下文)。", + "Keys and Dials": "按键与旋钮", + "LightCraft plugin for Logi Options+": "适用于 Logi Options+ 的 LightCraft 插件", + "Logi Options+ Plugin": "Logi Options+ 插件", + "Logi Options+ found": "已找到 Logi Options+", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "此电脑上有 Logi Options+,但尚未安装 LightCraft 插件。", + "Logi Options+ not found": "未找到 Logi Options+", + "Logi Options+ asks to remove the plugin: confirm it there.": "Logi Options+ 会请求移除插件:请在那里确认。", + "No action matches.": "没有匹配的操作。", + "Not connected": "未连接", + "Nothing — click to set": "无 — 点按以设置", + "Offline": "离线", + "One Value": "单个数值", + "Other": "其他", + "Pages and Profiles": "页面与配置", + "Pages and Tools": "页面与工具", + "Plugin not installed": "未安装插件", + "Profiles and Setup": "配置与设置", + "Rating & Labels": "评级与标签", + "Readout and Look": "读数与外观", + "Reinstall the plugin": "重新安装插件", + "Remove the plugin": "移除插件", + "Removing the surface plugin": "正在移除插件", + "Removing…": "正在移除…", + "Search actions": "搜索操作", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "此设备的支持将在以后提供。它的按键和旋钮将像 MX Creative Console 一样在此设置。", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console 通过适用于 Logi Options+ 的 LightCraft 插件与 LightCraft 通信。安装时插件会交给 Logi Options+,它会请你确认。", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "此 LightCraft 无法安装它:请打开 LightCraft 下载中的 LightCraft.lplug4,将其安装到 Logi Options+。", + "Tool page": "工具页", + "Tool pages": "工具页", + "Type a name, then Add page, or Rename on a page.": "输入名称,然后点“添加页面”,或在页面上点“重命名”。", + "Update the plugin": "更新插件", + "Use control surfaces": "使用控制设备", + "What a control does on every page that leaves it empty": "控件在未设置它的每个页面上的功能", + "from All pages": "来自所有页面", + "Dialogs show their own page (OK, Cancel…)": "对话框显示自己的页面(确定、取消…)", + "Switch pages with what LightCraft shows (Crop, Masking…)": "随 LightCraft 显示的内容切换页面(裁剪、蒙版…)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "Logi Options+ 会请求安装插件:请在那里点按“继续”。之后控制台会自动工作。", + "Display": "显示器", + "Upright: Vertical": "Upright: 垂直", + "Upright: Level": "Upright: 水平", + "Next Key Page": "下一键位页", + "Previous Key Page": "上一键位页", + "Next Dial Page": "下一旋钮页", + "Previous Dial Page": "上一旋钮页", + "Reset Dial Value": "重置旋钮数值", + "Show Unrated": "显示未评级", + "Any Label": "任意标签", + "Select Unrated": "选择未评级", + "Select No Label": "选择无标签", + "Reset Straighten": "重置拉直", + "No Mask": "无蒙版", + "Previous Mask": "上一个蒙版", + "Next Mask": "下一个蒙版", + "Select Previous Mask": "选择上一个蒙版", + "Select Next Mask": "选择下一个蒙版", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ 通过 LightCraft 插件工作。在此设置或导入你自己的 Loupedeck 配置文件之前,每个旋钮和按钮都按其标签工作(只导入布局)。", + "Import a Loupedeck profile…": "导入 Loupedeck 配置文件…", + "Buttons": "按钮", + "Loupedeck profile": "Loupedeck 配置文件", + "Up": "上方", + "Touch to find": "触碰查找", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "触碰设备上的按键、按钮或旋钮即可在此选中它。此页面打开时,设备不会更改照片。", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "将列表中的操作拖到图中的按键、按钮或旋钮上,或点击它(或在设备上触碰它)来选择它的功能。", + "A dial turns values: drop a value (or a page turn) on it.": "旋钮用于调节数值:请拖放数值(或翻页)到它上面。", + "Actions Ring": "操作环", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "将列表中的操作拖到某个位置,或点击位置并选择操作。操作环在每一页都相同。", + "Colour knobs P1–P8": "颜色旋钮 P1–P8", + "Tone knobs": "色调旋钮", + "Control Dial and arrows": "控制旋钮和箭头", + "Sat": "饱和", + "Lum": "明亮", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "控制台上的 Hue、Sat、Lum 和 Col/BW 按钮切换 P1–P8 发送的内容。", + "P1–P8 pressed": "按下 P1–P8", + "Ring slot 1": "操作环位置 1", + "Ring slot 2": "操作环位置 2", + "Ring slot 3": "操作环位置 3", + "Ring slot 4": "操作环位置 4", + "Ring slot 5": "操作环位置 5", + "Ring slot 6": "操作环位置 6", + "Ring slot 7": "操作环位置 7", + "Ring slot 8": "操作环位置 8" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a2..76e9185b86a 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -305,5 +305,16 @@ "Could not read {name}: {e}": "無法讀取 {name}:{e}", "Added {n} photo{}": "已加入 {n} 張照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目錄「{catalog}」要匯入到哪裡?", - "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}", + "{name} asks to control LightCraft: see Settings, Controls": "{name} 要求控制 LightCraft:請查看「設定 - 控制裝置」", + "Now: {context}": "目前:{context}", + "Imported into the profile “{name}”": "已匯入至設定檔「{name}」", + "Last import: {mapped} brought over, {dropped} left out": "上次匯入:移轉 {mapped} 項,略過 {dropped} 項", + "Saved {path}": "已儲存:{path}", + "Paired: {name}": "已配對:{name}", + "{name} asks to pair. Code: {code}": "{name} 要求配對。代碼:{code}", + "Listening on 127.0.0.1:{port}": "正在 127.0.0.1:{port} 上監聽", + "Plugin {version} installed": "已安裝外掛 {version}", + "Show page {name}": "顯示頁面 {name}", + "Switch to profile {name}": "切換到設定檔 {name}" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 0408e23ec87..6b3d2bad96f 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2157,5 +2157,241 @@ "Import dropped files without review": "不經檢查直接匯入拖放的檔案", "An import is running": "正在匯入", "An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片", - "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入" + "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入", + "1 Star": "1 星", + "2 Stars": "2 星", + "3 Stars": "3 星", + "4 Stars": "4 星", + "5 Stars": "5 星", + "A preset overwrites the tuning of every value.": "預設會覆寫所有數值的調校。", + "Acceleration": "加速", + "Add page": "新增頁面", + "Add the built-in profiles": "新增內建設定檔", + "Also for key presses": "按鍵時也顯示", + "Any dialog": "任何對話框", + "Anywhere": "任何位置", + "Apply movement every": "套用轉動的間隔", + "Apply to All": "套用至全部", + "Apply to Selected": "套用至所選", + "Approve": "核准", + "Balanced: a standard dial feel with responsive mid-range acceleration.": "均衡:標準手感,中速時加速靈敏。", + "Before / After": "修改前 / 修改後", + "Big steps": "大步長", + "Bold and expressive: faster response with strong acceleration for dynamic edits.": "大膽:反應更快、加速更強,適合動感編修。", + "Bottom edge": "底部邊緣", + "Bring over my TactileBridge setup": "移轉我的 TactileBridge 設定", + "Brush Feather": "筆刷羽化", + "Brush Flow": "筆刷流量", + "Brush Size": "筆刷大小", + "Cancel Dialog": "取消對話框", + "Cancel learning": "取消學習", + "Coarse": "粗調", + "Colours are #RRGGBB.": "顏色格式為 #RRGGBB。", + "Confirm Dialog": "確認對話框", + "Control Surface Input": "控制裝置輸入", + "Control Surface Profile": "控制裝置設定檔", + "Control Surface Settings": "控制裝置設定", + "Control Surface State": "控制裝置狀態", + "Controls": "控制裝置", + "Crop Orient.": "裁切方向", + "Deny": "拒絕", + "Dial": "旋鈕", + "Dial Feel": "旋鈕手感", + "Dialpad button 1": "Dialpad 按鈕 1", + "Dialpad button 2": "Dialpad 按鈕 2", + "Dialpad button 3": "Dialpad 按鈕 3", + "Dialpad button 4": "Dialpad 按鈕 4", + "Dials": "旋鈕", + "Dials Change All Selected Photos": "旋鈕變更所有所選照片", + "Dials change every selected photo (one undo step per turn)": "旋鈕變更每張所選照片(每次轉動一個復原步驟)", + "Edit: Color": "編修:顏色", + "Edit: Detail": "編修:細節", + "Edit: Effects": "編修:效果", + "Edit: Geometry": "編修:幾何", + "Edit: Light": "編修:光線", + "Edit: Optics": "編修:光學", + "Export Control Surface Layout": "匯出控制裝置配置", + "Export dialog": "匯出對話框", + "Fashion": "時尚", + "Fast below": "快速門檻", + "Fast turning": "快速轉動", + "Fine": "微調", + "Fine steps": "小步長", + "Follow Context": "跟隨情境", + "Forget": "忘記", + "Haptic feedback (where the device has it)": "觸覺回饋(裝置支援時)", + "Import Control Surface Setup": "匯入控制裝置設定", + "Import dialog": "匯入對話框", + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).": "可匯入 TactileBridge 的 settings.json(旋鈕手感、讀數、顏色、工具配置)、Logi 設定檔(.lp5)或 LightCraft 配置檔(.lcsurface)。", + "Its acceleration": "其加速", + "Its speed": "其速度", + "Keep the surface's readout steady while turning": "轉動時保持裝置讀數穩定", + "Key 1": "按鍵 1", + "Key 2": "按鍵 2", + "Key 3": "按鍵 3", + "Key 4": "按鍵 4", + "Key 5": "按鍵 5", + "Key 6": "按鍵 6", + "Key 7": "按鍵 7", + "Key 8": "按鍵 8", + "Key 9": "按鍵 9", + "Key background": "按鍵背景", + "Key text": "按鍵文字", + "Keys": "按鍵", + "Learn: touch a control": "學習:觸碰一個控制項", + "Library (grid)": "圖庫(格狀)", + "Linear Grad": "線性漸層", + "Mask": "遮色片", + "Mask On/Off": "遮色片開/關", + "Masking: a mask selected": "遮色片:已選遮色片", + "Masking: brush": "遮色片:筆刷", + "Masking: gradient": "遮色片:漸層", + "Moire": "摩爾紋", + "New Brush": "新筆刷", + "New Mask": "新遮色片", + "Next": "下一張", + "Next Page": "下一頁", + "Next Profile": "下一個設定檔", + "Next Surface Page": "控制裝置下一頁", + "Next page": "下一頁", + "No Rating": "無星級", + "No surface is connected.": "未連接控制裝置。", + "Nothing": "無", + "On": "開", + "On-Screen Readout": "螢幕讀數", + "Page": "頁面", + "Pages That Follow the App": "跟隨應用程式切換的頁面", + "Parameters are a JSON object, e.g. {\"rating\": 5}": "參數為 JSON 物件,例如 {\"rating\": 5}", + "Port": "連接埠", + "Presets for every value:": "適用於所有數值的預設:", + "Press this key to put the value on the dial; press it again to give the dial back.": "按下此鍵將該值交給旋鈕;再按一次交還旋鈕。", + "Previous": "上一張", + "Previous Page": "上一頁", + "Previous Surface Page": "控制裝置上一頁", + "Previous page": "上一頁", + "Radial Grad": "放射狀漸層", + "Real Estate": "房地產", + "Remove Feather": "移除羽化", + "Remove Opacity": "移除不透明度", + "Remove Size": "移除大小", + "Reset all": "全部重設", + "Roller": "滾輪", + "Show Surface Page": "顯示控制裝置頁面", + "Show the value or command in the window": "在視窗中顯示數值或命令", + "Show values on the keys and the dial display": "在按鍵和旋鈕顯示上顯示數值", + "Shown for": "顯示時長", + "Slow above": "慢速門檻", + "Slow turning": "慢速轉動", + "Soft, smooth and precise: gentle acceleration for delicate, controlled colour work.": "柔和精準:加速平緩,適合細膩可控的色彩調整。", + "Surface Pages Follow the App": "控制裝置頁面跟隨應用程式", + "Sync": "同步", + "Top edge": "頂部邊緣", + "Turn a dial or press a key on the surface…": "在裝置上轉動旋鈕或按下按鍵…", + "Turn ends after": "轉動結束於", + "Turn every dial the other way": "所有旋鈕反向", + "Turn this value the other way": "此數值反向", + "WB Picker": "白平衡滴管", + "Wedding": "婚禮", + "Wide range: slow base speed with a very high peak for sweeping adjustments.": "大範圍:基礎速度慢,峰值極高,適合大幅調整。", + "Zoom 1:1": "縮放 1:1", + "Zoom 200%": "縮放 200%", + "Zoom 400%": "縮放 400%", + "Zoom To Fit": "符合視窗", + "page": "頁面", + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft.": "此 LightCraft 附帶較新的 Logi Options+ 外掛。", + "All commands": "所有指令", + "All pages": "所有頁面", + "Browse & Select": "瀏覽與選取", + "Check that the keypad shows the same code.": "請確認鍵盤上顯示的是同一組代碼。", + "Coming later": "即將支援", + "Command parameters (advanced)": "指令參數(進階)", + "Connected": "已連線", + "Connection": "連線", + "Control Surface": "控制裝置", + "Install the plugin": "安裝外掛", + "Installing the surface plugin": "正在安裝外掛", + "Installing…": "正在安裝…", + "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below).": "此設定檔的按鍵頁與旋鈕頁。工具頁會在其工具開啟時自動出現(見下文)。", + "Keys and Dials": "按鍵與旋鈕", + "LightCraft plugin for Logi Options+": "適用於 Logi Options+ 的 LightCraft 外掛", + "Logi Options+ Plugin": "Logi Options+ 外掛", + "Logi Options+ found": "已找到 Logi Options+", + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet.": "此電腦上有 Logi Options+,但尚未安裝 LightCraft 外掛。", + "Logi Options+ not found": "未找到 Logi Options+", + "Logi Options+ asks to remove the plugin: confirm it there.": "Logi Options+ 會要求移除外掛:請在那裡確認。", + "No action matches.": "沒有符合的動作。", + "Not connected": "未連線", + "Nothing — click to set": "無 — 點按以設定", + "Offline": "離線", + "One Value": "單一數值", + "Other": "其他", + "Pages and Profiles": "頁面與設定檔", + "Pages and Tools": "頁面與工具", + "Plugin not installed": "未安裝外掛", + "Profiles and Setup": "設定檔與設定", + "Rating & Labels": "評等與標籤", + "Readout and Look": "讀數與外觀", + "Reinstall the plugin": "重新安裝外掛", + "Remove the plugin": "移除外掛", + "Removing the surface plugin": "正在移除外掛", + "Removing…": "正在移除…", + "Search actions": "搜尋動作", + "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's.": "此裝置的支援將於日後提供。它的按鍵與旋鈕將像 MX Creative Console 一樣在此設定。", + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.": "MX Creative Console 透過適用於 Logi Options+ 的 LightCraft 外掛與 LightCraft 溝通。安裝時外掛會交給 Logi Options+,它會請你確認。", + "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+.": "此 LightCraft 無法安裝它:請開啟 LightCraft 下載中的 LightCraft.lplug4,將其安裝到 Logi Options+。", + "Tool page": "工具頁", + "Tool pages": "工具頁", + "Type a name, then Add page, or Rename on a page.": "輸入名稱,然後點「新增頁面」,或在頁面上點「重新命名」。", + "Update the plugin": "更新外掛", + "Use control surfaces": "使用控制裝置", + "What a control does on every page that leaves it empty": "控制項在未設定它的每個頁面上的功能", + "from All pages": "來自所有頁面", + "Dialogs show their own page (OK, Cancel…)": "對話框顯示自己的頁面(確定、取消…)", + "Switch pages with what LightCraft shows (Crop, Masking…)": "隨 LightCraft 顯示的內容切換頁面(裁切、遮色片…)", + "Logi Options+ asks to install the plugin: click Continue there. The console then works by itself.": "Logi Options+ 會要求安裝外掛:請在那裡點按「繼續」。之後控制台會自動運作。", + "Display": "顯示器", + "Faces": "人臉", + "Upright: Vertical": "Upright: 垂直", + "Upright: Level": "Upright: 水平", + "Next Key Page": "下一按鍵頁", + "Previous Key Page": "上一按鍵頁", + "Next Dial Page": "下一旋鈕頁", + "Previous Dial Page": "上一旋鈕頁", + "Reset Dial Value": "重設旋鈕數值", + "Show Unrated": "顯示未評等", + "Any Label": "任意標籤", + "Select Unrated": "選取未評等", + "Select No Label": "選取無標籤", + "Reset Straighten": "重設拉直", + "No Mask": "無遮色片", + "Previous Mask": "上一個遮色片", + "Next Mask": "下一個遮色片", + "Select Previous Mask": "選取上一個遮色片", + "Select Next Mask": "選取下一個遮色片", + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).": "Loupedeck+ 透過 LightCraft 外掛程式運作。在此設定或匯入你自己的 Loupedeck 設定檔之前,每個旋鈕和按鈕都依其標示運作(只匯入配置)。", + "Import a Loupedeck profile…": "匯入 Loupedeck 設定檔…", + "Buttons": "按鈕", + "Loupedeck profile": "Loupedeck 設定檔", + "Up": "上方", + "Touch to find": "觸碰尋找", + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.": "觸碰裝置上的按鍵、按鈕或旋鈕即可在此選取。此頁面開啟時,裝置不會變更相片。", + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.": "將清單中的動作拖到圖中的按鍵、按鈕或旋鈕上,或按一下它(或在裝置上觸碰)來選擇它的功能。", + "A dial turns values: drop a value (or a page turn) on it.": "旋鈕用於調整數值:請拖放數值(或翻頁)到它上面。", + "Actions Ring": "動作環", + "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page.": "將清單中的動作拖到某個位置,或按一下位置並選擇動作。動作環在每一頁都相同。", + "Colour knobs P1–P8": "色彩旋鈕 P1–P8", + "Tone knobs": "色調旋鈕", + "Control Dial and arrows": "控制旋鈕和箭頭", + "Sat": "飽和", + "Lum": "明亮", + "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send.": "控制台上的 Hue、Sat、Lum 和 Col/BW 按鈕切換 P1–P8 送出的內容。", + "P1–P8 pressed": "按下 P1–P8", + "Ring slot 1": "動作環位置 1", + "Ring slot 2": "動作環位置 2", + "Ring slot 3": "動作環位置 3", + "Ring slot 4": "動作環位置 4", + "Ring slot 5": "動作環位置 5", + "Ring slot 6": "動作環位置 6", + "Ring slot 7": "動作環位置 7", + "Ring slot 8": "動作環位置 8" } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7e04f1356db..2ea14803d3e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -12,6 +12,7 @@ //! image coordinates (brush strokes, crop handles…) — mapped to screen and injected as real input //! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}` / `ui.scroll {dx, dy}` //! - `ui.set {view?, panel?, filmstrip?, leftPanel?, zoom?, …}` / `ui.dialog.confirm|cancel` +//! - `surface.*`: control surfaces (pairing, subscribe, input, layout, icons; `crate::surface`) //! - `ui.screenshot {path?, headless?}` (headless: CPU-rendered, no compositor needed), `ui.resize {width, height}`, `ui.render {id?, size?, path?}`, `app.quit` use std::sync::mpsc::Sender; @@ -29,6 +30,10 @@ pub struct ControlRequest { /// Who has the request: [`PENDING`], [`TAKEN`] (the app runs it) or [`ABANDONED`] (the /// sender gave up on it, so the app must not run it late: issue #718). pub state: std::sync::Arc, + /// The connection it came on (0 = in process: headless scripts and tests, trusted). + pub conn: u64, + /// Where events for that connection go, for `surface.subscribe` (none in process). + pub sink: Option, } /// Queued, not yet run. @@ -41,7 +46,14 @@ pub const ABANDONED: u8 = 2; impl ControlRequest { pub fn new(method: impl Into, params: Value) -> (Self, std::sync::mpsc::Receiver) { let (tx, rx) = std::sync::mpsc::channel(); - (Self { method: method.into(), params, reply: tx, state: Default::default() }, rx) + (Self { method: method.into(), params, reply: tx, state: Default::default(), conn: 0, sink: None }, rx) + } + + /// The request came on connection `conn` (numbered from 1), whose pushed events go to `sink`. + pub fn on_connection(mut self, conn: u64, sink: crate::surface::EventSink) -> Self { + self.conn = conn; + self.sink = Some(sink); + self } /// Claim the request for running; false when its sender already gave up on it. @@ -194,6 +206,9 @@ fn widget_rect(app: &LightcraftApp, id: &str) -> Option { } pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + if let Some(o) = crate::surface::handle(app, req) { + return o; + } let p = &req.params; let s = |k: &str| p.get(k).and_then(Value::as_str); let f = |k: &str| p.get(k).and_then(Value::as_f64); @@ -398,28 +413,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest Err(e) => err(e), } } - "ui.dialog.confirm" => match app.ui.dialog.take() { - Some(d) => { - let r = crate::panels::dialogs::confirm_dialog(app, &d); - // the import review and the rule editor stay open on an error, as with their buttons - if (r.is_err() - && matches!( - d, - crate::state::Dialog::Import { .. } - | crate::state::Dialog::SamModel { .. } - | crate::state::Dialog::SmartRules { .. } - | crate::state::Dialog::SaveEffect { .. } - | crate::state::Dialog::CaptureTime { .. } - )) - || (r.is_ok() && crate::panels::dialogs::keeps_open(app, &d)) - || (r.is_err() && crate::lightroom_destination::keeps_open_on_error(app, &d)) - { - app.ui.dialog = Some(d); - } - wrap(r) - } - None => err("no dialog open"), - }, + "ui.dialog.confirm" => wrap(confirm_dialog(app)), "ui.dialog.cancel" => { app.ui.dialog = None; ok(Value::Null) @@ -491,6 +485,28 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest } } +/// OK on the open dialog (`ui.dialog.confirm`, a surface's OK key). +pub(crate) fn confirm_dialog(app: &mut LightcraftApp) -> Result { + let Some(d) = app.ui.dialog.take() else { return Err("no dialog open".into()) }; + let r = crate::panels::dialogs::confirm_dialog(app, &d); + // the import review and the rule editor stay open on an error, as with their buttons + if (r.is_err() + && matches!( + d, + crate::state::Dialog::Import { .. } + | crate::state::Dialog::SamModel { .. } + | crate::state::Dialog::SmartRules { .. } + | crate::state::Dialog::SaveEffect { .. } + | crate::state::Dialog::CaptureTime { .. } + )) + || (r.is_ok() && crate::panels::dialogs::keeps_open(app, &d)) + || (r.is_err() && crate::lightroom_destination::keeps_open_on_error(app, &d)) + { + app.ui.dialog = Some(d); + } + r +} + /// Shown when an export has nowhere to go (no folder typed or chosen, and no home folder to default to). pub const NO_EXPORT_FOLDER: &str = "Choose an export folder first."; diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index 8686dbdf5de..a8ba734e96d 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -303,6 +303,12 @@ impl Headless { self.view.painted_text() } + /// The channel requests reach the app on (a transport in a test feeds it, like the desktop + /// app's control server). + pub fn control_sender(&self) -> Sender { + self.control.clone() + } + /// `app.quit` was requested. pub fn quit_requested(&self) -> bool { self.quit diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4fc43172ce2..5f1f396b6dc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -45,6 +45,9 @@ pub mod sidebar; pub mod slideshow_export; pub mod softpaint; pub mod state; +pub mod surface; +pub mod surface_icons; +pub mod surface_plugin; pub mod sync; pub mod tasks; pub mod text_field; @@ -194,6 +197,8 @@ mod tests_slideshow; #[cfg(test)] mod tests_solo_sections; #[cfg(test)] +mod tests_surface; +#[cfg(test)] mod tests_switch_library; #[cfg(test)] mod tests_sync; @@ -259,6 +264,9 @@ pub type CheckEditorFn = Box Result<(), String>>; /// storage); the work may finish asynchronously. pub type HostAction = Box Result>; +/// Start or stop the control-surface listener (see [`Services::surface_listener`]). +pub type SurfaceListenerFn = Box) -> Result<(), String>>; + /// The system's dark/light appearance where egui doesn't report one (Linux desktops whose /// windowing layer says nothing, e.g. many Wayland compositors). The host answers from what it /// last heard and wakes the UI itself when that changes; it is never polled for changes. @@ -339,6 +347,18 @@ pub struct Services { pub restore_library: Option, /// The system appearance for Appearance Mode ▸ Auto, ahead of egui's own report. pub system_theme: Option, + /// Where control-surface settings are kept (`control-surfaces.json`; none: in memory). + pub surface_store: Option>, + /// Open dialog for control-surface files (TactileBridge `settings.json`, `.lp5`, `.lcsurface`). + pub pick_surface_file: Option, + /// Save dialog for an exported `.lcsurface` layout file. + pub save_surface_file: Option, + /// Start (`Some(port)`) or stop (`None`) the loopback listener control surfaces connect to + /// (desktop only); it serves `surface.*` methods only. + pub surface_listener: Option, + /// Installs a surface's plugin into its maker's app (the LightCraft plugin for Logi + /// Options+; desktop only): Settings ▸ Controls, `surface.installPlugin`. + pub surface_plugin: Option>, } #[derive(Clone, Copy, Debug, Default)] @@ -531,6 +551,8 @@ pub struct LightcraftApp { pub recent_checks: panels::library_problem::RecentChecks, /// The activity stack shows every task, not just the first few ("+N more" was clicked). pub activity_expanded: bool, + /// Control surfaces: their engine, pairing and subscribers (`surface`). + pub surface: surface::SurfaceHost, } impl LightcraftApp { @@ -614,6 +636,7 @@ impl LightcraftApp { alt_asks_for_library: false, recent_checks: Default::default(), activity_expanded: false, + surface: Default::default(), model_setup: Default::default(), } } @@ -626,6 +649,13 @@ impl LightcraftApp { self } + /// Take requests from `rx` (the desktop app's control-surface listener) without the extra + /// screenshot support of [`Self::with_control`]. + pub fn with_requests(mut self, rx: Receiver) -> Self { + self.control_rx = Some(rx); + self + } + pub fn with_control(mut self, rx: Receiver) -> Self { self.control_rx = Some(rx); // keep CPU copies of photo textures so `ui.screenshot {"headless": true}` can draw them @@ -1186,6 +1216,7 @@ impl LightcraftApp { } self.last_time = now; self.drain_control(ctx); + surface::tick(self, ctx); } self.apply_settings(ctx); if !self.synthetic.is_empty() { @@ -1593,7 +1624,9 @@ impl LightcraftApp { panels::second::show(self, &ctx); panels::notices::show(self, &ctx); panels::dialogs::show(self, &ctx); + panels::controls::editor_window(self, &ctx); panels::library_problem::show(self, &ctx); + panels::surface_osd::show(self, &ctx); panels::toast(self, &ctx); drop_overlay::show(self, &ctx); self.widgets = widgets::take_registry(&ctx); @@ -1612,6 +1645,7 @@ impl LightcraftApp { panels::second::show(self, &ctx); panels::notices::show(self, &ctx); panels::dialogs::show(self, &ctx); + panels::controls::editor_window(self, &ctx); panels::library_problem::show(self, &ctx); export_task::poll(self, &ctx); slideshow_export::poll(self, &ctx); @@ -1622,6 +1656,7 @@ impl LightcraftApp { panels::left::album_drag_feedback(self, &ctx); panels::left::section_drag_feedback(self, &ctx); panels::keyword_list::drag_feedback(self, &ctx); + panels::surface_osd::show(self, &ctx); panels::toast(self, &ctx); drop_overlay::show(self, &ctx); self.widgets = widgets::take_registry(&ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 8c249dd3653..5d537d85d59 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -181,6 +181,8 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("tool.none", "No Tool", None, ""), // brush size / feather of the active brush (Masking brush, Remove tool and its selected spot) ("brush.smaller", "Decrease Brush Size", Some("["), "Window>Tools"), + // the brush's Erase mode; {on} sets it (a console key holds it like Alt), none toggles + ("brush.erase", "Erase", None, ""), ("brush.larger", "Increase Brush Size", Some("]"), "Window>Tools"), ("brush.featherLess", "Decrease Brush Feather", Some("Shift+["), "Window>Tools"), ("brush.featherMore", "Increase Brush Feather", Some("Shift+]"), "Window>Tools"), @@ -287,6 +289,26 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("dialog.captureTime", "Edit Capture Time…", None, "Photo"), ("photo.tagFromTracklog", "Auto-Tag from Tracklog…", None, "Photo"), ("app.exportPrevious", "Export with Previous", Some("Cmd+Alt+Shift+E"), "File"), + // control surfaces (`surface`): what their keys run, and their settings for agents + ("surface.maskPrevious", "Select Previous Mask", None, ""), + ("surface.maskNext", "Select Next Mask", None, ""), + ("surface.dialogConfirm", "Confirm Dialog", None, ""), + ("surface.dialogCancel", "Cancel Dialog", None, ""), + ("surface.pageNext", "Next Surface Page", None, ""), + ("surface.pagePrevious", "Previous Surface Page", None, ""), + ("surface.page", "Show Surface Page", None, ""), + ("surface.profile", "Control Surface Profile", None, ""), + ("surface.applyToSelected", "Dials Change All Selected Photos", None, ""), + ("surface.followContext", "Surface Pages Follow the App", None, ""), + ("surface.input", "Control Surface Input", None, ""), + ("surface.state", "Control Surface State", None, ""), + ("surface.settings", "Control Surface Settings", None, ""), + ("surface.forget", "Forget a Paired Surface", None, ""), + ("surface.import", "Import Control Surface Setup", None, ""), + ("surface.export", "Export Control Surface Layout", None, ""), + ("surface.plugin", "Surface Plugin Status", None, ""), + ("surface.installPlugin", "Install the Surface Plugin", None, ""), + ("surface.uninstallPlugin", "Remove the Surface Plugin", None, ""), ]; fn panel(app: &mut LightcraftApp, ctx: &egui::Context, p: RightPanel, name: &str) { @@ -441,6 +463,11 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option Option { + let on = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.brush_erase); + if on && app.ui.tool != "brush" { + // erasing needs the brush: pick it up on the selected mask + if let Err(e) = app.run("tool.brush", json!({})) { + return Some(Err(e)); + } + } + app.ui.brush_erase = on; + Ok(json!({"on": on})) + } "brush.smaller" | "brush.larger" | "brush.featherLess" | "brush.featherMore" => { let (k, df) = match id { "brush.smaller" => (1.0 / 1.2, 0.0), @@ -2315,6 +2353,10 @@ pub fn ui_enabled(app: &LightcraftApp, id: &str) -> bool { } "app.showInFolders" => show_in_folders_enabled(app, None), "app.openSamModelFolder" => app.session.segmenter.dir.is_some() && app.services.open_with.is_some(), + "surface.maskPrevious" | "surface.maskNext" => { + app.session.active().and_then(|id| app.session.develop_of(id)).is_some_and(|d| !d.masks.is_empty()) + } + "surface.dialogConfirm" | "surface.dialogCancel" => app.ui.dialog.is_some(), "file.exportPresets" => app.session.presets.iter().any(|p| !p.builtin), "file.exportMaskEffects" => !app.session.mask_effects.is_empty(), "dialog.saveMaskEffect" => app.session.active().is_some() && app.session.active_mask.is_some(), diff --git a/crates/ui-egui/src/panels/controls.rs b/crates/ui-egui/src/panels/controls.rs new file mode 100644 index 00000000000..8ffb866dd50 --- /dev/null +++ b/crates/ui-egui/src/panels/controls.rs @@ -0,0 +1,1685 @@ +//! Settings ▸ Controls: control surfaces. +//! +//! The page is built around the device itself, as Logi Options+ shows it: pick a surface at the +//! top (MX Creative Keypad, Dialpad, Actions Ring, …, each with its connected / offline state), +//! see a drawing of it with every key and dial showing its icon and name, click one and set what +//! it does in the panel beside it (actions in categories with a search box, a value's own dial +//! speed). The rest sits in sections under the device bar: pages and the pages that follow the +//! app, dial feel, the readout and the keys' look, and profiles, pairing and the plugin install. +//! Everything is saved to `control-surfaces.json` (`crate::surface`). +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: the settings design +//! (TactileBridge's SettingsForm: global and per-value dial feel, workflow presets, bridge +//! timing, OSD, plugin colours, tool contexts, Auto Sync, tool switching). + +use egui::{Color32, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2}; +use lightcraft_surface as ls; +use ls::settings::OsdPosition; +use ls::{Binding, PageGroup}; +use serde_json::{Value, json}; + +use super::settings::{check, choices, heading, hint, row}; +use crate::LightcraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::register; + +// ------------------------------------------------------------------------------------- devices + +/// A surface in the device bar. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Drawing { + Keypad, + Dialpad, + /// The Actions Ring of Logi Options+: eight slots, set on All pages. + Ring, + /// The Loupedeck+: knobs and buttons without pages, Loupedeck's own numbers. + LoupedeckPlus, + /// Support is still to come. + Later, +} + +/// (id, name, drawing, controls) of the surfaces in the device bar, in order. +const DEVICES: &[(&str, &str, Drawing)] = &[ + ("keypad", "MX Creative Keypad", Drawing::Keypad), + ("dialpad", "MX Creative Dialpad", Drawing::Dialpad), + ("ring", "Actions Ring", Drawing::Ring), + ("loupedeck-plus", "Loupedeck+", Drawing::LoupedeckPlus), + ("loupedeck", "Loupedeck Live / CT", Drawing::Later), + ("midi", "MIDI controllers", Drawing::Later), + ("tangent", "Tangent panels", Drawing::Later), +]; + +const KEYPAD: [&str; 9] = ["key.1", "key.2", "key.3", "key.4", "key.5", "key.6", "key.7", "key.8", "key.9"]; +const DIALPAD: [&str; 6] = ["dial", "roller", "pad.1", "pad.2", "pad.3", "pad.4"]; +const RING: [&str; 8] = ["ring.1", "ring.2", "ring.3", "ring.4", "ring.5", "ring.6", "ring.7", "ring.8"]; + +/// The device bar entry a control belongs to. +fn device_of(control: &str) -> &'static str { + if KEYPAD.contains(&control) { + "keypad" + } else if control.starts_with("ld.") { + "loupedeck-plus" + } else if control.starts_with("ring.") { + "ring" + } else { + "dialpad" + } +} + +fn current_device(app: &LightcraftApp) -> (&'static str, &'static str, Drawing) { + let id = app.surface.editor.device.as_str(); + DEVICES.iter().copied().find(|d| d.0 == id).unwrap_or(DEVICES[0]) +} + +/// Whether the MX Creative Console's plugin is connected now. +fn console_connected(app: &LightcraftApp) -> bool { + app.surface.connected().iter().any(|(_, d)| *d == ls::devices::MX_CREATIVE_CONSOLE.name) +} + +/// (connected, status text) of a device bar entry. +fn device_status(app: &LightcraftApp, drawing: Drawing) -> (bool, &'static str) { + match drawing { + Drawing::Keypad | Drawing::Dialpad | Drawing::LoupedeckPlus | Drawing::Ring => { + if !app.surface.settings().enabled { + (false, "Off") + } else if console_connected(app) { + (true, "Connected") + } else { + (false, "Offline") + } + } + Drawing::Later => (false, "Coming later"), + } +} + +// ------------------------------------------------------------------------------------- widgets + +fn slider(ui: &mut egui::Ui, id: &str, v: &mut f64, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> bool { + let r = ui.add(egui::Slider::new(v, range).fixed_decimals(decimals).suffix(suffix)); + register(ui.ctx(), format!("slider:{id}"), r.rect); + r.changed() +} + +fn slider_u32(ui: &mut egui::Ui, id: &str, v: &mut u32, range: std::ops::RangeInclusive, suffix: &str) -> bool { + let r = ui.add(egui::Slider::new(v, range).suffix(suffix)); + register(ui.ctx(), format!("slider:{id}"), r.rect); + r.changed() +} + +fn button(ui: &mut egui::Ui, id: &str, label: &str) -> bool { + let r = ui.button(tr(label)); + register(ui.ctx(), format!("button:{id}"), r.rect); + r.clicked() +} + +fn button_enabled(ui: &mut egui::Ui, id: &str, label: &str, enabled: bool) -> bool { + let r = ui.add_enabled(enabled, egui::Button::new(tr(label))); + register(ui.ctx(), format!("button:{id}"), r.rect); + r.clicked() +} + +fn warn_color() -> Color32 { + Color32::from_rgb(232, 168, 56) +} + +fn ok_color() -> Color32 { + Color32::from_rgb(92, 196, 120) +} + +/// A status dot and its text. +fn status(ui: &mut egui::Ui, t: &Tokens, on: bool, text: &str) { + let (r, _) = ui.allocate_exact_size(vec2(10.0, 16.0), Sense::hover()); + ui.painter().circle_filled(r.center(), 4.0, if on { ok_color() } else { t.text_disabled }); + ui.label(RichText::new(tr(text)).size(11.0).color(if on { t.text } else { t.text_dim })); +} + +// ------------------------------------------------------------------------------------- the page + +/// Sections under the device bar: (id, label). Keys and Dials (the drawn device and its editor) +/// opens in a window of its own ([`editor_window`]): the Settings window is one size on every tab +/// (560 points wide), too narrow for the device beside its editor. +const SECTIONS: &[(&str, &str)] = + &[("pages", "Pages and Tools"), ("feel", "Dial Feel"), ("readout", "Readout and Look"), ("setup", "Profiles and Setup")]; + +pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + learn_and_listen(app, ui.ctx()); + crate::surface_plugin::refresh(app, false); + top_bar(app, ui, t); + banners(app, ui, t); + device_bar(app, ui, t); + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + if button(ui, "surfaceEditKeys", "Edit Keys and Dials…") { + app.surface.editor.window = true; + } + hint(ui, t, "The device as it is laid out: click a key, button or dial (or touch it on the device) to choose what it does."); + }); + ui.separator(); + let section = + if SECTIONS.iter().any(|(id, _)| *id == app.surface.editor.section) { app.surface.editor.section.clone() } else { "pages".to_string() }; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (id, label) in SECTIONS { + if crate::widgets::text_button(ui, &format!("surfaceSection-{id}"), label, section == *id).clicked() { + app.surface.editor.section = id.to_string(); + } + } + }); + ui.add_space(4.0); + match section.as_str() { + "feel" => feel(app, ui, t), + "readout" => timing_and_readout(app, ui, t), + "setup" => { + plugin_section(app, ui, t); + profiles(app, ui, t); + connection(app, ui, t); + } + _ => pages_section(app, ui, t), + } +} + +/// Keys and Dials: the drawn device and its editor, in a resizable window of its own (opened +/// from Settings ▸ Controls; widget `window:surfaceEditor`). It stays open while Settings is. +pub fn editor_window(app: &mut LightcraftApp, ctx: &egui::Context) { + if !app.surface.editor.window { + return; + } + if !matches!(&app.ui.dialog, Some(crate::state::Dialog::Settings { .. })) { + app.surface.editor.window = false; + return; + } + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let mut open = true; + let r = egui::Window::new(tr("Keys and Dials")) + .id(egui::Id::new("surfaceEditorWindow")) + // over the Settings window it was opened from + .order(egui::Order::Foreground) + .open(&mut open) + .resizable(true) + .collapsible(false) + .default_size(vec2((screen.width() - 80.0).clamp(320.0, 980.0), (screen.height() - 120.0).clamp(240.0, 680.0))) + .max_size(vec2((screen.width() - 32.0).max(320.0), (screen.height() - 32.0).max(240.0))) + .show(ctx, |ui| { + learn_and_listen(app, ui.ctx()); + device_bar(app, ui, &t); + ui.separator(); + let max_h = (ui.available_height() - 8.0).max(220.0); + layout_section(app, ui, &t, max_h); + }); + if let Some(r) = r { + register(ctx, "window:surfaceEditor", r.response.rect); + } + if !open { + app.surface.editor.window = false; + } +} + +/// What a control touched on the device does while Settings ▸ Controls (or its editor window) is +/// open: it is selected in the editor (Touch to find) and does nothing to the photo. +fn learn_and_listen(app: &mut LightcraftApp, ctx: &egui::Context) { + if let Some(c) = app.surface.runtime.take_learned() { + app.surface.editor.device = device_of(&c).to_string(); + app.surface.editor.window = true; + // a Loupedeck+ colour knob: show the colour mode it was turned in + if let Some(n) = c.strip_prefix("ld.r").and_then(|n| n.parse::().ok()).filter(|n| (1..=32).contains(n)) { + ctx.data_mut(|d| d.insert_temp(egui::Id::new("surfaceLoupedeckMode"), (n - 1) / 8)); + } + app.surface.editor.control = Some(c); + app.surface.editor.params_text.clear(); + } + // Touch to find: while this page is open, a control touched on the device is selected here + // and does nothing to the photo (`surface::tick` stops it once the page is gone) + if !app.surface.editor.touch_find_off && app.surface.settings().enabled { + app.surface.editor.touch_find = Some(app.surface.now()); + if !app.surface.runtime.learning() { + app.surface.runtime.arm_learn(); + } + } +} + +/// On / off, the profile, and where the plugin stands, in one line. +fn top_bar(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + ui.horizontal_wrapped(|ui| { + let mut on = app.surface.settings().enabled; + if check(ui, "surface.enabled", &mut on, "Use control surfaces") { + let s = app.surface.runtime.settings_mut(); + s.enabled = on; + // off stays off; on lets LightCraft set up an installed plugin by itself again + s.off_by_user = !on; + app.surface.changed(); + if on { + crate::surface_plugin::auto_setup(app); + } + } + ui.add_space(12.0); + ui.label(RichText::new(tr("Profile")).color(t.text_label)); + let names: Vec = app.surface.settings().profiles.iter().map(|p| p.name.clone()).collect(); + let current = app.surface.settings().profile.clone(); + let r = egui::ComboBox::from_id_salt("surfaceProfile").selected_text(¤t).width(140.0).show_ui(ui, |ui| { + for n in &names { + if ui.selectable_label(*n == current, n).clicked() && *n != current { + let _ = app.run("surface.profile", json!({"profile": n})); + app.surface.editor.page = None; + } + } + }); + register(ui.ctx(), "combo:surfaceProfile", r.response.rect); + }); +} + +/// Pairing requests and a missing plugin: shown above everything until dealt with. +fn banners(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + let waiting: Vec<_> = app.surface.pairing.waiting().cloned().collect(); + for w in waiting { + egui::Frame::new().fill(t.inset).stroke(Stroke::new(1.0, t.accent)).corner_radius(4.0).inner_margin(6.0).show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(crate::i18n::tr_format!("{name} asks to pair. Code: {code}", name = w.name.clone(), code = w.code.clone())) + .color(t.text), + ); + if button(ui, &format!("surfaceApprove-{}", w.client), "Approve") { + let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let mut s = app.surface.settings().clone(); + if app.surface.pairing.approve(&w.request, &mut s, now).is_ok() { + app.surface.runtime.settings_mut().paired = s.paired; + app.surface.changed(); + } + } + if button(ui, &format!("surfaceDeny-{}", w.client), "Deny") { + app.surface.pairing.deny(&w.request); + } + }); + hint(ui, t, "Check that the keypad shows the same code."); + }); + } + let st = app.surface.plugin.status.clone(); + if let Some(s) = st.filter(|s| s.host.is_some() && (s.installed.is_none() || s.update_available()) && s.package.is_some()) + && app.surface.plugin.job.is_none() + { + ui.horizontal_wrapped(|ui| { + let text = if s.installed.is_none() { + "Logi Options+ is on this computer, but the LightCraft plugin isn't installed yet." + } else { + "A newer LightCraft plugin for Logi Options+ comes with this LightCraft." + }; + ui.label(RichText::new(tr(text)).color(warn_color())); + let label = if s.installed.is_none() { "Install the plugin" } else { "Update the plugin" }; + if button(ui, "surfaceInstallPluginBanner", label) { + let r = crate::surface_plugin::start(app, true); + if let Err(e) = r { + app.surface.plugin.message = Some(Err(e)); + } + } + }); + } +} + +fn device_bar(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + let (current, _, _) = current_device(app); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + for (id, name, drawing) in DEVICES { + let (on, _) = device_status(app, *drawing); + let selected = *id == current; + let fill = if selected { t.pressed } else { t.button }; + // one allocated chip (so the bar wraps on a narrow window): a status dot and the name + let color = if *drawing == Drawing::Later { t.text_dim } else { t.text }; + let galley = ui.painter().layout_no_wrap(tr(name).to_string(), FontId::proportional(11.5), color); + let (rect, _) = ui.allocate_exact_size(vec2(galley.size().x + 30.0, 24.0), Sense::hover()); + ui.painter().rect_filled(rect, CornerRadius::same(4), fill); + ui.painter().rect_stroke( + rect, + CornerRadius::same(4), + Stroke::new(1.0, if selected { t.accent } else { t.button_border }), + StrokeKind::Inside, + ); + let dot = match drawing { + Drawing::Later => t.text_disabled, + _ if on => ok_color(), + _ => t.text_dim, + }; + ui.painter().circle_filled(pos2(rect.left() + 12.0, rect.center().y), 3.5, dot); + ui.painter().galley(pos2(rect.left() + 22.0, rect.center().y - galley.size().y / 2.0), galley, color); + let r = ui.interact(rect, ui.id().with(("surfaceDevice", *id)), Sense::click()); + register(ui.ctx(), format!("button:surfaceDevice-{id}"), r.rect); + let (_, text) = device_status(app, *drawing); + let r = r.on_hover_text(tr(text)); + if r.clicked() { + app.surface.editor.device = id.to_string(); + app.surface.editor.window = true; + if app.surface.editor.control.as_deref().is_some_and(|c| device_of(c) != *id) { + app.surface.editor.control = None; + } + app.surface.editor.page = None; + } + } + }); +} + +// ------------------------------------------------------------------------------------- layout + +const BASE: &str = "\u{0}base"; + +/// The page group a device's pages belong to. +fn group_of(drawing: Drawing) -> PageGroup { + if drawing == Drawing::Dialpad { PageGroup::Dials } else { PageGroup::Keys } +} + +fn layout_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f32) { + let (_, name, drawing) = current_device(app); + match drawing { + Drawing::Ring => { + ring_section(app, ui, t, max_h); + return; + } + Drawing::Later => { + heading(ui, t, name); + hint(ui, t, "Support for this surface comes later. Its keys and dials will be set up here, like the MX Creative Console's."); + return; + } + Drawing::LoupedeckPlus => { + loupedeck_section(app, ui, t, max_h); + return; + } + _ => {} + } + let Some(profile) = app.surface.settings().active_profile().cloned() else { return }; + let group = group_of(drawing); + // the pages this device shows: its own pages, then every page (base); tool pages in a menu + let own: Vec<&ls::Page> = profile.pages.iter().filter(|p| !p.auto && p.in_group(group)).collect(); + let tools: Vec<&ls::Page> = profile.pages.iter().filter(|p| p.auto).collect(); + let page_key = app + .surface + .editor + .page + .clone() + // a page of this device's group (a keypad page doesn't carry the dial) + .filter(|k| k == BASE || profile.page(k).is_some_and(|p| p.auto || p.in_group(group))) + .unwrap_or_else(|| own.first().map(|p| p.name.clone()).unwrap_or(BASE.into())); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + ui.label(RichText::new(tr("Page")).color(t.text_label)); + for (i, p) in own.iter().enumerate() { + if crate::widgets::text_button(ui, &format!("surfacePage-{i}"), &p.name, page_key == p.name).clicked() { + app.surface.editor.page = Some(p.name.clone()); + } + } + if crate::widgets::text_button(ui, "surfacePage-base", "All pages", page_key == BASE) + .on_hover_text(tr("What a control does on every page that leaves it empty")) + .clicked() + { + app.surface.editor.page = Some(BASE.into()); + } + if !tools.is_empty() { + let is_tool = tools.iter().any(|p| p.name == page_key); + let text = if is_tool { page_key.clone() } else { tr("Tool pages").to_string() }; + let r = egui::ComboBox::from_id_salt("surfaceToolPage").selected_text(text).show_ui(ui, |ui| { + for p in &tools { + if ui.selectable_label(p.name == page_key, &p.name).clicked() { + app.surface.editor.page = Some(p.name.clone()); + } + } + }); + register(ui.ctx(), "combo:surfaceToolPage", r.response.rect); + } + }); + ui.add_space(4.0); + // the device shows the page being edited (live), so the drawing and the hardware match + if page_key != BASE { + app.surface.runtime.show_page(&page_key); + } + let page = profile.page(&page_key).cloned(); + let binding = |c: &str| -> Option { + if page_key == BASE { profile.base.get(c).cloned() } else { page.as_ref().and_then(|p| p.bindings.get(c).cloned()) } + }; + // (control, its binding, whether that comes from All pages) + let of = |c: &str| -> (String, Option, bool) { + match binding(c) { + Some(b) => (c.to_string(), Some(b), false), + None if page_key != BASE => (c.to_string(), profile.base.get(c).cloned(), profile.base.contains_key(c)), + None => (c.to_string(), None, false), + } + }; + let views: Vec<(String, Option, bool)> = match drawing { + Drawing::Keypad => KEYPAD.iter().map(|c| of(c)).collect(), + _ => DIALPAD.iter().map(|c| of(c)).collect(), + }; + let wide = ui.available_width() >= 640.0; + let draw_w = if wide { 300.0 } else { ui.available_width().min(300.0) }; + let mut clicked: Option = None; + let mut step: i32 = 0; + let mut device = |app: &LightcraftApp, ui: &mut egui::Ui| { + let labels: Vec = views + .iter() + .map(|(c, b, inherited)| { + (c.clone(), *inherited, b.as_ref().map(|b| short_label(app, b)).unwrap_or_default(), b.as_ref().and_then(ls::icons::icon_for)) + }) + .collect(); + let selected = app.surface.editor.control.clone(); + match drawing { + Drawing::Keypad => draw_keypad(ui, t, draw_w, &labels, selected.as_deref(), &mut clicked, &mut step), + _ => draw_dialpad(ui, t, draw_w, &labels, selected.as_deref(), &mut clicked), + } + }; + if wide { + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(draw_w); + device(app, ui); + }); + ui.add_space(10.0); + ui.vertical(|ui| editor_panel(app, ui, t, &page_key, max_h)); + }); + } else { + device(app, ui); + ui.add_space(6.0); + editor_panel(app, ui, t, &page_key, max_h); + } + if let Some(c) = clicked { + app.surface.editor.control = Some(c); + app.surface.editor.params_text.clear(); + } + apply_drop(app, ui, &page_key); + drag_preview(ui, t); + if step != 0 && !own.is_empty() { + let i = own.iter().position(|p| p.name == page_key).map_or(0, |i| i as i32); + let n = own.len() as i32; + let next = (i + step).rem_euclid(n) as usize; + if let Some(p) = own.get(next) { + app.surface.editor.page = Some(p.name.clone()); + } + } +} + +/// The Loupedeck+: every knob and button as Loupedeck numbers them, what each does (its label's +/// own job until set here or imported), Loupedeck's profiles found on this computer to import, +/// and the editor beside them. The console has no pages: its controls hold on every page. +fn loupedeck_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f32) { + heading(ui, t, "Loupedeck+"); + hint( + ui, + t, + "The Loupedeck+ works through the LightCraft plugin. Every knob and button does what its label says until you set it here, or bring over your own Loupedeck profile (only the layout comes along).", + ); + ui.horizontal_wrapped(|ui| { + // Loupedeck's own profiles on this computer, the last changed first: pick one, Import + let found = crate::surface::loupedeck_profiles(); + if !found.is_empty() { + let mut pick = ui.ctx().data(|d| d.get_temp::(egui::Id::new("surfaceLoupedeckPick"))).unwrap_or(0).min(found.len() - 1); + ui.label(RichText::new(tr("Loupedeck profile")).color(t.text_label)); + let r = egui::ComboBox::from_id_salt("surfaceLoupedeckProfile").selected_text(found[pick].0.clone()).width(240.0).show_ui(ui, |ui| { + for (i, (name, path)) in found.iter().enumerate() { + if ui.selectable_label(i == pick, name).on_hover_text(path.to_string_lossy()).clicked() { + pick = i; + } + } + }); + register(ui.ctx(), "combo:surfaceLoupedeckProfile", r.response.rect); + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("surfaceLoupedeckPick"), pick)); + if button(ui, "surfaceImportLoupedeck", "Import") { + let r = app_run_import(app, &found[pick].1.to_string_lossy()); + report(app, r); + app.surface.editor.device = "loupedeck-plus".into(); + } + } + if app.services.pick_surface_file.is_some() && button(ui, "surfaceImportLoupedeckFile", "Import a Loupedeck profile…") { + let files = app.services.pick_surface_file.as_mut().map(|f| f()).unwrap_or_default(); + for f in files { + let r = app_run_import(app, &f); + report(app, r); + app.surface.editor.device = "loupedeck-plus".into(); + } + } + }); + if let Some(m) = app.surface.editor.message.clone() { + ui.label(RichText::new(m).color(t.text_label)); + } + let Some(profile) = app.surface.settings().active_profile().cloned() else { return }; + let selected = app.surface.editor.control.clone(); + let mut clicked: Option = None; + // the P1–P8 knobs send other numbers in each of the console's colour modes: show one mode + let mode_id = egui::Id::new("surfaceLoupedeckMode"); + let mut mode = ui.ctx().data(|d| d.get_temp::(mode_id)).unwrap_or(0).min(3); + let mut grid = |app: &LightcraftApp, ui: &mut egui::Ui| { + let cell = |ui: &mut egui::Ui, id: &str, size: f32, clicked: &mut Option| { + let Some(c) = ls::devices::find_control(id) else { return }; + let own = profile.base.get(c.id).cloned(); + let inherited = own.is_none(); + let b = own.or_else(|| ls::loupedeck::default_binding(c.id)); + let label = b.as_ref().map(|b| short_label(app, b)).unwrap_or_default(); + let icon = b.as_ref().and_then(ls::icons::icon_for); + let (area, _) = ui.allocate_exact_size(vec2(size, size + 16.0), Sense::hover()); + let face = Rect::from_min_size(area.min, vec2(size, size)); + if draw_control(ui, t, face, c.id, (&label, icon, inherited), selected.as_deref() == Some(c.id), c.kind == ls::ControlKind::Encoder) { + *clicked = Some(c.id.to_string()); + } + // a knob's press is its own control: a small chip under it + let press = c.id.strip_prefix("ld.r").map(|n| format!("ld.b{n}")).filter(|p| ls::devices::find_control(p).is_some()); + let name_rect = Rect::from_min_size(pos2(area.left(), face.bottom() + 1.0), vec2(size, 14.0)); + if let Some(p) = press { + let chip = Rect::from_center_size(pos2(face.right() - 9.0, face.bottom() - 6.0), vec2(16.0, 12.0)); + let r = ui.interact(chip, ui.id().with(("surfacePress", &p)), Sense::click()); + register(ui.ctx(), format!("button:surfaceControl-{p}"), chip); + let on = selected.as_deref() == Some(p.as_str()); + let has = profile.base.contains_key(&p) || ls::loupedeck::default_binding(&p).is_some(); + ui.painter().rect_filled( + chip, + CornerRadius::same(3), + if on { + t.accent + } else if r.hovered() { + Color32::from_gray(90) + } else { + Color32::from_gray(60) + }, + ); + ui.painter().circle_filled(chip.center(), 2.5, if has { Color32::WHITE } else { Color32::from_gray(140) }); + let press_label = ls::devices::find_control(&p).map_or("", |c| c.label); + if r.on_hover_text(tr(press_label)).clicked() { + *clicked = Some(p.clone()); + } + } + // P1–P8 by their number (the mode is chosen above them) + let p_knob = c.id.strip_prefix("ld.r").and_then(|n| n.parse::().ok()).filter(|n| (1..=32).contains(n)); + let caption = p_knob.map_or_else(|| tr(c.label).to_string(), |n| format!("P{}", (n - 1) % 8 + 1)); + ui.painter().text(name_rect.center(), egui::Align2::CENTER_CENTER, caption, FontId::proportional(9.5), t.text_dim); + }; + let zone = |ui: &mut egui::Ui, title: &str, add: &mut dyn FnMut(&mut egui::Ui)| { + egui::Frame::new() + .fill(Color32::from_gray(40)) + .stroke(Stroke::new(1.0, Color32::from_gray(70))) + .corner_radius(10.0) + .inner_margin(8.0) + .show(ui, |ui| { + ui.label(RichText::new(tr(title)).font(t.semibold(12.0)).color(t.text_label)); + add(ui); + }); + ui.add_space(6.0); + }; + zone(ui, "Colour knobs P1–P8", &mut |ui| { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (i, m) in ["Hue", "Sat", "Lum", "B&W"].iter().enumerate() { + if crate::widgets::text_button(ui, &format!("surfaceLoupedeckMode-{i}"), m, mode == i as u32).clicked() { + mode = i as u32; + } + } + hint(ui, t, "The console's Hue, Sat, Lum and Col/BW buttons switch what P1–P8 send."); + }); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 4.0); + for k in 1..=8 { + cell(ui, &format!("ld.r{}", mode * 8 + k), 64.0, &mut clicked); + } + }); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 4.0); + for b in [98, 99, 100, 101] { + cell(ui, &format!("ld.b{b}"), 46.0, &mut clicked); + } + }); + }); + zone(ui, "Tone knobs", &mut |ui| { + for row in [[46, 33, 45, 40, 44, 35, 34], [38, 39, 37, 36, 41, 42, 47]] { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 4.0); + for n in row { + cell(ui, &format!("ld.r{n}"), 64.0, &mut clicked); + } + }); + } + }); + zone(ui, "Control Dial and arrows", &mut |ui| { + ui.horizontal_top(|ui| { + cell(ui, "ld.r48", 92.0, &mut clicked); + ui.vertical(|ui| { + for row in [&[78, 79, 110][..], &[49, 50, 51, 52, 53, 54], &[114, 115, 116]] { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 4.0); + for n in row { + cell(ui, &format!("ld.b{n}"), 44.0, &mut clicked); + } + }); + } + }); + }); + }); + zone(ui, "Buttons", &mut |ui| { + let rows: [&[u32]; 3] = [&[66, 67, 68, 69, 70, 91, 102, 97], &[71, 72, 73, 74, 75, 95, 96, 92, 93, 88], &[76, 77, 89, 90, 94, 103, 104]]; + for row in rows { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 4.0); + for n in row { + cell(ui, &format!("ld.b{n}"), 44.0, &mut clicked); + } + }); + } + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 4.0); + ui.label(RichText::new(tr("P1–P8 pressed")).size(11.0).color(t.text_dim)); + for n in 80..=87 { + cell(ui, &format!("ld.b{n}"), 40.0, &mut clicked); + } + }); + }); + }; + let wide = ui.available_width() >= 760.0; + if wide { + ui.horizontal_top(|ui| { + let w = (ui.available_width() - 310.0).max(300.0); + ui.vertical(|ui| { + ui.set_width(w); + egui::ScrollArea::vertical().id_salt("surfaceLoupedeck").max_height(max_h).show(ui, |ui| grid(app, ui)); + }); + ui.add_space(10.0); + ui.vertical(|ui| editor_panel(app, ui, t, BASE, max_h)); + }); + } else { + egui::ScrollArea::vertical().id_salt("surfaceLoupedeck").max_height(max_h * 0.6).show(ui, |ui| grid(app, ui)); + ui.add_space(6.0); + editor_panel(app, ui, t, BASE, max_h); + } + ui.ctx().data_mut(|d| d.insert_temp(mode_id, mode)); + if let Some(c) = clicked { + app.surface.editor.control = Some(c); + app.surface.editor.params_text.clear(); + } + apply_drop(app, ui, BASE); + drag_preview(ui, t); +} + +/// The Actions Ring (Logi Options+' on-screen ring, opened from a button of the mouse or the +/// console): eight slots around a circle, the same on every page. Drag an action from the list +/// onto a slot, or click a slot and pick one. +fn ring_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f32) { + heading(ui, t, "Actions Ring"); + hint(ui, t, "Drag an action from the list onto a slot, or click a slot and choose its action. The ring is the same on every page."); + let Some(profile) = app.surface.settings().active_profile().cloned() else { return }; + let views: Vec = RING + .iter() + .map(|c| { + let b = profile.base.get(*c); + ((*c).to_string(), false, b.map(|b| short_label(app, b)).unwrap_or_default(), b.and_then(ls::icons::icon_for)) + }) + .collect(); + let mut clicked: Option = None; + let selected = app.surface.editor.control.clone(); + let wide = ui.available_width() >= 640.0; + let draw_w = if wide { 300.0 } else { ui.available_width().min(300.0) }; + if wide { + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(draw_w); + draw_ring(ui, t, draw_w, &views, selected.as_deref(), &mut clicked); + }); + ui.add_space(10.0); + ui.vertical(|ui| editor_panel(app, ui, t, BASE, max_h)); + }); + } else { + draw_ring(ui, t, draw_w, &views, selected.as_deref(), &mut clicked); + ui.add_space(6.0); + editor_panel(app, ui, t, BASE, max_h); + } + if let Some(c) = clicked { + app.surface.editor.control = Some(c); + app.surface.editor.params_text.clear(); + } + apply_drop(app, ui, BASE); + drag_preview(ui, t); +} + +/// The ring's centre and the angle of slot `i` (0-based): slot 1 at the top, then clockwise. +pub fn ring_slot_angle(i: usize) -> f32 { + -std::f32::consts::FRAC_PI_2 + i as f32 * std::f32::consts::TAU / 8.0 +} + +fn draw_ring(ui: &mut egui::Ui, t: &Tokens, w: f32, slots: &[View], selected: Option<&str>, clicked: &mut Option) { + let side = w.min(300.0); + let (cell, _) = ui.allocate_exact_size(vec2(w, side), Sense::hover()); + let center = cell.center(); + let p = ui.painter(); + p.circle_filled(center, side * 0.48, Color32::from_gray(36)); + p.circle_stroke(center, side * 0.48, Stroke::new(1.0, Color32::from_gray(70))); + p.circle_filled(center, side * 0.16, Color32::from_gray(52)); + p.text(center, egui::Align2::CENTER_CENTER, tr("LightCraft"), FontId::proportional(11.0), t.text_dim); + let slot = side * 0.24; + for (i, (c, inherited, label, icon)) in slots.iter().enumerate() { + let a = ring_slot_angle(i); + let at = center + vec2(a.cos(), a.sin()) * side * 0.34; + let r = Rect::from_center_size(at, vec2(slot, slot)); + if draw_control(ui, t, r, c, (label, *icon, *inherited), selected == Some(c.as_str()), true) { + *clicked = Some(c.clone()); + } + } +} + +/// One control face: a rounded key with its icon and name. +#[allow(clippy::too_many_arguments)] +fn draw_control(ui: &mut egui::Ui, t: &Tokens, rect: Rect, control: &str, view: (&str, Option<&str>, bool), selected: bool, round: bool) -> bool { + let (label, icon, inherited) = view; + let id = ui.id().with(("surfaceControl", control)); + let r = ui.interact(rect, id, Sense::click()); + register(ui.ctx(), format!("button:surfaceControl-{control}"), rect); + // an action dragged from the list onto this control: it does that from now on + let dragging = r.dnd_hover_payload::().is_some(); + if let Some(p) = r.dnd_release_payload::() { + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new(DROP_ID), (control.to_string(), (*p).clone()))); + } + let p = ui.painter(); + let fill = if r.hovered() || dragging { Color32::from_gray(42) } else { Color32::from_gray(26) }; + let stroke = if dragging { + Stroke::new(2.5, ok_color()) + } else if selected { + Stroke::new(2.0, t.accent) + } else { + Stroke::new(1.0, Color32::from_gray(70)) + }; + if round { + p.circle_filled(rect.center(), rect.width() / 2.0, fill); + p.circle_stroke(rect.center(), rect.width() / 2.0, stroke); + } else { + p.rect_filled(rect, CornerRadius::same(8), fill); + p.rect_stroke(rect, CornerRadius::same(8), stroke, StrokeKind::Inside); + } + let text_h = if label.is_empty() { 0.0 } else { (rect.height() * 0.3).min(28.0) }; + let icon_side = ((rect.height() - text_h) * 0.62).min(rect.width() * 0.62); + let mut drew = false; + if let Some(name) = icon { + let ir = Rect::from_center_size(pos2(rect.center().x, rect.top() + (rect.height() - text_h) / 2.0 + 2.0), vec2(icon_side, icon_side)); + let tint = if inherited { Color32::from_gray(120) } else { Color32::WHITE }; + drew = crate::surface_icons::paint(ui, name, ir, tint); + } + let text = if label.is_empty() { "—".to_string() } else { label.to_string() }; + let font = FontId::proportional(if drew { 10.0 } else { 11.0 }); + let galley = ui.painter().layout(text, font, if label.is_empty() || inherited { t.text_dim } else { t.text }, rect.width() - 8.0); + let y = if drew { rect.bottom() - text_h + (text_h - galley.size().y).max(0.0) / 2.0 - 2.0 } else { rect.center().y - galley.size().y / 2.0 }; + let pos = pos2(rect.center().x - galley.size().x / 2.0, y); + ui.painter().galley(pos, galley, t.text); + let tip = if label.is_empty() { + tr("Nothing — click to set").to_string() + } else if inherited { + format!("{label} ({})", tr("from All pages")) + } else { + label.to_string() + }; + let r = r.on_hover_text(tip); + r.clicked() +} + +/// (control, inherited from All pages, label, icon). +type View = (String, bool, String, Option<&'static str>); + +/// An action being dragged from the action list onto a control. +#[derive(Clone, Debug, PartialEq)] +struct DragAction { + binding: Binding, + label: String, + icon: Option<&'static str>, +} + +/// Where a drop on a control waits for the page to apply it: (control, action). +const DROP_ID: &str = "surfaceDrop"; + +/// The action being dragged, drawn under the pointer. +fn drag_preview(ui: &egui::Ui, t: &Tokens) { + let Some(d) = egui::DragAndDrop::payload::(ui.ctx()) else { return }; + let Some(at) = ui.ctx().pointer_latest_pos() else { return }; + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("surfaceDragPreview"))); + let galley = painter.layout_no_wrap(d.label.clone(), FontId::proportional(12.0), t.text); + let rect = Rect::from_min_size(at + vec2(14.0, 6.0), vec2(galley.size().x + 36.0, 26.0)); + painter.rect_filled(rect, CornerRadius::same(5), t.inset); + painter.rect_stroke(rect, CornerRadius::same(5), Stroke::new(1.0, t.accent), StrokeKind::Inside); + if let Some(icon) = d.icon { + crate::surface_icons::paint_with(ui.ctx(), &painter, icon, Rect::from_min_size(rect.min + vec2(5.0, 4.0), vec2(18.0, 18.0)), Color32::WHITE); + } + painter.galley(pos2(rect.left() + 28.0, rect.center().y - galley.size().y / 2.0), galley, t.text); +} + +/// An action dropped on a control this frame: set it (on `page`) and select the control. A dial +/// takes only values and page turns. +fn apply_drop(app: &mut LightcraftApp, ui: &egui::Ui, page: &str) { + let id = egui::Id::new(DROP_ID); + let Some((control, d)) = ui.ctx().data_mut(|m| { + let v = m.get_temp::<(String, DragAction)>(id); + m.remove::<(String, DragAction)>(id); + v + }) else { + return; + }; + let turns = matches!(d.binding, Binding::Value { .. } | Binding::PageNext { .. } | Binding::PagePrevious { .. }); + if ls::devices::is_encoder(&control) && !turns { + app.surface.editor.message = Some(tr("A dial turns values: drop a value (or a page turn) on it.").to_string()); + return; + } + set_binding(app, page, &control, Some(d.binding)); + app.surface.editor.control = Some(control); + app.surface.editor.params_text.clear(); + app.surface.editor.message = None; +} + +fn draw_keypad(ui: &mut egui::Ui, t: &Tokens, w: f32, keys: &[View], selected: Option<&str>, clicked: &mut Option, step: &mut i32) { + let pad = 14.0; + let gap = 8.0; + let key = ((w - 2.0 * pad - 2.0 * gap) / 3.0).max(40.0); + let body_h = pad * 2.0 + key * 3.0 + gap * 2.0 + gap + 30.0; + let (body, _) = ui.allocate_exact_size(vec2(w, body_h), Sense::hover()); + ui.painter().rect_filled(body, CornerRadius::same(18), Color32::from_gray(52)); + ui.painter().rect_stroke(body, CornerRadius::same(18), Stroke::new(1.0, Color32::from_gray(80)), StrokeKind::Inside); + for (i, (c, inherited, label, icon)) in keys.iter().enumerate() { + let (row, col) = ((i / 3) as f32, (i % 3) as f32); + let r = Rect::from_min_size(pos2(body.left() + pad + col * (key + gap), body.top() + pad + row * (key + gap)), vec2(key, key)); + if draw_control(ui, t, r, c, (label, *icon, *inherited), selected == Some(c.as_str()), false) { + *clicked = Some(c.clone()); + } + } + // the two page buttons under the keys, at the left and right corners (as on the Keypad) + let y = body.top() + pad + 3.0 * key + 3.0 * gap; + let bw = (key * 0.55).max(36.0); + for (i, (s, glyph)) in [(-1, "‹"), (1, "›")].into_iter().enumerate() { + let x = if s < 0 { body.left() + pad } else { body.right() - pad - bw }; + let r = Rect::from_min_size(pos2(x, y), vec2(bw, 26.0)); + let resp = ui.interact(r, ui.id().with(("surfacePageButton", i)), Sense::click()); + register(ui.ctx(), format!("button:surfaceKeypadPage-{}", if s < 0 { "previous" } else { "next" }), r); + ui.painter().rect_filled(r, CornerRadius::same(6), if resp.hovered() { Color32::from_gray(42) } else { Color32::from_gray(30) }); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, glyph, FontId::proportional(16.0), t.text); + if resp.on_hover_text(tr(if s < 0 { "Previous page" } else { "Next page" })).clicked() { + *step = s; + } + } +} + +/// Where each control of the MX Creative Dialpad sits, as fractions of its square body (the real +/// device, seen from above): buttons 1 and 2 top left, the roller top right, the big dial in the +/// middle, button 3 bottom left and button 4 bottom right. (control, centre x, centre y, width, +/// height, round). +pub const DIALPAD_PLACES: [(&str, f32, f32, f32, f32, bool); 6] = [ + ("pad.1", 0.16, 0.16, 0.2, 0.2, true), + ("pad.2", 0.39, 0.16, 0.2, 0.2, true), + ("roller", 0.79, 0.16, 0.3, 0.19, false), + ("dial", 0.5, 0.55, 0.52, 0.52, true), + ("pad.3", 0.15, 0.87, 0.19, 0.19, true), + ("pad.4", 0.85, 0.87, 0.19, 0.19, true), +]; + +fn draw_dialpad(ui: &mut egui::Ui, t: &Tokens, w: f32, controls: &[View], selected: Option<&str>, clicked: &mut Option) { + let side = w.min(320.0); + let (cell, _) = ui.allocate_exact_size(vec2(w, side), Sense::hover()); + let body = Rect::from_center_size(cell.center(), vec2(side, side)); + let corner = CornerRadius::same((side * 0.1) as u8); + ui.painter().rect_filled(body, corner, Color32::from_gray(52)); + ui.painter().rect_stroke(body, corner, Stroke::new(1.0, Color32::from_gray(80)), StrokeKind::Inside); + let find = |id: &str| controls.iter().find(|v| v.0 == id); + for (id, x, y, cw, ch, round) in DIALPAD_PLACES { + let Some((c, inherited, label, icon)) = find(id) else { continue }; + let r = Rect::from_center_size(pos2(body.left() + x * side, body.top() + y * side), vec2(cw * side, ch * side)); + if draw_control(ui, t, r, c, (label, *icon, *inherited), selected == Some(c.as_str()), round) { + *clicked = Some(c.clone()); + } + } +} + +fn short_label(_app: &LightcraftApp, b: &Binding) -> String { + match b { + Binding::Command { command, params } => { + let s = ls::icons::command_label(command, params); + if s == *command { + // the registry's own name (a UI command's, else the engine's) + crate::menus::ui_commands() + .find(|c| c.0 == command) + .map(|c| tr(c.1).to_string()) + .or_else(|| lightcraft_engine::find_command(command).map(|c| tr(c.label).to_string())) + .unwrap_or_else(|| s.clone()) + } else { + tr(&s).to_string() + } + } + other => tr(&other.describe()).to_string(), + } +} + +fn edit_profile(app: &mut LightcraftApp, f: impl FnOnce(&mut ls::Profile)) { + let s = app.surface.runtime.settings_mut(); + let cur = s.profile.clone(); + if let Some(p) = s.profiles.iter_mut().find(|p| p.name == cur) { + f(p); + } + app.surface.changed(); +} + +fn edit_page(app: &mut LightcraftApp, page: &str, f: impl FnOnce(&mut ls::Page)) { + edit_profile(app, |p| { + if let Some(q) = p.pages.iter_mut().find(|q| q.name == page) { + f(q); + } + }); +} + +fn set_binding(app: &mut LightcraftApp, page: &str, control: &str, b: Option) { + edit_profile(app, |p| { + let map = if page == BASE { Some(&mut p.base) } else { p.pages.iter_mut().find(|q| q.name == page).map(|q| &mut q.bindings) }; + if let Some(map) = map { + match b { + Some(b) => { + map.insert(control.to_string(), b); + } + None => { + map.remove(control); + } + } + } + }); +} + +/// The panel beside the drawing: what the selected control does, and the action picker. +fn editor_panel(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, page: &str, max_h: f32) { + ui.horizontal_wrapped(|ui| { + let mut on = !app.surface.editor.touch_find_off; + if check(ui, "surface.touchFind", &mut on, "Touch to find") { + app.surface.editor.touch_find_off = !on; + if !on { + app.surface.editor.touch_find = None; + app.surface.runtime.cancel_learn(); + } + } + if on { + hint( + ui, + t, + "Touch a key, button or dial on the device to select it here. While this page is open, the device doesn't change your photo.", + ); + } else { + let learning = app.surface.runtime.learning(); + if button(ui, "surfaceLearn", if learning { "Cancel learning" } else { "Learn: touch a control" }) { + if learning { + app.surface.runtime.cancel_learn(); + } else { + app.surface.runtime.arm_learn(); + } + } + if learning { + hint(ui, t, "Turn a dial or press a key on the surface…"); + } + } + }); + // (the Loupedeck+ page shows its import messages above its drawing) + if current_device(app).2 != Drawing::LoupedeckPlus + && let Some(m) = app.surface.editor.message.clone() + { + ui.label(RichText::new(m).color(warn_color())); + } + let Some(control) = app.surface.editor.control.clone().filter(|c| device_of(c) == current_device(app).0) else { + ui.add_space(6.0); + hint( + ui, + t, + "Drag an action from the list onto a key, button or dial of the drawing, or click one (or touch it on the device) to choose what it does.", + ); + ui.add_space(4.0); + crate::text_field::TextField::singleline("field:surfaceActionSearch", &mut app.surface.editor.filter) + .hint(tr("Search actions")) + .width(240.0) + .show(ui); + // nothing selected: the list is there to drag from (a key's list: every action) + let _ = action_picker(app, ui, t, "", None, max_h - 80.0); + return; + }; + let current = { + let Some(p) = app.surface.settings().active_profile() else { return }; + if page == BASE { p.base.get(&control).cloned() } else { p.page(page).and_then(|q| q.bindings.get(&control).cloned()) } + }; + let name = ls::devices::find_control(&control).map_or(control.clone(), |c| tr(c.label).to_string()); + let page_name = if page == BASE { tr("All pages").to_string() } else { page.to_string() }; + ui.add_space(4.0); + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::hover()); + ui.painter().rect_filled(r, CornerRadius::same(6), Color32::from_gray(26)); + if let Some(icon) = current.as_ref().and_then(ls::icons::icon_for) { + crate::surface_icons::paint(ui, icon, r.shrink(4.0), Color32::WHITE); + } + ui.vertical(|ui| { + ui.label(RichText::new(format!("{name} · {page_name}")).size(11.0).color(t.text_dim)); + let what = current.as_ref().map_or_else(|| tr("Nothing").to_string(), |b| short_label(app, b)); + ui.label(RichText::new(what).font(t.semibold(13.0)).color(t.text)); + }); + }); + ui.horizontal_wrapped(|ui| { + if button_enabled(ui, "surfaceClear", "Clear", current.is_some()) { + set_binding(app, page, &control, None); + } + if let Some(Binding::Value { .. }) = ¤t + && !ls::devices::is_encoder(&control) + { + hint(ui, t, "Press this key to put the value on the dial; press it again to give the dial back."); + } + }); + // a value's own dial feel + if let Some(Binding::Value { target }) = ¤t { + let mut tu = app.surface.settings().tuning_of(target); + let mut c = false; + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(tr("Its speed")).color(t.text_label)); + c |= slider(ui, "surface.valueSpeed", &mut tu.speed, 0.1..=5.0, 2, "×"); + ui.label(RichText::new(tr("Its acceleration")).color(t.text_label)); + c |= slider(ui, "surface.valueAccel", &mut tu.acceleration, 0.1..=4.0, 2, "×"); + }); + if c { + app.surface.runtime.settings_mut().tuning.insert(target.clone(), tu.sanitized()); + app.surface.changed(); + } + } + if let Some(Binding::Command { command, params }) = ¤t { + egui::CollapsingHeader::new(tr("Command parameters (advanced)")).id_salt("surfaceParams").show(ui, |ui| { + if app.surface.editor.params_text.is_empty() { + app.surface.editor.params_text = if params.is_null() { "{}".into() } else { params.to_string() }; + } + crate::text_field::TextField::singleline("field:surfaceParams", &mut app.surface.editor.params_text).width(240.0).show(ui); + match serde_json::from_str::(&app.surface.editor.params_text) { + Ok(v) if v.is_object() || v.is_null() => { + let v = if v.as_object().is_some_and(|o| o.is_empty()) { Value::Null } else { v }; + if v != *params { + set_binding(app, page, &control, Some(Binding::command_with(command, v))); + } + } + _ => hint(ui, t, "Parameters are a JSON object, e.g. {\"rating\": 5}"), + } + }); + } + ui.add_space(4.0); + crate::text_field::TextField::singleline("field:surfaceActionSearch", &mut app.surface.editor.filter) + .hint(tr("Search actions")) + .width(240.0) + .show(ui); + let picked = action_picker(app, ui, t, &control, current.as_ref(), max_h - 120.0); + if let Some(b) = picked { + set_binding(app, page, &control, Some(b)); + app.surface.editor.params_text.clear(); + } +} + +/// Every action in categories, filtered by the search box; the chosen one. +fn action_picker(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, control: &str, current: Option<&Binding>, height: f32) -> Option { + let q = app.surface.editor.filter.trim().to_lowercase(); + let encoder = ls::devices::is_encoder(control); + // (group, label, icon, key, binding) + let mut items: Vec<(String, String, Option<&'static str>, String, Binding)> = Vec::new(); + // keys: what a key does once first, then the values it can put on the dial + let mut order: Vec<&ls::catalog::Entry> = ls::catalog::cached().iter().collect(); + if !encoder { + order.sort_by_key(|e| e.value); + } + for e in order { + // a dial turns values (and pages); keys do anything + if encoder && !e.value && !matches!(e.binding, Binding::PageNext { .. } | Binding::PagePrevious { .. }) { + continue; + } + let label = match &e.binding { + Binding::Command { .. } => short_label(app, &e.binding), + _ => tr(&e.label).to_string(), + }; + items.push((tr(e.group).to_string(), label, e.icon, e.key.clone(), e.binding.clone())); + } + if !encoder && let Some(p) = app.surface.settings().active_profile() { + let g = tr("Pages and Profiles").to_string(); + for pg in p.pages.iter().filter(|p| !p.auto) { + let b = Binding::Page { page: pg.name.clone() }; + items.push(( + g.clone(), + crate::i18n::tr_format!("Show page {name}", name = pg.name.clone()), + Some("toggle-tools"), + ls::catalog::key_of(&b), + b, + )); + } + for pr in &app.surface.settings().profiles { + let b = Binding::Profile { profile: pr.name.clone() }; + items.push(( + g.clone(), + crate::i18n::tr_format!("Switch to profile {name}", name = pr.name.clone()), + Some("toggle-tools"), + ls::catalog::key_of(&b), + b, + )); + } + } + if !encoder { + // every other command of the app, for power users + let g = tr("All commands").to_string(); + let mut all: Vec<(String, String)> = crate::menus::ui_commands().map(|c| (c.0.to_string(), tr(c.1).to_string())).collect(); + all.extend(app.session.commands().into_iter().map(|c| (c.id.to_string(), tr(c.label).to_string()))); + all.sort_by(|a, b| a.1.cmp(&b.1)); + all.dedup_by(|a, b| a.0 == b.0); + for (id, label) in all { + let b = Binding::command(&id); + let key = ls::catalog::key_of(&b); + if ls::catalog::of(&b).is_some() { + continue; + } + items.push((g.clone(), label, None, key, b)); + } + } + let matches = |label: &str, key: &str, group: &str| { + q.is_empty() || label.to_lowercase().contains(&q) || key.to_lowercase().contains(&q) || group.to_lowercase().contains(&q) + }; + let mut groups: Vec = Vec::new(); + for it in &items { + if !groups.contains(&it.0) { + groups.push(it.0.clone()); + } + } + let current_key = current.map(ls::catalog::key_of); + let mut picked = None; + egui::ScrollArea::vertical().id_salt("surfaceActions").max_height(height.max(140.0)).auto_shrink([false, true]).show(ui, |ui| { + let mut shown = 0usize; + for g in &groups { + let rows: Vec<_> = items.iter().filter(|it| &it.0 == g && matches(&it.1, &it.3, &it.0)).collect(); + if rows.is_empty() { + continue; + } + let has_current = rows.iter().any(|it| Some(&it.3) == current_key.as_ref()); + let open = if q.is_empty() { None } else { Some(true) }; + let mut h = egui::CollapsingHeader::new(RichText::new(format!("{g} ({})", rows.len())).color(t.text)) + .id_salt(("surfaceGroup", g.as_str())) + .default_open(has_current); + if let Some(o) = open { + h = h.open(Some(o)); + } + let r = h.show(ui, |ui| { + for (_, label, icon, key, b) in rows.iter().map(|x| (&x.0, &x.1, x.2, &x.3, &x.4)) { + shown += 1; + if shown > 600 { + break; + } + let selected = Some(key) == current_key.as_ref(); + let resp = ui.horizontal(|ui| { + let (ir, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); + if let Some(name) = icon { + crate::surface_icons::paint(ui, name, ir, Color32::WHITE); + } + ui.add(egui::Button::selectable(selected, label.as_str())).interact(Sense::click_and_drag()) + }); + register(ui.ctx(), format!("item:surfaceAction-{key}"), resp.inner.rect); + // drag it onto a key, button or dial of the drawing + resp.inner.dnd_set_drag_payload(DragAction { binding: b.clone(), label: label.clone(), icon }); + if resp.inner.clicked() { + picked = Some(b.clone()); + } + } + }); + register(ui.ctx(), format!("group:surfaceActions-{g}"), r.header_response.rect); + } + if shown == 0 { + hint(ui, t, "No action matches."); + } + }); + picked +} + +// ------------------------------------------------------------------------------------- pages + +fn pages_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + let Some(profile) = app.surface.settings().active_profile().cloned() else { return }; + heading(ui, t, "Pages"); + hint(ui, t, "Keypad pages and dial pages of this profile. A tool page appears by itself while its tool is open (see below)."); + for (i, p) in profile.pages.iter().enumerate() { + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(&p.name).color(t.text)).on_hover_text(tr("Page")); + let mut keys = p.in_group(PageGroup::Keys); + let mut dials = p.in_group(PageGroup::Dials); + let mut auto = p.auto; + let a = check(ui, &format!("surface.pageKeys-{i}"), &mut keys, "Keys"); + let b = check(ui, &format!("surface.pageDials-{i}"), &mut dials, "Dials"); + let c = check(ui, &format!("surface.pageAuto-{i}"), &mut auto, "Tool page"); + if a || b || c { + let name = p.name.clone(); + edit_page(app, &name, |q| { + q.groups = match (keys, dials) { + (true, false) => vec![PageGroup::Keys], + (false, true) => vec![PageGroup::Dials], + _ => Vec::new(), + }; + q.auto = auto; + }); + } + if button(ui, &format!("surfaceRenamePage-{i}"), "Rename") { + let new = app.surface.editor.new_name.trim().to_string(); + let old = p.name.clone(); + if !new.is_empty() && profile.page(&new).is_none() { + edit_profile(app, |pr| { + if let Some(q) = pr.pages.iter_mut().find(|q| q.name == old) { + q.name = new.clone(); + } + for list in pr.contexts.values_mut() { + for n in list.iter_mut().filter(|n| **n == old) { + *n = new.clone(); + } + } + }); + app.surface.editor.new_name.clear(); + } + } + if button(ui, &format!("surfaceDeletePage-{i}"), "Delete") { + let name = p.name.clone(); + edit_profile(app, |pr| pr.pages.retain(|q| q.name != name)); + } + }); + } + ui.horizontal_wrapped(|ui| { + crate::text_field::TextField::singleline("field:surfaceNewName", &mut app.surface.editor.new_name).hint(tr("Name")).width(160.0).show(ui); + if button(ui, "surfaceAddPage", "Add page") { + let name = app.surface.editor.new_name.trim().to_string(); + let name = if name.is_empty() { format!("Page {}", profile.pages.len() + 1) } else { name }; + edit_profile(app, |p| p.pages.push(ls::Page { name: name.clone(), groups: vec![PageGroup::Keys], ..Default::default() })); + app.surface.editor.new_name.clear(); + } + }); + hint(ui, t, "Type a name, then Add page, or Rename on a page."); + contexts(app, ui, t); +} + +fn contexts(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + heading(ui, t, "Pages That Follow the App"); + let mut follow = app.surface.settings().follow_context; + if check(ui, "surface.followContext", &mut follow, "Switch pages with what LightCraft shows (Crop, Masking…)") { + app.surface.runtime.settings_mut().follow_context = follow; + app.surface.changed(); + } + let mut dialogs = app.surface.settings().dialog_pages; + if check(ui, "surface.dialogPages", &mut dialogs, "Dialogs show their own page (OK, Cancel…)") { + app.surface.runtime.settings_mut().dialog_pages = dialogs; + app.surface.changed(); + } + let Some(profile) = app.surface.settings().active_profile().cloned() else { return }; + ui.label( + RichText::new(crate::i18n::tr_format!("Now: {context}", context = tr(ls::context::label(app.surface.runtime.context())).to_string())) + .size(11.0) + .color(t.text_dim), + ); + for (key, label) in ls::context::KNOWN { + let current = profile.contexts.get(*key).and_then(|l| l.first()).cloned(); + row(ui, t, label, |ui| { + let r = egui::ComboBox::from_id_salt(format!("surfaceContext-{key}")) + .selected_text(current.clone().unwrap_or_else(|| "—".into())) + .show_ui(ui, |ui| { + if ui.selectable_label(current.is_none(), "—").clicked() { + let k = key.to_string(); + edit_profile(app, |p| { + p.contexts.remove(&k); + }); + } + for pg in &profile.pages { + if ui.selectable_label(current.as_deref() == Some(&pg.name), &pg.name).clicked() { + let (k, n) = (key.to_string(), pg.name.clone()); + edit_profile(app, |p| { + p.contexts.insert(k, vec![n]); + }); + } + } + }); + register(ui.ctx(), format!("combo:surfaceContext-{key}"), r.response.rect); + }); + } +} + +// ------------------------------------------------------------------------------------- setup + +fn plugin_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + heading(ui, t, "Logi Options+ Plugin"); + hint( + ui, + t, + "The MX Creative Console talks to LightCraft through the LightCraft plugin for Logi Options+. Installing hands the plugin to Logi Options+, which asks you to confirm.", + ); + if app.services.surface_plugin.is_none() { + hint(ui, t, "This LightCraft can't install it: open LightCraft.lplug4 from the LightCraft download to install it in Logi Options+."); + return; + } + let s = app.surface.plugin.status.clone().unwrap_or_default(); + ui.horizontal_wrapped(|ui| { + status(ui, t, s.host.is_some(), if s.host.is_some() { "Logi Options+ found" } else { "Logi Options+ not found" }); + ui.add_space(8.0); + match &s.installed { + Some(v) => status(ui, t, true, &crate::i18n::tr_format!("Plugin {version} installed", version = v.clone())), + None => status(ui, t, false, "Plugin not installed"), + } + ui.add_space(8.0); + status(ui, t, console_connected(app), if console_connected(app) { "Connected" } else { "Not connected" }); + }); + let busy = app.surface.plugin.job.as_ref().map(|j| j.installing); + ui.horizontal_wrapped(|ui| { + let label = if s.update_available() { + "Update the plugin" + } else if s.installed.is_some() { + "Reinstall the plugin" + } else { + "Install the plugin" + }; + if button_enabled(ui, "surfaceInstallPlugin", label, busy.is_none() && s.can_install()) + && let Err(e) = crate::surface_plugin::start(app, true) + { + app.surface.plugin.message = Some(Err(e)); + } + if button_enabled(ui, "surfaceUninstallPlugin", "Remove the plugin", busy.is_none() && s.installed.is_some() && s.package.is_some()) + && let Err(e) = crate::surface_plugin::start(app, false) + { + app.surface.plugin.message = Some(Err(e)); + } + match busy { + Some(true) => hint(ui, t, "Installing…"), + Some(false) => hint(ui, t, "Removing…"), + None => {} + } + }); + if s.package.is_none() && s.host.is_some() { + hint( + ui, + t, + "No plugin package came with this LightCraft (LightCraft.lplug4 next to the program). Developers: build it with the plugin's scripts/package.ps1 and point LIGHTCRAFT_LOGI_PLUGIN at it.", + ); + } + match &app.surface.plugin.message { + Some(Ok(m)) => { + ui.label(RichText::new(tr(m)).color(t.text_label)); + } + Some(Err(e)) => { + ui.label(RichText::new(e.clone()).color(warn_color())); + } + None => {} + } +} + +fn connection(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + heading(ui, t, "Connection"); + row(ui, t, "Port", |ui| { + let mut port = u32::from(app.surface.settings().port); + let r = ui.add(egui::DragValue::new(&mut port).range(1024..=65535)); + register(ui.ctx(), "drag:surfacePort", r.rect); + if r.changed() { + app.surface.runtime.settings_mut().port = u16::try_from(port).unwrap_or(ls::settings::DEFAULT_PORT); + app.surface.changed(); + } + match (app.surface.listening, &app.surface.listen_error) { + (Some(p), _) => { + ui.label(RichText::new(crate::i18n::tr_format!("Listening on 127.0.0.1:{port}", port = p)).size(11.0).color(t.text_dim)); + } + (None, Some(e)) => { + ui.label(RichText::new(e.clone()).size(11.0).color(warn_color())); + } + _ => {} + } + }); + if let Some(e) = app.surface.load_error.clone().or(app.surface.save_error.clone()) { + ui.label(RichText::new(e).color(warn_color())); + } + let connected = app.surface.connected(); + if connected.is_empty() { + hint(ui, t, "No surface is connected."); + } else { + for (client, device) in connected { + ui.horizontal(|ui| status(ui, t, true, &format!("{client} — {device}"))); + } + } + let paired: Vec<(String, String)> = app.surface.settings().paired.iter().map(|c| (c.client.clone(), c.name.clone())).collect(); + for (client, name) in paired { + ui.horizontal(|ui| { + ui.label(RichText::new(crate::i18n::tr_format!("Paired: {name}", name = name)).color(t.text_label)); + if button(ui, &format!("surfaceForget-{client}"), "Forget") { + app.surface.unpair(&client); + } + }); + } +} + +fn profiles(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + heading(ui, t, "Profiles"); + let names: Vec = app.surface.settings().profiles.iter().map(|p| p.name.clone()).collect(); + if let Some(desc) = app.surface.settings().active_profile().map(|p| p.description.clone()).filter(|d| !d.is_empty()) { + hint(ui, t, &desc); + } + ui.horizontal_wrapped(|ui| { + crate::text_field::TextField::singleline("field:surfaceProfileName", &mut app.surface.editor.new_name).hint(tr("Name")).width(160.0).show(ui); + if button(ui, "surfaceDuplicate", "Duplicate") { + let name = app.surface.editor.new_name.trim().to_string(); + let s = app.surface.runtime.settings_mut(); + if let Some(mut p) = s.active_profile().cloned() { + p.name = if name.is_empty() { format!("{} copy", p.name) } else { name }; + p.description.clear(); + s.profile = p.name.clone(); + s.profiles.push(p); + app.surface.editor.new_name.clear(); + app.surface.changed(); + } + } + if button(ui, "surfaceRename", "Rename") { + let name = app.surface.editor.new_name.trim().to_string(); + if !name.is_empty() && !names.contains(&name) { + let s = app.surface.runtime.settings_mut(); + let cur = s.profile.clone(); + if let Some(p) = s.profiles.iter_mut().find(|p| p.name == cur) { + p.name = name.clone(); + } + s.profile = name; + app.surface.editor.new_name.clear(); + app.surface.changed(); + } + } + if names.len() > 1 && button(ui, "surfaceDeleteProfile", "Delete") { + let s = app.surface.runtime.settings_mut(); + let cur = s.profile.clone(); + s.profiles.retain(|p| p.name != cur); + app.surface.changed(); + } + if button(ui, "surfaceRestore", "Add the built-in profiles") { + let s = app.surface.runtime.settings_mut(); + for p in ls::defaults::profiles() { + if !s.profiles.iter().any(|q| q.name == p.name) { + s.profiles.push(p); + } + } + app.surface.changed(); + } + }); + ui.horizontal_wrapped(|ui| { + if let Some(path) = crate::surface::tactilebridge_settings_path() + && button(ui, "surfaceImportTb", "Bring over my TactileBridge setup") + { + let r = app_run_import(app, &path.to_string_lossy()); + report(app, r); + } + if app.services.pick_surface_file.is_some() && button(ui, "surfaceImport", "Import…") { + let files = app.services.pick_surface_file.as_mut().map(|f| f()).unwrap_or_default(); + for f in files { + let r = app_run_import(app, &f); + report(app, r); + } + } + if app.services.save_surface_file.is_some() && button(ui, "surfaceExport", "Export…") { + let name = format!("{}.lcsurface", app.surface.settings().profile); + if let Some(path) = app.services.save_surface_file.as_mut().and_then(|f| f(&name)) { + let r = app.run("surface.export", json!({"path": path})); + app.surface.editor.message = Some(match r { + Ok(_) => crate::i18n::tr_format!("Saved {path}", path = path), + Err(e) => e, + }); + } + } + }); + hint( + ui, + t, + "Import takes a TactileBridge settings.json (dial feel, readout, colours, tool layouts), a Logi profile (.lp5) or a LightCraft layout file (.lcsurface).", + ); + if let Some(m) = app.surface.editor.message.clone() { + ui.label(RichText::new(m).color(t.text_label)); + } + if let Some(r) = app.surface.last_report.clone() { + egui::CollapsingHeader::new(crate::i18n::tr_format!( + "Last import: {mapped} brought over, {dropped} left out", + mapped = r.mapped.len(), + dropped = r.dropped.len() + )) + .id_salt("surfaceReport") + .show(ui, |ui| { + for l in r.dropped.iter().take(200) { + ui.label(RichText::new(format!("✕ {} — {}", l.from, l.note)).size(11.0).color(t.text_dim)); + } + for l in r.mapped.iter().take(400) { + let note = if l.note.is_empty() { String::new() } else { format!(" ({})", l.note) }; + ui.label(RichText::new(format!("✓ {} → {}{note}", l.from, l.to)).size(11.0).color(t.text_dim)); + } + }); + } +} + +fn app_run_import(app: &mut LightcraftApp, path: &str) -> Result { + app.run("surface.import", json!({"path": path})) +} + +fn report(app: &mut LightcraftApp, r: Result) { + app.surface.editor.page = None; + app.surface.editor.control = None; + app.surface.editor.message = Some(match r { + Ok(v) => crate::i18n::tr_format!("Imported into the profile “{name}”", name = v["profile"].as_str().unwrap_or_default().to_string()), + Err(e) => e, + }); +} + +// ------------------------------------------------------------------------------------- feel + +fn feel(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + heading(ui, t, "Dial Feel"); + let mut m = app.surface.settings().motion.clone(); + let mut changed = false; + row(ui, t, "Speed", |ui| changed |= slider(ui, "surface.speed", &mut m.speed, 0.1..=5.0, 2, "×")); + row(ui, t, "Acceleration", |ui| changed |= slider(ui, "surface.acceleration", &mut m.acceleration, 0.1..=4.0, 2, "×")); + row(ui, t, "Fine steps", |ui| changed |= slider(ui, "surface.fine", &mut m.fine, 0.01..=1.0, 2, "×")); + row(ui, t, "Big steps", |ui| changed |= slider(ui, "surface.coarse", &mut m.coarse, 1.0..=20.0, 1, "×")); + changed |= check(ui, "surface.invert", &mut m.invert, "Turn every dial the other way"); + if changed { + app.surface.runtime.settings_mut().motion = m; + app.surface.changed(); + } + heading(ui, t, "One Value"); + let target = app.surface.editor.tuning_target.clone(); + let label = ls::targets::target_spec(&target).map_or(target.clone(), |s| tr(s.label).to_string()); + row(ui, t, "Value", |ui| { + let r = egui::ComboBox::from_id_salt("surfaceTuningTarget").selected_text(label).show_ui(ui, |ui| { + for s in ls::targets::all_targets() { + if ui.selectable_label(s.id == target, format!("{} — {}", tr(s.group), tr(s.label))).clicked() { + app.surface.editor.tuning_target = s.id.clone(); + } + } + }); + register(ui.ctx(), "combo:surfaceTuningTarget", r.response.rect); + }); + let mut tu = app.surface.settings().tuning_of(&target); + let mut c = false; + row(ui, t, "Its speed", |ui| c |= slider(ui, "surface.tuneSpeed", &mut tu.speed, 0.1..=5.0, 2, "×")); + row(ui, t, "Its acceleration", |ui| c |= slider(ui, "surface.tuneAccel", &mut tu.acceleration, 0.1..=4.0, 2, "×")); + row(ui, t, "Slow turning", |ui| c |= slider(ui, "surface.tuneMin", &mut tu.acceleration_min, 0.1..=10.0, 1, "×")); + row(ui, t, "Fast turning", |ui| c |= slider(ui, "surface.tuneMax", &mut tu.acceleration_max, 0.1..=15.0, 1, "×")); + row(ui, t, "Fast below", |ui| c |= slider_u32(ui, "surface.tuneFast", &mut tu.fast_ms, 5..=250, " ms")); + row(ui, t, "Slow above", |ui| c |= slider_u32(ui, "surface.tuneSlow", &mut tu.slow_ms, 20..=1200, " ms")); + c |= check(ui, "surface.tuneInvert", &mut tu.invert, "Turn this value the other way"); + if c { + app.surface.runtime.settings_mut().tuning.insert(target.clone(), tu.sanitized()); + app.surface.changed(); + } + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(tr("Presets for every value:")).color(t.text_label)); + for (name, desc, tuning) in ls::settings::tuning_presets() { + let r = ui.button(tr(name)).on_hover_text(tr(desc)); + register(ui.ctx(), format!("button:surfacePreset-{name}"), r.rect); + if r.clicked() { + let s = app.surface.runtime.settings_mut(); + for spec in ls::targets::all_targets() { + s.tuning.insert(spec.id, tuning.clone()); + } + app.surface.changed(); + } + } + if button(ui, "surfaceTuningReset", "Reset all") { + app.surface.runtime.settings_mut().tuning.clear(); + app.surface.changed(); + } + }); + hint(ui, t, "A preset overwrites the tuning of every value."); +} + +// ------------------------------------------------------------------------------------- readout + +fn timing_and_readout(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + let mut s = app.surface.settings().clone(); + let before = s.clone(); + heading(ui, t, "Editing"); + check(ui, "surface.applyToSelected", &mut s.apply_to_selected, "Dials change every selected photo (one undo step per turn)"); + row(ui, t, "Turn ends after", |ui| { + slider_u32(ui, "surface.gestureEnd", &mut s.transport.gesture_end_ms, 200..=10_000, " ms"); + }); + row(ui, t, "Apply movement every", |ui| { + slider_u32(ui, "surface.flush", &mut s.transport.flush_ms, 8..=100, " ms"); + }); + check(ui, "surface.echo", &mut s.transport.echo_suppression, "Keep the surface's readout steady while turning"); + heading(ui, t, "On-Screen Readout"); + check(ui, "surface.osd", &mut s.osd.enabled, "Show the value or command in the window"); + check(ui, "surface.osdCommands", &mut s.osd.show_commands, "Also for key presses"); + row(ui, t, "Opacity", |ui| { + slider(ui, "surface.osdOpacity", &mut s.osd.opacity, 0.1..=1.0, 2, ""); + }); + row(ui, t, "Shown for", |ui| { + slider_u32(ui, "surface.osdTime", &mut s.osd.display_ms, 500..=10_000, " ms"); + }); + row(ui, t, "Position", |ui| { + choices( + ui, + "surfaceOsdPosition", + &[ + (OsdPosition::TopEdge, "Top edge"), + (OsdPosition::Top, "Top"), + (OsdPosition::Bottom, "Bottom"), + (OsdPosition::BottomEdge, "Bottom edge"), + ], + &mut s.osd.position, + ); + }); + row(ui, t, "Background", |ui| { + crate::text_field::TextField::singleline("field:surfaceOsdColor", &mut s.osd.background).width(90.0).show(ui); + }); + heading(ui, t, "Keys"); + check(ui, "surface.showValues", &mut s.look.show_values, "Show values on the keys and the dial display"); + check(ui, "surface.haptics", &mut s.look.haptics, "Haptic feedback (where the device has it)"); + row(ui, t, "Key background", |ui| { + crate::text_field::TextField::singleline("field:surfaceBackground", &mut s.look.background).width(90.0).show(ui); + }); + row(ui, t, "Key text", |ui| { + crate::text_field::TextField::singleline("field:surfaceForeground", &mut s.look.foreground).width(90.0).show(ui); + }); + hint(ui, t, "Colours are #RRGGBB."); + if s != before { + // colours apply once they are whole (#RRGGBB) + let colours_ok = [&s.osd.background, &s.look.background, &s.look.foreground].iter().all(|c| ls::settings::rgb(c).is_some()); + let only_colours_changed = { + let mut a = s.clone(); + a.osd.background = before.osd.background.clone(); + a.look.background = before.look.background.clone(); + a.look.foreground = before.look.foreground.clone(); + a == before + }; + if colours_ok || !only_colours_changed { + if !colours_ok { + s.osd.background = before.osd.background; + s.look.background = before.look.background; + s.look.foreground = before.look.foreground; + } + *app.surface.runtime.settings_mut() = s; + app.surface.changed(); + } else { + // keep the half-typed colour in the field without applying it + let rt = app.surface.runtime.settings_mut(); + rt.osd.background = s.osd.background; + rt.look.background = s.look.background; + rt.look.foreground = s.look.foreground; + } + } +} diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index a07aee8b2c3..9ada1817965 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -4,6 +4,7 @@ pub mod activity; pub mod bottombar; pub mod chips; pub mod compare; +pub mod controls; pub mod crop_overlay; pub mod denoise; pub mod detail; @@ -38,6 +39,7 @@ pub mod slide_templates; pub mod slide_titles; pub mod slideshow; pub mod strip; +pub mod surface_osd; pub mod topbar; pub mod unnamed; diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index d93aa06884d..74fedcc1459 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -1,5 +1,5 @@ //! The Settings dialog (⌘,): General, Import, Performance, Display, Interface, Slideshow, Faces, -//! AI Denoise. +//! AI Denoise, Controls (control surfaces, `panels::controls`). //! //! Changes apply immediately (no OK/Cancel). Where they are stored: //! - **app settings** ([`crate::state::AppSettings`]: startup view, delete confirmation, GPU, @@ -30,6 +30,7 @@ pub const TABS: &[(&str, &str)] = &[ ("slideshow", "Slideshow"), ("faces", "Faces"), ("denoise", "AI Denoise"), + ("controls", "Controls"), ]; /// Thumbnail cache sizes offered (MB). @@ -48,6 +49,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, tab: &str) { "slideshow" => slideshow_tab(app, ui, &t, true), "faces" => super::faces::settings_tab(app, ui, &t), "denoise" => super::denoise::settings_tab(app, ui, &t), + "controls" => super::controls::settings_tab(app, ui, &t), _ => general_tab(app, ui, &t), } } diff --git a/crates/ui-egui/src/panels/surface_osd.rs b/crates/ui-egui/src/panels/surface_osd.rs new file mode 100644 index 00000000000..f2ad764cd1b --- /dev/null +++ b/crates/ui-egui/src/panels/surface_osd.rs @@ -0,0 +1,113 @@ +//! The on-screen readout of control surfaces: a pill in the window showing the value a dial is +//! turning (name, value and a bar), the command a key ran, or a surface notice (page, profile). +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT: TactileBridge's OSD overlay +//! (`OsdOverlay.cs`): its pill shape, layout, positions, opacity, colour and fade. + +use egui::{Align2, Color32, Rect, pos2, vec2}; +use lightcraft_surface as ls; +use ls::runtime::Shown; +use ls::settings::OsdPosition; + +use crate::LightcraftApp; +use crate::theme::Tokens; + +/// The pill's size (points), as TactileBridge's. +const WIDTH: f32 = 320.0; +const HEIGHT: f32 = 72.0; +/// The fade after the display time (s). +const FADE: f64 = 0.4; + +/// What the readout says: (title, value text, bar 0…1, age in s, icon). +pub fn content(app: &LightcraftApp) -> Option<(String, String, Option, f64, Option<&'static str>)> { + let now_ms = app.surface.now() * 1000.0; + let (shown, at) = app.surface.runtime.shown(now_ms)?; + let (title, value, bar, icon) = match shown { + Shown::Value { target } => { + let spec = ls::targets::target_spec(target)?; + let v = crate::surface::value(app, target); + let title = crate::i18n::tr(spec.label).to_string(); + let title = if spec.kind == ls::TargetKind::Mask { format!("{} · {}", crate::i18n::tr("Mask"), title) } else { title }; + let icon = ls::icons::icon_for(&ls::Binding::value(target)); + (title, v.map(|v| spec.format(v)).unwrap_or_else(|| "—".into()), v.map(|v| spec.position(v)), icon) + } + // a command without a short label of its own names itself by id: show its registry label + Shown::Command { label, icon } => { + let text = if !label.contains(' ') && label.contains('.') { + crate::surface::registry_label(app, label).unwrap_or_else(|| label.clone()) + } else { + crate::i18n::tr(label).to_string() + }; + (text, String::new(), None, *icon) + } + Shown::Notice { text } => (notice_text(text), String::new(), None, None), + }; + Some((title, value, bar, (now_ms - at) / 1000.0, icon)) +} + +/// Notices come in English from the engine ("Dial: Exposure", "Apply to all selected: On"): +/// translate their parts. +fn notice_text(text: &str) -> String { + match text.split_once(": ") { + Some((head, tail)) => { + let tail = match tail { + "On" | "Off" | "page" => crate::i18n::tr(tail).to_string(), + t => ls::targets::all_targets() + .into_iter() + .find(|s| s.label == t) + .map_or_else(|| t.to_string(), |s| crate::i18n::tr(s.label).to_string()), + }; + format!("{}: {tail}", crate::i18n::tr(head)) + } + None => crate::i18n::tr(text).to_string(), + } +} + +pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { + let Some((title, value, bar, age, icon)) = content(app) else { return }; + let osd = &app.surface.settings().osd; + let display = f64::from(osd.display_ms) / 1000.0; + let fade = if age <= display { 1.0 } else { (1.0 - (age - display) / FADE).clamp(0.0, 1.0) } as f32; + if fade <= 0.0 { + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(30)); + let area = app.canvas_rect.unwrap_or_else(|| ctx.content_rect()); + let center_x = area.center().x; + let y = match osd.position { + OsdPosition::TopEdge => area.top() + 20.0 + HEIGHT / 2.0, + OsdPosition::Top => area.top() + 80.0 + HEIGHT / 2.0, + OsdPosition::BottomEdge => area.bottom() - 20.0 - HEIGHT / 2.0, + OsdPosition::Bottom => area.bottom() - 80.0 - HEIGHT / 2.0, + }; + let opacity = osd.opacity.clamp(0.1, 1.0) as f32 * fade; + let (r, g, b) = ls::settings::rgb(&osd.background).unwrap_or((32, 32, 32)); + let t = Tokens::get(ctx); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("surface_osd"))); + let width = WIDTH.min(area.width() - 16.0).max(160.0); + let rect = Rect::from_center_size(pos2(center_x, y), vec2(width, HEIGHT)); + painter.rect_filled(rect, HEIGHT / 2.0, Color32::from_rgb(r, g, b).gamma_multiply(opacity)); + painter.rect_stroke(rect, HEIGHT / 2.0, egui::Stroke::new(1.0, Color32::from_white_alpha(40).gamma_multiply(fade)), egui::StrokeKind::Inside); + crate::widgets::register(ctx, "osd:surface", rect); + let title_c = Color32::from_rgb(220, 220, 220).gamma_multiply(fade); + let value_c = Color32::WHITE.gamma_multiply(fade); + // the action's icon (the same one the surface's key shows) at the left of the pill + let icon_rect = Rect::from_center_size(pos2(rect.left() + 40.0, rect.center().y), vec2(40.0, 40.0)); + let has_icon = icon.is_some_and(|name| crate::surface_icons::paint_with(ctx, &painter, name, icon_rect, Color32::WHITE.gamma_multiply(fade))); + let left = if has_icon { rect.left() + 70.0 } else { rect.left() + 30.0 }; + let right = rect.right() - 30.0; + if value.is_empty() { + let center = if has_icon { pos2((left + right) / 2.0, rect.center().y) } else { rect.center() }; + painter.text(center, Align2::CENTER_CENTER, &title, t.semibold(17.0), value_c); + return; + } + let text_y = rect.top() + 26.0; + painter.text(pos2(left, text_y), Align2::LEFT_CENTER, &title, t.font(14.0), title_c); + painter.text(pos2(right, text_y), Align2::RIGHT_CENTER, &value, t.semibold(18.0), value_c); + if let Some(p) = bar { + let track = Rect::from_min_max(pos2(left, rect.top() + 46.0), pos2(right, rect.top() + 50.0)); + painter.rect_filled(track, 2.0, Color32::from_white_alpha(80).gamma_multiply(fade)); + let fill = Rect::from_min_max(track.min, pos2(track.left() + track.width() * p.clamp(0.0, 1.0) as f32, track.bottom())); + painter.rect_filled(fill, 2.0, Color32::from_rgb(100, 180, 255).gamma_multiply(fade)); + } +} diff --git a/crates/ui-egui/src/surface.rs b/crates/ui-egui/src/surface.rs new file mode 100644 index 00000000000..5c99ec6e134 --- /dev/null +++ b/crates/ui-egui/src/surface.rs @@ -0,0 +1,1207 @@ +//! Control surfaces in the app: the [`lightcraft_surface`] engine wired to the session, the +//! `surface.*` control-channel methods (pairing, subscribe, input, layout, icons), the pushes to +//! subscribed surfaces and the `surface.*` UI commands. The protocol is documented in +//! `docs/control-surfaces.md`; the editor is Settings ▸ Controls (`panels::controls`); the +//! on-screen readout is `panels::surface_osd`. +//! +//! Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::Sender; + +use lightcraft_catalog::PhotoId; +use lightcraft_surface as ls; +use ls::layout::Host; +use ls::{Binding, Effect, TargetKind}; +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use crate::control::{ControlRequest, Outcome}; +use crate::state::{BeforeAfter, RightPanel, ViewMode, Zoom}; + +/// Where a connection's pushed events go, and whether it is still open (the transport clears +/// `open` when the peer goes away). +#[derive(Clone)] +pub struct EventSink { + pub tx: Sender, + pub open: Arc, +} + +impl EventSink { + fn is_open(&self) -> bool { + self.open.load(Ordering::SeqCst) + } +} + +/// Load and save `control-surfaces.json` (the desktop host stores it in the settings folder). +pub trait SurfaceStore { + /// The saved text, `None` when there is none yet. + fn load(&self) -> Result, String>; + fn save(&self, text: &str) -> Result<(), String>; +} + +struct Subscriber { + conn: u64, + client: String, + device: &'static ls::DeviceDef, + sink: EventSink, + last: Option, + /// Values the surface shows outside its layout (actions from its own app, `surface.watch`). + watch: Vec, +} + +/// The most values one surface may watch. +pub const MAX_WATCH: usize = 128; + +/// The editor's selection (Settings ▸ Controls). +#[derive(Clone, Debug, Default)] +pub struct EditorState { + /// The page being edited (`None` = the profile's base bindings). + pub page: Option, + /// The control being edited. + pub control: Option, + /// The value whose tuning is shown. + pub tuning_target: String, + /// Filter text for the value and command lists. + pub filter: String, + /// A message from the last import / export. + pub message: Option, + /// The JSON of the selected command binding's parameters, as typed. + pub params_text: String, + /// Name typed for a new profile or page. + pub new_name: String, + /// The surface shown (`keypad`, `dialpad`, `ring`…; empty: the first). + pub device: String, + /// The part of the page shown (`pages`, `feel`, `readout`, `setup`; empty: pages). + pub section: String, + /// The Keys and Dials window is open (the drawn device and its editor: + /// `panels::controls::editor_window`). + pub window: bool, + /// Touch to find switched off (it is on by default: while Settings ▸ Controls is open, a + /// control touched on the device is selected in the editor and does nothing to the photo). + pub touch_find_off: bool, + /// Touch to find is listening, and when Settings ▸ Controls was last drawn (egui time, s): + /// it stops by itself once the page is gone. + pub touch_find: Option, +} + +/// How long after Settings ▸ Controls was last drawn Touch to find stops listening (s). +const TOUCH_FIND_GRACE: f64 = 0.4; + +pub struct SurfaceHost { + pub runtime: ls::Runtime, + pub pairing: ls::protocol::Pairing, + /// Connection → the paired client it authenticated as. + authed: BTreeMap, + subscribers: Vec, + last_photo: Option, + /// The photo a gesture's undo step was opened on, and its label. + gesture: Option<(PhotoId, String)>, + /// Settings changed and not yet saved, since (egui time, s). + dirty_since: Option, + loaded: bool, + /// Why the settings file couldn't be read (shown in Settings ▸ Controls; the file is kept). + pub load_error: Option, + /// Why saving failed last. + pub save_error: Option, + pub editor: EditorState, + /// The last TactileBridge import, for the report in Settings ▸ Controls. + pub last_report: Option, + /// Points → physical pixels last frame (zoom percent of a fitted photo). + pixels_per_point: f32, + /// egui time of the last tick (s). + now: f64, + /// The port the surface listener runs on. + pub listening: Option, + /// Why it couldn't start, and when to try again (egui time, s). + pub listen_error: Option, + listen_retry_at: f64, + /// The surface plugin's install state (Settings ▸ Controls). + pub plugin: crate::surface_plugin::PluginState, +} + +impl Default for SurfaceHost { + fn default() -> Self { + SurfaceHost { + runtime: ls::Runtime::new(ls::SurfaceSettings::default()), + pairing: ls::protocol::Pairing::new(&seed()), + authed: BTreeMap::new(), + subscribers: Vec::new(), + last_photo: None, + gesture: None, + dirty_since: None, + loaded: false, + load_error: None, + save_error: None, + editor: EditorState { tuning_target: "light.exposure".into(), ..Default::default() }, + last_report: None, + pixels_per_point: 1.0, + now: 0.0, + listening: None, + listen_error: None, + listen_retry_at: 0.0, + plugin: Default::default(), + } + } +} + +/// Unpredictable bytes for pairing codes and tokens (std's per-process random hash keys, the +/// time and the process id; no extra dependency). +fn seed() -> Vec { + use std::hash::{BuildHasher, Hasher}; + let mut out = Vec::new(); + for i in 0..8u64 { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u64(i); + h.write_u128(web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); + out.extend_from_slice(&h.finish().to_le_bytes()); + } + out.extend_from_slice(&std::process::id().to_le_bytes()); + out +} + +impl SurfaceHost { + pub fn settings(&self) -> &ls::SurfaceSettings { + self.runtime.settings() + } + + /// A dial (or other surface control) is adjusting the photo right now: its gesture's undo + /// step is open. The canvas hides overlays and tool graphics meanwhile. + pub fn adjusting(&self) -> bool { + self.gesture.is_some() + } + + /// The app clock at the last frame (egui time, s). + pub fn now(&self) -> f64 { + self.now + } + + /// Settings were changed (editor, keys): apply and save soon. + pub fn changed(&mut self) { + self.runtime.settings_changed(); + self.dirty_since.get_or_insert(self.now); + } + + /// Surfaces subscribed right now: (client, device name). + pub fn connected(&self) -> Vec<(String, &'static str)> { + self.subscribers.iter().filter(|s| s.sink.is_open()).map(|s| (s.client.clone(), s.device.name)).collect() + } + + /// Forget a paired client (Settings ▸ Controls): its token stops working, its connections + /// are told and dropped. + pub fn unpair(&mut self, client: &str) { + self.runtime.settings_mut().paired.retain(|c| c.client != client); + let gone: Vec = self.authed.iter().filter(|(_, c)| *c == client).map(|(k, _)| *k).collect(); + for conn in gone { + self.authed.remove(&conn); + } + for s in self.subscribers.iter().filter(|s| s.client == client) { + let _ = s.sink.tx.send(json!({"event": "surface.unpaired"})); + } + self.subscribers.retain(|s| s.client != client); + self.changed(); + } +} + +// ------------------------------------------------------------------------------------- values + +/// Current value of a target (no active photo, no selected mask: none). +pub fn value(app: &LightcraftApp, target: &str) -> Option { + let spec = ls::targets::target_spec(target)?; + match spec.kind { + TargetKind::Develop => { + let d = app.session.develop_of(app.session.active()?)?; + lightcraft_develop::controls::get(&d, target) + } + TargetKind::Mask => { + let field = ls::targets::mask_field(target)?; + let d = app.session.develop_of(app.session.active()?)?; + let id = app.session.active_mask?; + let m = d.masks.iter().find(|m| m.id == id)?; + serde_json::to_value(m.adjust).ok()?.get(field)?.as_f64() + } + TargetKind::Ui => Some(match target { + "ui.brushSize" => f64::from(app.ui.brush_size) * 400.0, + "ui.brushFeather" => f64::from(app.ui.brush_feather), + "ui.brushFlow" => f64::from(app.ui.brush_flow), + "ui.removeSize" => f64::from(app.ui.remove_size) * 1000.0, + "ui.removeFeather" => f64::from(app.ui.remove_feather), + "ui.removeOpacity" => f64::from(app.ui.remove_opacity), + "ui.zoom" => zoom_percent(app), + _ => return None, + }), + } +} + +/// The loupe's zoom in percent (a fitted photo: what fitting gives). +fn zoom_percent(app: &LightcraftApp) -> f64 { + match app.ui.zoom { + Zoom::Percent(p) if p.is_finite() => f64::from(p), + _ => { + let w = app.session.active().and_then(|id| app.session.catalog.photo(id)).map(|p| p.width.max(1) as f64); + match (app.image_rect, w) { + (Some(r), Some(w)) => (f64::from(r.width()) * f64::from(app.surface.pixels_per_point) / w * 100.0).clamp(5.0, 800.0), + _ => 100.0, + } + } + } +} + +fn set_ui_value(app: &mut LightcraftApp, target: &str, v: f64) { + let Some(spec) = ls::targets::target_spec(target) else { return }; + let v = spec.clamp(v) as f32; + match target { + "ui.brushSize" => app.ui.brush_size = (v / 400.0).clamp(0.002, 0.5), + "ui.brushFeather" => app.ui.brush_feather = v, + "ui.brushFlow" => app.ui.brush_flow = v, + "ui.removeSize" => { + app.ui.remove_size = (v / 1000.0).clamp(0.001, 0.25); + if app.session.active_spot.is_some() { + let _ = app.run("spot.update", json!({"size": app.ui.remove_size})); + } + } + "ui.removeFeather" => app.ui.remove_feather = v, + "ui.removeOpacity" => app.ui.remove_opacity = v, + "ui.zoom" => { + let _ = app.run("view.navigate", json!({"zoom": {"percent": v}})); + } + _ => {} + } +} + +// ------------------------------------------------------------------------------------- effects + +fn label_of(target: &str) -> String { + ls::targets::target_spec(target).map_or_else(|| target.to_string(), |s| s.label.to_string()) +} + +/// Is the session's open interaction the one our gesture opened? +fn ours(app: &LightcraftApp) -> bool { + match (&app.surface.gesture, &app.session.interaction) { + (Some((photo, label)), Some(i)) => i.photo == *photo && i.label == *label, + _ => false, + } +} + +fn begin(app: &mut LightcraftApp, target: &str) { + let Some(spec) = ls::targets::target_spec(target) else { return }; + if spec.kind == TargetKind::Ui { + return; + } + let Some(photo) = app.session.active() else { return }; + let label = label_of(target); + if app.run("develop.beginInteraction", json!({"label": label})).is_ok() { + app.surface.gesture = Some((photo, label)); + } +} + +fn end(app: &mut LightcraftApp, apply_to_selected: bool) { + if ours(app) { + // Apply to Selected: the end of the gesture carries the change to every selected photo, + // in the same undo step (the session's Auto Sync does exactly that) + let before = app.session.auto_sync; + if apply_to_selected { + app.session.auto_sync = true; + } + let _ = app.run("develop.endInteraction", json!({})); + app.session.auto_sync = before; + } + app.surface.gesture = None; +} + +fn adjust(app: &mut LightcraftApp, target: &str, delta: f64) { + let Some(spec) = ls::targets::target_spec(target) else { return }; + if !delta.is_finite() { + return; + } + if spec.kind != TargetKind::Ui && !ours(app) { + // something else took over the edit (a mouse drag, a photo change): a new undo step + begin(app, target); + } + match spec.kind { + TargetKind::Develop => { + let _ = app.run("develop.adjust", json!({"control": target, "delta": delta})); + } + TargetKind::Mask => { + let (Some(field), Some(v)) = (ls::targets::mask_field(target), value(app, target)) else { return }; + let _ = app.run("mask.adjust", json!({"values": {field: spec.clamp(v + delta)}})); + } + TargetKind::Ui => { + let v = value(app, target).unwrap_or(spec.default); + set_ui_value(app, target, v + delta); + } + } +} + +fn reset(app: &mut LightcraftApp, target: &str) { + let Some(spec) = ls::targets::target_spec(target) else { return }; + match spec.kind { + TargetKind::Develop => { + let _ = app.run("develop.resetControl", json!({"control": target})); + } + TargetKind::Mask => { + if let Some(field) = ls::targets::mask_field(target) { + let _ = app.run("mask.adjust", json!({"values": {field: spec.default}})); + } + } + TargetKind::Ui => set_ui_value(app, target, spec.default), + } +} + +/// Run the engine's effects. +pub fn run_effects(app: &mut LightcraftApp, effects: Vec) { + for e in effects { + match e { + Effect::Command { command, params } => { + let params = if params.is_null() { json!({}) } else { params }; + if let Err(err) = app.run(&command, params) { + log::info!("surface: {command}: {err}"); + } + } + Effect::Begin { target } => begin(app, &target), + Effect::Adjust { target, delta } => adjust(app, &target, delta), + Effect::End { apply_to_selected, .. } => end(app, apply_to_selected), + Effect::Reset { target } => reset(app, &target), + Effect::Changed { .. } => {} + Effect::Save => { + let now = app.surface.now; + app.surface.dirty_since.get_or_insert(now); + } + } + } +} + +// ------------------------------------------------------------------------------------- context + +/// The context key of what the app shows. +pub fn context_key(app: &LightcraftApp) -> String { + // Dialogs get their own page only when the user asked for it; Settings ▸ Controls never: the + // keys show the page being edited there. + let controls_open = matches!(&app.ui.dialog, Some(crate::state::Dialog::Settings { tab }) if tab == "controls" || app.surface.editor.window); + let dialog = if controls_open || !app.surface.settings().dialog_pages { + None + } else { + app.ui.dialog.as_ref().and_then(|d| serde_json::to_value(d).ok()).and_then(|v| v.get("kind").and_then(Value::as_str).map(str::to_string)) + }; + let library = + matches!(app.ui.view, ViewMode::PhotoGrid | ViewMode::SquareGrid | ViewMode::Survey | ViewMode::People) || app.session.active().is_none(); + let panel = match app.ui.right { + RightPanel::Edit | RightPanel::Profiles => Some("edit"), + RightPanel::Crop => Some("crop"), + RightPanel::Remove => Some("remove"), + RightPanel::Masking => Some("masking"), + RightPanel::RedEye => Some("redeye"), + _ => None, + }; + let section = app.ui.open_sections.last().map(String::as_str); + let tool = match app.ui.tool.as_str() { + "" => None, + t => Some(t), + }; + ls::context::context_key(&ls::context::AppState { + dialog: dialog.as_deref(), + library, + panel, + section, + mask_selected: app.session.active_mask.is_some(), + tool, + }) +} + +/// A command's own label from the registry (UI commands, then engine commands), translated. +pub fn registry_label(app: &LightcraftApp, command: &str) -> Option { + crate::menus::ui_commands() + .find(|c| c.0 == command) + .map(|c| c.1.to_string()) + .or_else(|| app.session.commands().into_iter().find(|c| c.id == command).map(|c| c.label.to_string())) + .map(|l| crate::i18n::tr(&l).to_string()) +} + +// ------------------------------------------------------------------------------------- layout + +struct AppHost<'a>(&'a LightcraftApp); + +impl Host for AppHost<'_> { + fn value(&self, target: &str) -> Option { + value(self.0, target) + } + + fn label(&self, b: &Binding) -> String { + match b { + Binding::Command { command, params } => { + let short = ls::icons::command_label(command, params); + if short != *command { + return crate::i18n::tr(&short).to_string(); + } + // the registry's own label + let label = crate::menus::ui_commands() + .find(|c| c.0 == command) + .map(|c| c.1.to_string()) + .or_else(|| self.0.session.commands().into_iter().find(|c| c.id == command).map(|c| c.label.to_string())) + .unwrap_or_else(|| command.clone()); + crate::i18n::tr(&label).to_string() + } + other => crate::i18n::tr(&other.describe()).to_string(), + } + } + + fn state(&self, b: &Binding) -> Option { + let app = self.0; + let Binding::Command { command, params } = b else { return None }; + let photo = app.session.active().and_then(|id| app.session.catalog.photo(id)); + Some(match command.as_str() { + "develop.autoSync" => app.session.auto_sync, + "view.beforeAfter" => app.ui.before_after != BeforeAfter::Off, + "view.clipping" => app.ui.show_clipping, + "view.maskOverlay" => app.ui.mask_overlay, + "view.filmstrip" => app.ui.filmstrip, + "view.survey" => app.ui.view == ViewMode::Survey, + "develop.treatment" => app.session.active().and_then(|id| app.session.develop_of(id)).is_some_and(|d| crate::is_bw(&d)), + "panel.crop" => app.ui.right == RightPanel::Crop, + "panel.remove" => app.ui.right == RightPanel::Remove, + "panel.masking" => app.ui.right == RightPanel::Masking, + "panel.edit" => app.ui.right == RightPanel::Edit, + // New Brush and Add / Subtract are one-shot: never lit; the plain brush is a mode + "tool.brush" if params.get("new").is_some() || params.get("op").is_some() => return None, + "tool.brush" => app.ui.tool == "brush", + "tool.linear" => app.ui.tool == "linear", + "tool.radial" => app.ui.tool == "radial", + "tool.wbPicker" => app.ui.tool == "wbPicker", + "photo.rate" => photo.is_some_and(|p| params.get("rating").and_then(Value::as_u64) == Some(u64::from(p.rating))), + "photo.label" => { + let want = params.get("label").and_then(Value::as_str).and_then(lightcraft_catalog::ColorLabel::parse); + photo.is_some_and(|p| p.label.is_some() && p.label == want) + } + "photo.pick" => photo.is_some_and(|p| p.flag == lightcraft_catalog::Flag::Pick), + _ => return None, + }) + } + + fn tr(&self, english: &str) -> String { + crate::i18n::tr(english).to_string() + } +} + +/// The layout of a device as the app shows it now. +pub fn layout(app: &LightcraftApp, device: &'static ls::DeviceDef) -> ls::layout::DeviceLayout { + ls::layout::build(&app.surface.runtime, device, &AppHost(app)) +} + +// ------------------------------------------------------------------------------------- frames + +/// Once per frame: load settings, follow the app's context, flush dial movement, end idle +/// gestures, push layouts to subscribed surfaces, save settings. +pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { + let now = ctx.input(|i| i.time); + app.surface.now = now; + app.surface.pixels_per_point = ctx.pixels_per_point(); + crate::surface_plugin::poll(app); + if !app.surface.loaded { + app.surface.loaded = true; + load(app); + } + // Touch to find ends with the page that started it: the console acts on photos again + let controls_open = matches!(&app.ui.dialog, Some(crate::state::Dialog::Settings { tab }) if tab == "controls" || app.surface.editor.window); + if app.surface.editor.touch_find.is_some_and(|at| !controls_open || now - at > TOUCH_FIND_GRACE) { + app.surface.editor.touch_find = None; + app.surface.runtime.cancel_learn(); + } + let now_ms = now * 1000.0; + // the photo changed under a gesture: end it (its ticks belonged to the other photo) + let photo = app.session.active(); + if photo != app.surface.last_photo { + app.surface.last_photo = photo; + let ends: Vec = app.surface.runtime.interrupt().into_iter().filter(|e| !matches!(e, Effect::Adjust { .. })).collect(); + run_effects(app, ends); + app.surface.gesture = None; + } + let key = context_key(app); + app.surface.runtime.set_context(&key); + let effects = app.surface.runtime.flush(now_ms); + run_effects(app, effects); + push(app, now_ms); + listener(app, now); + #[cfg(not(target_arch = "wasm32"))] + app.surface.pairing.expire(now_ms.max(0.0) as u64); + if let Some(since) = app.surface.dirty_since + && now - since >= 0.5 + { + app.surface.dirty_since = None; + save(app); + } + if app.surface.runtime.busy(now_ms) { + ctx.request_repaint_after(std::time::Duration::from_millis(u64::from(app.surface.settings().transport.flush_ms))); + } +} + +/// Keep the surface listener running on the configured port while surfaces are enabled. +fn listener(app: &mut LightcraftApp, now: f64) { + let want = app.surface.settings().enabled.then_some(app.surface.settings().port); + if want == app.surface.listening || now < app.surface.listen_retry_at { + return; + } + let Some(start) = app.services.surface_listener.as_mut() else { return }; + // stop the old one first (a new port, or switched off) + if app.surface.listening.is_some() { + let _ = start(None); + app.surface.listening = None; + } + match want { + Some(port) => match start(Some(port)) { + Ok(()) => { + app.surface.listening = Some(port); + app.surface.listen_error = None; + } + Err(e) => { + log::warn!("control surfaces: {e}"); + app.surface.listen_error = Some(e); + app.surface.listen_retry_at = now + 2.0; + } + }, + None => app.surface.listen_error = None, + } +} + +fn load(app: &mut LightcraftApp) { + let Some(store) = app.services.surface_store.as_ref() else { return }; + match store.load() { + Ok(Some(text)) => match ls::SurfaceSettings::from_json(&text) { + Ok(s) => app.surface.runtime.replace_settings(s), + Err(e) => { + log::warn!("{e}"); + app.notices + .push(format!("{e}. Control surfaces use their defaults; Settings ▸ Controls saves a new file when you change something.")); + app.surface.load_error = Some(e); + } + }, + Ok(None) => {} + Err(e) => { + log::warn!("control-surfaces.json: {e}"); + app.surface.load_error = Some(e); + } + } + // the Logi plugin installed: on, and trusted, before the listener starts + crate::surface_plugin::auto_setup(app); +} + +/// Save the settings now (Settings ▸ Controls, keys that change settings). +pub fn save(app: &mut LightcraftApp) { + let Some(store) = app.services.surface_store.as_ref() else { return }; + let text = app.surface.settings().to_json(); + match store.save(&text) { + Ok(()) => { + app.surface.save_error = None; + app.surface.load_error = None; + } + Err(e) => { + log::warn!("control-surfaces.json: {e}"); + app.surface.save_error = Some(e); + } + } +} + +/// Send each subscriber its layout when it changed (held back while a value is still catching +/// up with the dial: echo suppression). +fn push(app: &mut LightcraftApp, _now_ms: f64) { + app.surface.subscribers.retain(|s| s.sink.is_open()); + if app.surface.subscribers.is_empty() { + return; + } + if let Some(t) = app.surface.runtime.turning() + && app.surface.runtime.holds_feedback(t) + { + return; + } + let wanted: Vec<(&'static ls::DeviceDef, Vec)> = app.surface.subscribers.iter().map(|s| (s.device, s.watch.clone())).collect(); + let mut layouts: Vec<(usize, Value)> = Vec::new(); + for (i, (d, watch)) in wanted.iter().enumerate() { + let mut v = serde_json::to_value(layout(app, d)).unwrap_or(Value::Null); + if !watch.is_empty() + && let Value::Object(m) = &mut v + { + m.insert("values".into(), watched_values(app, watch)); + } + layouts.push((i, v)); + } + let mut dead = Vec::new(); + for (i, v) in layouts { + let Some(s) = app.surface.subscribers.get_mut(i) else { continue }; + if s.last.as_ref() == Some(&v) { + continue; + } + if s.sink.tx.send(json!({"event": "surface.layout", "layout": v})).is_err() { + dead.push(i); + } + s.last = Some(v); + } + for i in dead.into_iter().rev() { + if i < app.surface.subscribers.len() { + app.surface.subscribers.remove(i); + } + } +} + +/// `{target: {"value": "+0.35", "position": 0.53}}` for watched values that have one now. +fn watched_values(app: &LightcraftApp, watch: &[String]) -> Value { + let show = app.surface.settings().look.show_values; + let mut m = serde_json::Map::new(); + for t in watch { + let Some(spec) = ls::targets::target_spec(t) else { continue }; + let Some(v) = value(app, t) else { continue }; + let text = if show { json!(spec.format(v)) } else { Value::Null }; + m.insert(t.clone(), json!({"value": text, "position": spec.position(v)})); + } + Value::Object(m) +} + +/// `surface.catalog`: every action, with labels and categories in the app's language. +pub fn catalog(app: &LightcraftApp) -> Value { + let host = AppHost(app); + let all = ls::catalog::entries(); + let mut groups: Vec<&'static str> = Vec::new(); + for e in &all { + if !groups.contains(&e.group) { + groups.push(e.group); + } + } + let entries: Vec = all + .into_iter() + .map(|e| { + json!({ + "key": e.key, + "group": host.tr(e.group), + "label": host.label(&e.binding), + "icon": e.icon, + "value": e.value, + }) + }) + .collect(); + json!({"groups": groups.iter().map(|g| host.tr(g)).collect::>(), "entries": entries}) +} + +// ------------------------------------------------------------------------------------- protocol + +fn ok(v: Value) -> Outcome { + Outcome::Done(json!({"ok": true, "result": v})) +} +fn err(e: impl std::fmt::Display) -> Outcome { + Outcome::Done(json!({"ok": false, "error": e.to_string()})) +} + +/// The most events one `surface.input` may carry. +pub const MAX_EVENTS: usize = 256; + +/// One `surface.input` event: a control of the device, or an action from the surface's own app. +enum Ev { + Input(ls::Input), + Act(Binding, Option), +} + +fn run_event(app: &mut LightcraftApp, e: Ev, now_ms: f64) -> usize { + let effects = match e { + Ev::Input(i) => app.surface.runtime.input(i, now_ms), + Ev::Act(b, ticks) => app.surface.runtime.act(&b, ticks, now_ms), + }; + let n = effects.len(); + run_effects(app, effects); + n +} + +fn parse_events(p: &Value) -> Result, String> { + let list = p.get("events").and_then(Value::as_array).ok_or("surface.input: give `events: [...]`")?; + if list.len() > MAX_EVENTS { + return Err(format!("surface.input: at most {MAX_EVENTS} events at once")); + } + let mut out = Vec::new(); + for e in list { + if let Some(key) = e.get("action").and_then(Value::as_str) { + let entry = ls::catalog::find(key).ok_or_else(|| format!("surface.input: no action `{}`", ls::protocol::clean(key)))?; + if let Some(t) = e.get("ticks") { + let t = t.as_f64().filter(|t| t.is_finite()).ok_or("surface.input: `ticks` must be a number")?; + out.push(Ev::Act(entry.binding, Some(t.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32))); + } else if let Some(down) = e.get("press").and_then(Value::as_bool) { + out.push(if down { Ev::Act(entry.binding, None) } else { Ev::Input(ls::Input::Release { control: "action".into() }) }); + } else { + return Err("surface.input: an event needs `ticks` or `press`".into()); + } + continue; + } + let control = e + .get("control") + .and_then(Value::as_str) + .map(ls::protocol::clean) + .filter(|c| !c.is_empty()) + .ok_or("surface.input: each event needs a `control` or an `action`")?; + if let Some(t) = e.get("ticks") { + let t = t.as_f64().filter(|t| t.is_finite()).ok_or("surface.input: `ticks` must be a number")?; + out.push(Ev::Input(ls::Input::Turn { control, ticks: t.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32 })); + } else if let Some(down) = e.get("press").and_then(Value::as_bool) { + let page = e.get("page").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).filter(|n| (1..=64).contains(n)); + out.push(Ev::Input(if down { ls::Input::Press { control, page } } else { ls::Input::Release { control } })); + } else { + return Err("surface.input: an event needs `ticks` or `press`".into()); + } + } + Ok(out) +} + +fn hello(app: &mut LightcraftApp, req: &ControlRequest) -> Outcome { + let p = &req.params; + let protocol = p.get("protocol").and_then(Value::as_u64).unwrap_or(u64::from(ls::protocol::PROTOCOL)); + if protocol > u64::from(ls::protocol::PROTOCOL) { + return err(format!("surface.hello: this LightCraft speaks surface protocol {}; update LightCraft", ls::protocol::PROTOCOL)); + } + let paired = match p.get("token").and_then(Value::as_str) { + Some(t) => match ls::protocol::verify(app.surface.settings(), t).map(|c| c.client.clone()) { + Some(client) => { + app.surface.authed.insert(req.conn, client); + true + } + None => false, + }, + None => app.surface.authed.contains_key(&req.conn) || req.conn == 0, + }; + ok(json!({ + "protocol": ls::protocol::PROTOCOL, + "app": "LightCraft", + "version": env!("CARGO_PKG_VERSION"), + "paired": paired, + "enabled": app.surface.settings().enabled, + "devices": ls::devices::devices().iter().map(|d| json!({"id": d.id, "name": d.name, "controls": d.controls.iter().map(|c| json!({"id": c.id, "kind": c.kind, "label": c.label})).collect::>()})).collect::>(), + })) +} + +fn pair(app: &mut LightcraftApp, req: &ControlRequest) -> Outcome { + let p = &req.params; + let now = (app.surface.now * 1000.0).max(0.0) as u64; + if let Some(id) = p.get("request").and_then(Value::as_str) { + return match app.surface.pairing.poll(id, now) { + Some(ls::protocol::PairState::Approved { token }) => { + if let Some(c) = ls::protocol::verify(app.surface.settings(), &token).map(|c| c.client.clone()) { + app.surface.authed.insert(req.conn, c); + } + ok(json!({"status": "approved", "token": token})) + } + Some(state) => ok(serde_json::to_value(state).unwrap_or_default()), + None => err("surface.pair: no such request (it may have expired); ask again"), + }; + } + let client = p.get("client").and_then(Value::as_str).unwrap_or(""); + let name = p.get("name").and_then(Value::as_str).unwrap_or(client); + match app.surface.pairing.ask(client, name, now) { + Ok(r) => { + let text = crate::i18n::tr_format!("{name} asks to control LightCraft: see Settings, Controls", name = r.name.clone()); + app.toast_for(&app.tasks.repaint.clone().unwrap_or_default(), text, 8.0); + ok(json!({"status": "pending", "request": r.request, "code": r.code})) + } + Err(e) => err(e), + } +} + +/// Handle `surface.*` control methods; `None` for other methods. +pub fn handle(app: &mut LightcraftApp, req: &ControlRequest) -> Option { + let m = req.method.as_str(); + if !m.starts_with("surface.") { + return None; + } + if !app.surface.loaded { + app.surface.loaded = true; + load(app); + } + let p = &req.params; + Some(match m { + "surface.hello" => hello(app, req), + "surface.pair" => pair(app, req), + "surface.catalog" => ok(catalog(app)), + "surface.icons" => { + let names: Vec = match p.get("names").and_then(Value::as_array) { + Some(a) => a.iter().filter_map(Value::as_str).take(512).map(str::to_string).collect(), + None => ls::icons::names().map(str::to_string).collect(), + }; + let map: serde_json::Map = names.into_iter().filter_map(|n| ls::icons::svg(&n).map(|s| (n, json!(s)))).collect(); + ok(Value::Object(map)) + } + _ => { + if !app.surface.settings().enabled { + return Some(err("control surfaces are switched off (Settings ▸ Controls)")); + } + let client = if req.conn == 0 { Some("local".to_string()) } else { app.surface.authed.get(&req.conn).cloned() }; + let Some(client) = client else { + return Some(err( + "this surface isn't paired: call surface.pair, approve it in Settings ▸ Controls, then surface.hello with its token", + )); + }; + match m { + "surface.subscribe" => { + let device = p.get("device").and_then(Value::as_str).unwrap_or(ls::devices::MX_CREATIVE_CONSOLE.id); + let Some(device) = ls::devices::find_device(device) else { + return Some(err(format!("surface.subscribe: unknown device `{device}`"))); + }; + let Some(sink) = req.sink.clone() else { return Some(err("surface.subscribe: this connection can't receive events")) }; + app.surface.subscribers.retain(|s| s.conn != req.conn); + let l = serde_json::to_value(layout(app, device)).unwrap_or_default(); + app.surface.subscribers.push(Subscriber { conn: req.conn, client, device, sink, last: Some(l.clone()), watch: Vec::new() }); + ok(json!({"layout": l})) + } + "surface.watch" => { + let targets: Vec = p + .get("targets") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(Value::as_str) + .filter(|t| ls::targets::target_spec(t).is_some()) + .take(MAX_WATCH) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + match app.surface.subscribers.iter_mut().find(|s| s.conn == req.conn) { + Some(s) => { + s.watch = targets; + // the next frame pushes the values + s.last = None; + ok(Value::Null) + } + None => err("surface.watch: subscribe first"), + } + } + "surface.unsubscribe" => { + app.surface.subscribers.retain(|s| s.conn != req.conn); + ok(Value::Null) + } + "surface.layout" => { + let device = p.get("device").and_then(Value::as_str).unwrap_or(ls::devices::MX_CREATIVE_CONSOLE.id); + match ls::devices::find_device(device) { + Some(d) => ok(serde_json::to_value(layout(app, d)).unwrap_or_default()), + None => err(format!("surface.layout: unknown device `{device}`")), + } + } + "surface.input" => match parse_events(p) { + Ok(events) => { + let now_ms = app.surface.now * 1000.0; + let mut n = 0; + for e in events { + n += run_event(app, e, now_ms); + } + if let Some(ctx) = app.tasks.repaint.clone() { + ctx.request_repaint(); + } + ok(json!({"effects": n})) + } + Err(e) => err(e), + }, + other => err(format!("unknown method `{other}`")), + } + } + }) +} + +// ------------------------------------------------------------------------------------- commands + +/// `surface.*` UI commands (`engine.execute`); `None` for other ids. +pub fn command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option> { + if !app.surface.loaded { + app.surface.loaded = true; + load(app); + } + if let Some(r) = crate::surface_plugin::command(app, id) { + return Some(r); + } + let now_ms = app.surface.now * 1000.0; + let r = match id { + "surface.maskPrevious" | "surface.maskNext" => step_mask(app, if id == "surface.maskNext" { 1 } else { -1 }), + "surface.dialogConfirm" => crate::control::confirm_dialog(app), + "surface.dialogCancel" => { + app.ui.dialog = None; + Ok(Value::Null) + } + "surface.pageNext" | "surface.pagePrevious" => { + let group = match p.get("group").and_then(Value::as_str) { + Some("keys") => Some(ls::PageGroup::Keys), + Some("dials") => Some(ls::PageGroup::Dials), + _ => None, + }; + let b = if id == "surface.pageNext" { Binding::PageNext { group } } else { Binding::PagePrevious { group } }; + act(app, b, now_ms) + } + "surface.page" => match p.get("page").and_then(Value::as_str) { + Some(page) => act(app, Binding::Page { page: page.into() }, now_ms), + None => Err("surface.page: give `page`".into()), + }, + "surface.profile" => match p.get("profile").and_then(Value::as_str) { + Some(name) if app.surface.settings().profiles.iter().any(|q| q.name == name) => { + act(app, Binding::Profile { profile: name.into() }, now_ms) + } + Some(name) => Err(format!("surface.profile: no profile `{name}`")), + None => act(app, Binding::ProfileNext, now_ms), + }, + "surface.applyToSelected" | "surface.followContext" => { + let (cur, b) = if id == "surface.applyToSelected" { + (app.surface.settings().apply_to_selected, Binding::ApplyToSelected) + } else { + (app.surface.settings().follow_context, Binding::FollowContext) + }; + match p.get("on").and_then(Value::as_bool) { + Some(on) if on == cur => Ok(json!({"on": on})), + _ => act(app, b, now_ms).map(|_| { + let on = if id == "surface.applyToSelected" { + app.surface.settings().apply_to_selected + } else { + app.surface.settings().follow_context + }; + json!({"on": on}) + }), + } + } + "surface.state" => Ok(state(app)), + "surface.import" => import(app, p), + "surface.export" => export(app, p), + "surface.forget" => match p.get("client").and_then(Value::as_str) { + // what Forget does in Settings > Controls: the client's token stops working + Some(c) if app.surface.settings().paired.iter().any(|x| x.client == c) => { + let c = c.to_string(); + app.surface.unpair(&c); + Ok(Value::Null) + } + Some(c) => Err(format!("surface.forget: no paired surface `{}`", ls::protocol::clean(c))), + None => Err("surface.forget: give `client`".into()), + }, + "surface.settings" => match p.get("settings") { + // replace the whole settings file content (agents, tests); keeps pairings + Some(v) => match ls::SurfaceSettings::from_json(&v.to_string()) { + Ok(mut s) => { + s.paired = app.surface.settings().paired.clone(); + app.surface.runtime.replace_settings(s); + app.surface.dirty_since.get_or_insert(app.surface.now); + Ok(Value::Null) + } + Err(e) => Err(e), + }, + None => Ok(serde_json::to_value(app.surface.settings()).unwrap_or_default()), + }, + "surface.input" => match parse_events(p) { + // the same input a surface sends, from a command (agents, tests, the editor's preview) + Ok(events) => { + for e in events { + run_event(app, e, now_ms); + } + Ok(Value::Null) + } + Err(e) => Err(e), + }, + _ => return None, + }; + Some(r) +} + +fn act(app: &mut LightcraftApp, b: Binding, now_ms: f64) -> Result { + let effects = app.surface.runtime.perform("command", &b, now_ms); + run_effects(app, effects); + Ok(state(app)) +} + +fn step_mask(app: &mut LightcraftApp, step: i64) -> Result { + let id = app.session.active().ok_or("no active photo")?; + let d = app.session.develop_of(id).ok_or("no active photo")?; + let ids: Vec = d.masks.iter().map(|m| m.id).collect(); + if ids.is_empty() { + return Err("this photo has no masks".into()); + } + let n = ids.len() as i64; + let i = app.session.active_mask.and_then(|m| ids.iter().position(|x| *x == m)).map_or(if step > 0 { -1 } else { n }, |i| i as i64); + let j = (i + step).rem_euclid(n); + let next = ids.get(usize::try_from(j).unwrap_or(0)).copied().ok_or("no mask")?; + app.run("mask.select", json!({"id": next}))?; + Ok(json!({"id": next})) +} + +/// `surface.state`: profile, context, pages, focus, toggles, connected surfaces, waiting pairing +/// requests. +pub fn state(app: &LightcraftApp) -> Value { + let r = &app.surface.runtime; + json!({ + "enabled": r.settings().enabled, + "profile": r.settings().profile, + "profiles": r.settings().profiles.iter().map(|p| p.name.clone()).collect::>(), + "context": r.context(), + "keyPage": r.pages().get(&ls::PageGroup::Keys), + "dialPage": r.pages().get(&ls::PageGroup::Dials), + "focus": r.focus(), + "turning": r.turning(), + "applyToSelected": r.settings().apply_to_selected, + "followContext": r.settings().follow_context, + "connected": app.surface.connected().into_iter().map(|(c, d)| json!({"client": c, "device": d})).collect::>(), + "paired": r.settings().paired.iter().map(|c| json!({"client": c.client, "name": c.name})).collect::>(), + "pairing": app.surface.pairing.waiting().map(|q| json!({"request": q.request, "client": q.client, "name": q.name, "code": q.code})).collect::>(), + "osd": r.shown(app.surface.now * 1000.0).map(|(s, _)| match s { + ls::runtime::Shown::Value { target } => json!({"value": target, "text": value(app, target).and_then(|v| ls::targets::target_spec(target).map(|s| s.format(v)))}), + ls::runtime::Shown::Command { label, .. } => json!({"command": label}), + ls::runtime::Shown::Notice { text } => json!({"notice": text}), + }), + "loadError": app.surface.load_error, + "saveError": app.surface.save_error, + }) +} + +/// The largest file `surface.import` reads. +const MAX_IMPORT: u64 = 16 * 1024 * 1024; + +fn read_file(path: &str) -> Result, String> { + #[cfg(not(target_arch = "wasm32"))] + { + let meta = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?; + if meta.len() > MAX_IMPORT { + return Err(format!("{path} is too large")); + } + std::fs::read(path).map_err(|e| format!("{path}: {e}")) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, MAX_IMPORT); + Err("files can't be read here".into()) + } +} + +/// TactileBridge's settings file on this computer, if there is one. +pub fn tactilebridge_settings_path() -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + let base = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from)?; + let p = base.join("TactileBridge").join("settings.json"); + p.is_file().then_some(p) + } + #[cfg(target_arch = "wasm32")] + { + None + } +} + +/// Loupedeck's profiles for the Loupedeck+ made for the photo editor whose actions LightCraft +/// maps (Loupedeck keeps them under `@_lightroom`), as its software keeps them on this computer: +/// (the profile's name, its `ProfileInfo.json`), newest first. Read only. +pub fn loupedeck_profiles() -> Vec<(String, std::path::PathBuf)> { + #[cfg(not(target_arch = "wasm32"))] + { + let Some(base) = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from) else { return Vec::new() }; + let mut out = Vec::new(); + for device in ["Loupedeck15", "Loupedeck10"] { + let Ok(apps) = std::fs::read_dir(base.join("Loupedeck").join("Applications").join(device)) else { continue }; + for app in apps.flatten().take(200) { + if !app.file_name().to_string_lossy().to_ascii_lowercase().contains("lightroom") { + continue; + } + let Ok(profiles) = std::fs::read_dir(app.path().join("Profiles")) else { continue }; + for prof in profiles.flatten().take(200) { + let file = prof.path().join("ProfileInfo.json"); + let Ok(meta) = std::fs::metadata(&file) else { continue }; + if meta.len() > MAX_IMPORT { + continue; + } + let Ok(text) = std::fs::read_to_string(&file) else { continue }; + let Ok(v) = serde_json::from_str::(text.trim_start_matches('\u{feff}')) else { continue }; + let name = v.get("displayName").and_then(Value::as_str).unwrap_or("Loupedeck").to_string(); + let changed = v.get("lastModifiedTimeUtc").and_then(Value::as_str).unwrap_or_default().to_string(); + out.push((changed, name, file)); + if out.len() >= 50 { + break; + } + } + } + } + // the one changed last (the user's own) first + out.sort_by(|a, b| b.0.cmp(&a.0)); + out.into_iter().map(|(_, n, f)| (n, f)).collect() + } + #[cfg(target_arch = "wasm32")] + { + Vec::new() + } +} + +/// Is this file a Loupedeck+ profile (its `ProfileInfo.json`, or an `.lp5` holding one)? +fn is_loupedeck(bytes: &[u8]) -> bool { + let json = if bytes.starts_with(b"PK") { ls::zip::read_member(bytes, "ProfileInfo.json").unwrap_or_default() } else { bytes.to_vec() }; + let text = String::from_utf8_lossy(json.get(..json.len().min(8192)).unwrap_or_default()); + text.contains("\"Loupedeck15\"") || text.contains("\"Loupedeck10\"") +} + +/// A Loupedeck+ profile's layout into every LightCraft profile (the console has no pages: its +/// controls hold on every page and in every profile), replacing an earlier import. +fn import_loupedeck(app: &mut LightcraftApp, s: &mut ls::SurfaceSettings, bytes: &[u8]) -> Result { + let presets: Vec<(String, String)> = app.session.presets.iter().map(|p| (p.name.to_lowercase(), p.id.clone())).collect(); + let find = |name: &str| { + let n = name.trim().to_lowercase(); + presets.iter().find(|(p, _)| *p == n).map(|(_, id)| id.clone()) + }; + let imported = ls::loupedeck::import(bytes, &find)?; + for p in &mut s.profiles { + p.base.retain(|c, _| !c.starts_with("ld.")); + p.base.extend(imported.bindings.clone()); + } + app.surface.last_report = Some(imported.report.clone()); + Ok(json!({"profile": s.profile, "device": ls::devices::LOUPEDECK_PLUS.id, "loupedeck": imported.name, "report": imported.report})) +} + +/// `surface.import {path}`: a TactileBridge `settings.json`, a Logi profile (`.lp5`), a +/// Loupedeck+ profile (its `ProfileInfo.json` or an exported `.lp5`) or a LightCraft layout file +/// (`.lcsurface`, a profile as JSON). +fn import(app: &mut LightcraftApp, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).ok_or("surface.import: give `path`")?; + let bytes = read_file(path)?; + let lower = path.to_ascii_lowercase(); + let mut s = app.surface.settings().clone(); + let result = if is_loupedeck(&bytes) { + import_loupedeck(app, &mut s, &bytes)? + } else if lower.ends_with(".lp5") { + let (mut profile, report) = ls::tactilebridge::import_lp5(&bytes)?; + profile.name = unique_profile_name(&s, &profile.name); + let name = profile.name.clone(); + s.profiles.push(profile); + s.profile = name.clone(); + app.surface.last_report = Some(report.clone()); + json!({"profile": name, "report": report}) + } else if lower.ends_with(".lcsurface") { + let text = String::from_utf8_lossy(&bytes); + let mut profile: ls::Profile = serde_json::from_str(&text).map_err(|e| format!("{path}: not a LightCraft layout file ({e})"))?; + profile.name = unique_profile_name(&s, if profile.name.trim().is_empty() { "Imported" } else { &profile.name }); + let name = profile.name.clone(); + s.profiles.push(profile); + s.profile = name.clone(); + json!({"profile": name}) + } else { + let text = String::from_utf8_lossy(&bytes); + let report = ls::tactilebridge::import_settings(&mut s, &text)?; + app.surface.last_report = Some(report.clone()); + json!({"profile": s.profile, "report": report}) + }; + s.paired = app.surface.settings().paired.clone(); + app.surface.runtime.replace_settings(s); + app.surface.dirty_since.get_or_insert(app.surface.now); + Ok(result) +} + +fn unique_profile_name(s: &ls::SurfaceSettings, base: &str) -> String { + let mut name = base.trim().to_string(); + let mut n = 2; + while s.profiles.iter().any(|p| p.name == name) { + name = format!("{} {n}", base.trim()); + n += 1; + } + name +} + +/// `surface.export {path, profile?}`: write a profile as a LightCraft layout file. +fn export(app: &mut LightcraftApp, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).ok_or("surface.export: give `path`")?; + let name = p.get("profile").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| app.surface.settings().profile.clone()); + let profile = app.surface.settings().profiles.iter().find(|q| q.name == name).ok_or_else(|| format!("surface.export: no profile `{name}`"))?; + let text = serde_json::to_string_pretty(profile).map_err(|e| e.to_string())?; + match app.services.write.as_mut() { + Some(w) => w(path, text.as_bytes())?, + None => return Err("files can't be written here".into()), + } + Ok(json!({"path": path, "profile": name})) +} diff --git a/crates/ui-egui/src/surface_icons.rs b/crates/ui-egui/src/surface_icons.rs new file mode 100644 index 00000000000..e9acf3be3c2 --- /dev/null +++ b/crates/ui-egui/src/surface_icons.rs @@ -0,0 +1,144 @@ +//! Control-surface icons (`assets/surface-icons`, the same pack the surface plugins draw on keys) +//! as egui textures, for Settings ▸ Controls and the on-screen readout. Rasterised once per name +//! and size and kept for the session. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; + +use lightcraft_surface as ls; + +type Cache = Arc>>>; + +/// The most icon textures kept (names × sizes); beyond it the cache starts over. +const MAX_CACHED: usize = 1024; + +fn cache(ctx: &egui::Context) -> Cache { + ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::new("surfaceIcons")).clone()) +} + +/// Rasterise an SVG to `px` × `px` straight RGBA (`None`: not an SVG resvg reads). +pub fn rasterize(svg: &str, px: u32) -> Option { + let px = px.clamp(8, 512); + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).ok()?; + let mut pixmap = resvg::tiny_skia::Pixmap::new(px, px)?; + let size = tree.size(); + let (w, h) = (size.width(), size.height()); + if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + return None; + } + let s = (px as f32 / w).min(px as f32 / h); + let dx = (px as f32 - w * s) / 2.0; + let dy = (px as f32 - h * s) / 2.0; + resvg::render(&tree, resvg::tiny_skia::Transform::from_row(s, 0.0, 0.0, s, dx, dy), &mut pixmap.as_mut()); + // tiny-skia keeps premultiplied alpha, as egui's textures do + let pixels: Vec = + pixmap.pixels().iter().map(|p| egui::Color32::from_rgba_premultiplied(p.red(), p.green(), p.blue(), p.alpha())).collect(); + Some(egui::ColorImage { size: [px as usize, px as usize], source_size: egui::vec2(px as f32, px as f32), pixels }) +} + +/// The texture of icon `name` at `points` (sized for the screen's pixels). +pub fn texture(ctx: &egui::Context, name: &str, points: f32) -> Option { + let svg = ls::icons::svg(name)?; + let px = (points * ctx.pixels_per_point()).round().clamp(8.0, 512.0) as u32; + let c = cache(ctx); + let mut map = c.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(t) = map.get(&(name.to_string(), px)) { + return t.clone(); + } + if map.len() >= MAX_CACHED { + map.clear(); + } + let tex = rasterize(svg, px).map(|img| ctx.load_texture(format!("surfaceIcon:{name}:{px}"), img, egui::TextureOptions::LINEAR)); + map.insert((name.to_string(), px), tex.clone()); + tex +} + +/// Paint icon `name` into `rect` (nothing when there's no such icon). +pub fn paint(ui: &egui::Ui, name: &str, rect: egui::Rect, tint: egui::Color32) -> bool { + paint_with(ui.ctx(), ui.painter(), name, rect, tint) +} + +/// [`paint`] with any painter (the readout draws on its own layer). +pub fn paint_with(ctx: &egui::Context, painter: &egui::Painter, name: &str, rect: egui::Rect, tint: egui::Color32) -> bool { + let side = rect.width().min(rect.height()); + let Some(t) = texture(ctx, name, side) else { return false }; + let r = egui::Rect::from_center_size(rect.center(), egui::vec2(side, side)); + painter.image(t.id(), r, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint); + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pack_rasterises_and_bad_svg_does_not() { + let svg = ls::icons::svg("exposure").expect("exposure icon"); + let img = rasterize(svg, 48).expect("rasterised"); + assert_eq!(img.size, [48, 48]); + assert!(img.pixels.iter().any(|p| p.a() > 0), "something is drawn"); + assert!(rasterize("not svg", 32).is_none()); + assert!(rasterize("", 32).is_none()); + // every icon of the pack reads + for n in ls::icons::names() { + assert!(rasterize(ls::icons::svg(n).unwrap_or_default(), 16).is_some(), "{n}"); + } + } +} + +/// Where an icon really draws, in its own viewBox units, found on a canvas twice its size (so a +/// drawing that spills over the viewBox shows): (left, top, right, bottom, viewBox width, height). +pub fn drawn_box(svg: &str) -> Option<(f32, f32, f32, f32, f32, f32)> { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).ok()?; + let (w, h) = (tree.size().width(), tree.size().height()); + if !(w > 0.0 && h > 0.0) { + return None; + } + let px = 256u32; + let mut pixmap = resvg::tiny_skia::Pixmap::new(px, px)?; + // the viewBox in the middle half of the canvas + let s = (px as f32 / 2.0) / w.max(h); + let off = px as f32 / 4.0; + resvg::render(&tree, resvg::tiny_skia::Transform::from_row(s, 0.0, 0.0, s, off, off), &mut pixmap.as_mut()); + let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0u32, 0u32); + for (i, p) in pixmap.pixels().iter().enumerate() { + if p.alpha() > 24 { + let (x, y) = (i as u32 % px, i as u32 / px); + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x + 1); + y1 = y1.max(y + 1); + } + } + if x0 > x1 { + return None; + } + let u = |v: u32| (v as f32 - off) / s; + Some((u(x0), u(y0), u(x1), u(y1), w, h)) +} + +#[cfg(test)] +mod placement { + /// Every icon draws fully inside its key with a margin, horizontally centred, and not tiny: + /// the keys show the whole drawing at about the same size (`assets/surface-icons`). + #[test] + fn every_icon_is_inside_centred_and_full_size() { + let mut bad = Vec::new(); + for n in lightcraft_surface::icons::names() { + let Some((l, t, r, b, w, h)) = super::drawn_box(lightcraft_surface::icons::svg(n).unwrap_or_default()) else { + bad.push(format!("{n}: draws nothing")); + continue; + }; + if l < 0.5 || t < 0.5 || r > w - 0.5 || b > h - 0.5 { + bad.push(format!("{n}: outside the key ({l:.1} {t:.1} {r:.1} {b:.1})")); + } + if ((l + r) / 2.0 - w / 2.0).abs() > 1.0 { + bad.push(format!("{n}: off-centre ({:.1})", (l + r) / 2.0)); + } + if (r - l).max(b - t) < 0.45 * w { + bad.push(format!("{n}: small ({:.2})", (r - l).max(b - t) / w)); + } + } + assert!(bad.is_empty(), "{bad:#?}"); + } +} diff --git a/crates/ui-egui/src/surface_plugin.rs b/crates/ui-egui/src/surface_plugin.rs new file mode 100644 index 00000000000..a0648056058 --- /dev/null +++ b/crates/ui-egui/src/surface_plugin.rs @@ -0,0 +1,237 @@ +//! Installing a surface's plugin into its maker's app from Settings ▸ Controls (the LightCraft +//! plugin for Logi Options+), and taking it out again. +//! +//! The host app supplies a [`PluginInstaller`] (`Services::surface_plugin`; desktop only): it +//! knows where the maker's app keeps plugins, where LightCraft's copy of the plugin package is, +//! and how to hand it to the maker's installer. Installing runs off the UI thread with a row in +//! the activity stack. Commands: `surface.plugin` (status), `surface.installPlugin`, +//! `surface.uninstallPlugin`. + +use std::sync::Arc; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; + +use lightcraft_engine::activity::{Cancel, TaskGuard}; +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::LightcraftApp; +use lightcraft_surface as ls; + +/// Where a surface plugin stands. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginStatus { + /// The maker's app, by name ("Logi Options+"), when it is installed on this computer. + pub host: Option, + /// The version of the plugin installed there. + pub installed: Option, + /// The version of the plugin package that comes with LightCraft (none: this build has none). + pub package: Option, + /// Where that package is. + pub package_path: Option, +} + +impl PluginStatus { + /// The package is newer than what is installed (or nothing is). + pub fn can_install(&self) -> bool { + self.host.is_some() && self.package.is_some() + } + + pub fn update_available(&self) -> bool { + match (&self.installed, &self.package) { + (Some(i), Some(p)) => version_key(p) > version_key(i), + _ => false, + } + } +} + +fn version_key(v: &str) -> Vec { + v.split(['.', '-', '+']).map(|p| p.parse::().unwrap_or(0)).collect() +} + +/// The host app's side: finds and installs a surface plugin. Calls may block (they run on a +/// worker thread, except `status`, which only looks at files). +pub trait PluginInstaller: Send + Sync { + /// The plugin's name for messages ("LightCraft plugin for Logi Options+"). + fn name(&self) -> String; + fn status(&self) -> PluginStatus; + /// Install (or update) the plugin; it connects to LightCraft on `port`. The text says what + /// happens next ("Click Continue in Logi Options+…"). + fn install(&self, port: u16) -> Result; + fn uninstall(&self) -> Result; + /// The trust token the installed plugin reads (its data folder), if there is one. + fn plugin_token(&self) -> Option { + None + } + /// Hand the installed plugin a trust token (`Some`) and the port LightCraft listens on, in + /// its data folder, which only this user can read. Only what differs is written. + fn provision(&self, _token: Option<&str>, _port: u16) -> Result<(), String> { + Ok(()) + } +} + +/// The client id of the LightCraft plugin for Logi Options+. +pub const LOGI_CLIENT: &str = "lightcraft-logi"; + +/// Zero setup for the plugin LightCraft knows how to install: when it is installed for this +/// user, control surfaces turn on by themselves (unless the user turned them off) and the plugin +/// is trusted at once, through a token in its data folder (no pairing code to compare). Runs +/// when the settings load, before the surface listener starts, and after an install. +pub fn auto_setup(app: &mut LightcraftApp) { + let Some(i) = installer(app) else { return }; + let status = i.status(); + app.surface.plugin.status = Some(status.clone()); + if status.installed.is_none() { + return; + } + let s = app.surface.settings(); + if s.off_by_user { + return; + } + if !s.enabled { + app.surface.runtime.settings_mut().enabled = true; + app.surface.changed(); + log::info!("control surfaces turned on: the Logi Options+ plugin is installed"); + } + let port = app.surface.settings().port; + let trusted = i.plugin_token().is_some_and(|t| ls::protocol::verify(app.surface.settings(), t.trim()).is_some_and(|c| c.client == LOGI_CLIENT)); + let token = if trusted { + None + } else { + let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let mut s = app.surface.settings().clone(); + let t = app.surface.pairing.trust(LOGI_CLIENT, "LightCraft plugin for Logi Options+", &mut s, now); + app.surface.runtime.settings_mut().paired = s.paired; + app.surface.changed(); + Some(t) + }; + if let Err(e) = i.provision(token.as_deref(), port) { + log::warn!("Logi plugin: {e}"); + app.surface.plugin.message = Some(Err(e)); + } +} + +/// An install or uninstall on its way. +pub struct PluginJob { + rx: Receiver>, + _guard: TaskGuard, + pub installing: bool, +} + +/// What Settings ▸ Controls shows about the plugin. +#[derive(Default)] +pub struct PluginState { + pub status: Option, + /// egui time of the last status check (s). + checked_at: f64, + pub job: Option, + /// The last install / uninstall result. + pub message: Option>, +} + +fn installer(app: &LightcraftApp) -> Option> { + app.services.surface_plugin.clone() +} + +/// Look at the plugin again (at most every 3 s unless `force`). +pub fn refresh(app: &mut LightcraftApp, force: bool) { + let now = app.surface.now(); + if !force && app.surface.plugin.status.is_some() && now - app.surface.plugin.checked_at < 3.0 { + return; + } + let Some(i) = installer(app) else { return }; + app.surface.plugin.status = Some(i.status()); + app.surface.plugin.checked_at = now; +} + +/// Start installing (`install`) or removing the plugin on a worker thread. +pub fn start(app: &mut LightcraftApp, install: bool) -> Result { + let Some(i) = installer(app) else { return Err("this LightCraft can't install surface plugins (desktop only)".into()) }; + if app.surface.plugin.job.is_some() { + return Err("the plugin is already being installed or removed".into()); + } + let status = i.status(); + if install && !status.can_install() { + return Err(match (&status.host, &status.package) { + (None, _) => "Logi Options+ isn't installed on this computer".into(), + _ => "this LightCraft has no plugin package with it (see docs/control-surfaces.md, Installing the plugin)".into(), + }); + } + let port = app.surface.listening.unwrap_or(app.surface.settings().port); + let label = if install { "Installing the surface plugin" } else { "Removing the surface plugin" }; + let guard = app.session.activity.start("surfacePlugin", label, Cancel::No); + guard.detail(&i.name()); + let (tx, rx) = channel(); + let repaint = app.tasks.repaint.clone(); + std::thread::Builder::new() + .name("surface-plugin".into()) + .spawn(move || { + let r = if install { i.install(port) } else { i.uninstall() }; + let _ = tx.send(r); + if let Some(c) = repaint { + c.request_repaint(); + } + }) + .map_err(|e| format!("can't start the installer: {e}"))?; + app.surface.plugin.message = None; + app.surface.plugin.job = Some(PluginJob { rx, _guard: guard, installing: install }); + Ok(json!({"started": true})) +} + +/// Once per frame: pick up a finished job. +pub fn poll(app: &mut LightcraftApp) { + let Some(job) = &app.surface.plugin.job else { return }; + let r = match job.rx.try_recv() { + Ok(r) => r, + Err(TryRecvError::Empty) => return, + Err(TryRecvError::Disconnected) => Err("the installer stopped without an answer".into()), + }; + let installed = job.installing && r.is_ok(); + app.surface.plugin.job = None; + app.surface.plugin.message = Some(r); + refresh(app, true); + if installed { + auto_setup(app); + } +} + +/// `surface.plugin*` commands; `None` for other ids. +pub fn command(app: &mut LightcraftApp, id: &str) -> Option> { + Some(match id { + "surface.plugin" => { + refresh(app, true); + let busy = app.surface.plugin.job.as_ref().map(|j| if j.installing { "installing" } else { "removing" }); + let message = match &app.surface.plugin.message { + Some(Ok(m)) => json!({"ok": true, "text": m}), + Some(Err(e)) => json!({"ok": false, "text": e}), + None => Value::Null, + }; + Ok(json!({"status": app.surface.plugin.status, "busy": busy, "message": message})) + } + "surface.installPlugin" => start(app, true), + "surface.uninstallPlugin" => start(app, false), + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn versions_compare_by_number() { + let s = |i: Option<&str>, p: Option<&str>| PluginStatus { + host: Some("Logi Options+".into()), + installed: i.map(str::to_string), + package: p.map(str::to_string), + package_path: None, + }; + assert!(s(Some("0.1.0"), Some("0.2.0")).update_available()); + assert!(s(Some("0.9.0"), Some("0.10.0")).update_available()); + assert!(!s(Some("0.2.0"), Some("0.2.0")).update_available()); + assert!(!s(None, Some("0.2.0")).update_available()); + assert!(s(None, Some("0.2.0")).can_install()); + assert!(!s(None, None).can_install()); + assert!(!PluginStatus { host: None, ..s(None, Some("1")) }.can_install()); + } +} diff --git a/crates/ui-egui/src/tests_surface.rs b/crates/ui-egui/src/tests_surface.rs new file mode 100644 index 00000000000..b1469004e8c --- /dev/null +++ b/crates/ui-egui/src/tests_surface.rs @@ -0,0 +1,685 @@ +//! Control surfaces in the app (`crate::surface`, Settings ▸ Controls, the on-screen readout). +//! +//! Scenarios, as a photographer with an MX Creative Console sees them: +//! +//! * The plugin asks to pair; LightCraft says so; I check the code and approve it in Settings ▸ +//! Controls; from then on the plugin connects with its token. Anything unpaired is refused. +//! * Turning the dial moves Exposure on the open photo, and the window shows the value. When I +//! stop turning, that turn is one undo step. +//! * With "Dials change every selected photo" on, the turn lands on every selected photo, still as +//! one undo step. +//! * Opening Crop puts the crop page on the keypad and Straighten on the dial. +//! * In Settings ▸ Controls I can press Learn, touch a key, and change what it does. +//! * My TactileBridge settings come over in one go; damaged files never crash anything. + +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::mpsc::{Receiver, channel}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use crate::control::ControlRequest; +use crate::headless::Headless; +use crate::state::{Dialog, RightPanel, ViewMode}; +use crate::surface::{EventSink, SurfaceStore}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +/// An in-memory settings file. +#[derive(Clone, Default)] +struct MemStore(Arc>>); + +impl SurfaceStore for MemStore { + fn load(&self) -> Result, String> { + Ok(self.0.lock().unwrap().clone()) + } + fn save(&self, text: &str) -> Result<(), String> { + *self.0.lock().unwrap() = Some(text.to_string()); + Ok(()) + } +} + +fn demo_with(store: MemStore, enabled: bool) -> Headless { + if enabled { + let s = lightcraft_surface::SurfaceSettings { enabled: true, ..Default::default() }; + store.save(&s.to_json()).unwrap(); + } + let services = Services { png: None, surface_store: Some(Box::new(store)), ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + h.settle(T); + h +} + +fn demo() -> Headless { + demo_with(MemStore::default(), true) +} + +/// A request on a TCP-like connection `conn` whose events go to `sink`. +fn request_on(h: &mut Headless, conn: u64, sink: &EventSink, method: &str, params: Value) -> Value { + let (req, rx) = ControlRequest::new(method, params); + let req = req.on_connection(conn, sink.clone()); + h.control_sender().send(req).unwrap(); + let t0 = Instant::now(); + loop { + h.step(); + if let Ok(v) = rx.try_recv() { + return v; + } + assert!(t0.elapsed() < T, "no reply to {method}"); + } +} + +fn sink() -> (EventSink, Receiver) { + let (tx, rx) = channel(); + (EventSink { tx, open: Arc::new(AtomicBool::new(true)) }, rx) +} + +fn exposure(h: &Headless) -> f64 { + let id = h.app.session.active().unwrap(); + h.app.session.develop_of(id).unwrap().light.exposure +} + +/// Open the first photo in Detail with the Edit panel. +fn open_photo(h: &mut Headless) { + let first = h.app.session.visible_cloned()[0]; + assert_eq!(h.request("engine.execute", json!({"command": "library.select", "params": {"ids": [first.0]}}), T)["ok"], true); + h.app.ui.view = ViewMode::Detail; + h.app.ui.right = RightPanel::Edit; + h.settle(T); +} + +/// Frames until the dial gesture has ended (the default 800 ms at 60 frames a second). +fn finish_gesture(h: &mut Headless) { + for _ in 0..70 { + h.step(); + } +} + +fn input(h: &mut Headless, events: Value) -> Value { + h.request("engine.execute", json!({"command": "surface.input", "params": {"events": events}}), T) +} + +#[test] +fn pairing_then_subscribe_and_turn_over_a_connection() { + let mut h = demo(); + open_photo(&mut h); + let (sink1, events1) = sink(); + // unpaired: hello says so, input and subscribe are refused + let r = request_on(&mut h, 7, &sink1, "surface.hello", json!({"protocol": 1, "client": "test"})); + assert_eq!(r["result"]["paired"], false, "{r}"); + let r = request_on(&mut h, 7, &sink1, "surface.input", json!({"events": [{"control": "dial", "ticks": 5}]})); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap().contains("isn't paired")); + // ask; Settings ▸ Controls shows the request with its code + let r = request_on(&mut h, 7, &sink1, "surface.pair", json!({"client": "test", "name": "Test Plugin"})); + assert_eq!(r["result"]["status"], "pending", "{r}"); + let (req, code) = (r["result"]["request"].as_str().unwrap().to_string(), r["result"]["code"].as_str().unwrap().to_string()); + assert_eq!(code.len(), 6); + h.app.ui.dialog = Some(Dialog::Settings { tab: "controls".into() }); + h.settle(T); + assert!(h.painted_text().iter().any(|t| t.contains(&code)), "the code is shown"); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceApprove-test"}), T)["ok"], true); + h.settle(T); + assert_eq!(h.app.surface.settings().paired.len(), 1); + let r = request_on(&mut h, 7, &sink1, "surface.pair", json!({"request": req})); + assert_eq!(r["result"]["status"], "approved", "{r}"); + let token = r["result"]["token"].as_str().unwrap().to_string(); + h.app.ui.dialog = None; + // a new connection presents the token + let (sink2, events2) = sink(); + let r = request_on(&mut h, 8, &sink2, "surface.hello", json!({"protocol": 1, "token": token})); + assert_eq!(r["result"]["paired"], true, "{r}"); + let r = request_on(&mut h, 9, &sink2, "surface.hello", json!({"token": "forged"})); + assert_eq!(r["result"]["paired"], false); + let r = request_on(&mut h, 8, &sink2, "surface.subscribe", json!({"device": "mx-creative-console"})); + assert_eq!(r["ok"], true, "{r}"); + let layout = &r["result"]["layout"]; + assert_eq!(layout["dials"][1]["binding"]["target"], "light.exposure"); + assert_eq!(layout["keys"].as_array().unwrap().len(), 9); + // turn the dial: exposure moves, the readout shows it, the plugin hears the new value + let before = exposure(&h); + let r = request_on(&mut h, 8, &sink2, "surface.input", json!({"events": [{"control": "roller", "ticks": 3}, {"control": "roller", "ticks": 2}]})); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..3 { + h.step(); + } + assert!(exposure(&h) > before, "{} > {before}", exposure(&h)); + assert!(h.painted_text().iter().any(|t| t == "Exposure"), "the on-screen readout"); + let pushed: Vec = events2.try_iter().collect(); + let last = pushed.iter().rev().find(|e| e["event"] == "surface.layout").unwrap_or_else(|| panic!("no layout pushed: {pushed:?}")); + let shown: f64 = last["layout"]["dials"][1]["value"].as_str().unwrap().trim_start_matches('+').parse().unwrap(); + assert!((shown - exposure(&h)).abs() < 0.006, "the pushed value is the photo's: {shown} vs {}", exposure(&h)); + // the first connection never subscribed: nothing pushed to it + assert!(events1.try_iter().next().is_none()); + // the turn is one undo step once it ends + finish_gesture(&mut h); + let after = exposure(&h); + assert_eq!(h.request("engine.execute", json!({"command": "edit.undo"}), T)["ok"], true); + assert!((exposure(&h) - before).abs() < 1e-9, "one undo puts the whole turn back: {} vs {before} (was {after})", exposure(&h)); + // forget it (the command Forget runs): the token stops working + assert_eq!(h.request("engine.execute", json!({"command": "surface.forget", "params": {"client": "nobody"}}), T)["ok"], false); + assert_eq!(h.request("engine.execute", json!({"command": "surface.forget", "params": {"client": "test"}}), T)["ok"], true); + let r = request_on(&mut h, 10, &sink2, "surface.hello", json!({"token": token})); + assert_eq!(r["result"]["paired"], false); +} + +#[test] +fn apply_to_selected_changes_every_selected_photo_in_one_step() { + let mut h = demo(); + open_photo(&mut h); + let ids: Vec = h.app.session.visible_cloned().iter().take(3).map(|p| p.0).collect(); + assert_eq!(h.request("engine.execute", json!({"command": "library.select", "params": {"ids": ids}}), T)["ok"], true); + h.settle(T); + let r = h.request("engine.execute", json!({"command": "surface.applyToSelected", "params": {"on": true}}), T); + assert_eq!(r["result"]["on"], true, "{r}"); + let exp = |h: &Headless, id: u64| h.app.session.develop_of(lightcraft_catalog::PhotoId(id)).unwrap().light.exposure; + let before: Vec = ids.iter().map(|i| exp(&h, *i)).collect(); + assert_eq!(input(&mut h, json!([{"control": "roller", "ticks": 10}]))["ok"], true); + finish_gesture(&mut h); + for (i, id) in ids.iter().enumerate() { + assert!((exp(&h, *id) - before[i] - 0.10).abs() < 1e-6, "photo {id}: {} vs {}", exp(&h, *id), before[i]); + } + assert_eq!(h.request("engine.execute", json!({"command": "edit.undo"}), T)["ok"], true); + for (i, id) in ids.iter().enumerate() { + assert!((exp(&h, *id) - before[i]).abs() < 1e-9, "one undo step for all"); + } +} + +#[test] +fn pages_follow_crop_and_keys_run_commands() { + let mut h = demo(); + open_photo(&mut h); + let state = |h: &mut Headless| h.request("engine.execute", json!({"command": "surface.state"}), T)["result"].clone(); + let s = state(&mut h); + assert_eq!((s["keyPage"].as_str(), s["dialPage"].as_str()), (Some("Page 1"), Some("Dial Page")), "{s}"); + assert!(s["context"].as_str().unwrap().starts_with("develop"), "{s}"); + h.app.ui.right = RightPanel::Crop; + h.settle(T); + let s = state(&mut h); + assert_eq!((s["context"].as_str(), s["keyPage"].as_str(), s["dialPage"].as_str()), (Some("crop"), Some("Crop"), Some("Crop")), "{s}"); + // the dial straightens + assert_eq!(input(&mut h, json!([{"control": "dial", "ticks": 50}]))["ok"], true); + finish_gesture(&mut h); + let id = h.app.session.active().unwrap(); + assert!(h.app.session.develop_of(id).unwrap().crop.geometry.angle.abs() > 0.1); + // back to Edit: the hand-picked pages come back + h.app.ui.right = RightPanel::Edit; + h.settle(T); + assert_eq!(state(&mut h)["keyPage"], "Page 1"); + // a key runs its command: Page 1, key 2 = Next photo + let before = h.app.session.active(); + assert_eq!(input(&mut h, json!([{"control": "key.2", "press": true}, {"control": "key.2", "press": false}]))["ok"], true); + h.settle(T); + assert_ne!(h.app.session.active(), before); + // the dialpad's fourth button turns the dial page + assert_eq!(input(&mut h, json!([{"control": "pad.4", "press": true}]))["ok"], true); + assert_eq!(state(&mut h)["dialPage"], "White Balance"); +} + +#[test] +fn settings_tab_learn_and_edit_a_key() { + let store = MemStore::default(); + let mut h = demo_with(store.clone(), true); + open_photo(&mut h); + assert_eq!(h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": "controls"}}), T)["ok"], true); + // the drawn device and its editor: Edit Keys and Dials… in Settings ▸ Controls + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceEditKeys"}), T)["ok"], true); + h.settle(T); + h.settle(T); + for id in [ + "button:surfaceControl-key.1", + "button:surfaceDevice-dialpad", + "button:surfaceSection-feel", + "check:surface.touchFind", + "check:surface.enabled", + "combo:surfaceProfile", + ] { + assert!(h.app.widgets.iter().any(|(w, _)| w == id), "{id}"); + } + // Touch to find (on while this page is open): touch key 5 on the surface: it is selected, + // and nothing runs + let clip = h.app.widgets.iter().find(|(w, _)| w == "check:surface.touchFind").map(|(_, r)| *r).unwrap(); + assert!(clip.bottom() < 900.0, "Touch to find is on screen: {clip:?}"); + assert!(h.app.surface.runtime.learning()); + let before = h.app.session.active(); + assert_eq!(input(&mut h, json!([{"control": "key.5", "press": true}]))["ok"], true); + h.settle(T); + assert_eq!(h.app.surface.editor.control.as_deref(), Some("key.5")); + assert_eq!(h.app.session.active(), before, "a learnt press doesn't act"); + assert!(h.app.widgets.iter().any(|(w, _)| w == "field:surfaceActionSearch"), "the selected key's editor"); + // touching a dial switches the drawing to the Dialpad, and the photo doesn't change + let exposure_before = exposure(&h); + assert_eq!(input(&mut h, json!([{"control": "dial", "ticks": 1}]))["ok"], true); + assert_eq!(input(&mut h, json!([{"control": "dial", "ticks": 3}]))["ok"], true); + h.settle(T); + assert_eq!(h.app.surface.editor.device, "dialpad"); + assert_eq!(h.app.surface.editor.control.as_deref(), Some("dial")); + assert_eq!(exposure(&h), exposure_before, "a touched dial is found, not turned"); + assert!(h.app.widgets.iter().any(|(w, _)| w == "button:surfaceControl-dial"), "the Dialpad is drawn"); + // pick an action from the list: search, click + h.app.surface.editor.filter = "Highlights".into(); + h.settle(T); + assert_eq!(h.request("ui.clickWidget", json!({"id": "item:surfaceAction-v.light.highlights"}), T)["ok"], true); + h.settle(T); + let p = h.app.surface.settings().active_profile().unwrap().clone(); + assert!( + p.pages.iter().any(|pg| pg.bindings.get("dial") == Some(&lightcraft_surface::Binding::value("light.highlights"))), + "the dial moves Highlights now" + ); + // the other sections open + for s in ["pages", "feel", "readout", "setup"] { + assert_eq!(h.request("ui.clickWidget", json!({"id": format!("button:surfaceSection-{s}")}), T)["ok"], true); + h.settle(T); + } + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceDevice-keypad"}), T)["ok"], true); + h.settle(T); + // make key 5 put Contrast on the dial + let profile = h.app.surface.settings().profile.clone(); + let mut s = h.app.surface.settings().clone(); + let page = s.profiles.iter_mut().find(|p| p.name == profile).unwrap().pages.iter_mut().find(|p| p.name == "Page 1").unwrap(); + page.bindings.insert("key.5".into(), lightcraft_surface::Binding::value("light.contrast")); + assert_eq!(h.request("engine.execute", json!({"command": "surface.settings", "params": {"settings": s}}), T)["ok"], true); + h.settle(T); + assert!(h.painted_text().iter().any(|t| t == "Contrast"), "the key shows its new label"); + h.app.ui.dialog = None; + // (the keypad follows the dialog's page until the next frame; Touch to find ends with the page) + h.settle(T); + for _ in 0..40 { + h.step(); + } + assert!(!h.app.surface.runtime.learning(), "Touch to find stopped with the page"); + // press it: the dial moves Contrast until pressed again + assert_eq!(input(&mut h, json!([{"control": "key.5", "press": true}, {"control": "dial", "ticks": 4}]))["ok"], true); + finish_gesture(&mut h); + let id = h.app.session.active().unwrap(); + assert!(h.app.session.develop_of(id).unwrap().light.contrast > 0.0); + // saved + for _ in 0..40 { + h.step(); + } + assert!(store.load().unwrap().unwrap().contains("light.contrast")); +} + +#[test] +fn tactilebridge_settings_import_and_damaged_files() { + let dir = std::env::temp_dir().join(format!("lc-surface-tb-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("settings.json"); + std::fs::write( + &path, + r##"{"controls": {"globalSpeedMultiplier": 1.2, "adjustmentProfiles": {"Kelvin": {"speedMultiplier": 0.3}}}, + "osd": {"opacity": 0.6, "position": "Up"}, + "toolContext": {"contexts": {"Crop": {"buttons": ["SwitchCropOrientation"], "encoders": ["Zoom"]}}}}"##, + ) + .unwrap(); + let mut h = demo(); + let r = h.request("engine.execute", json!({"command": "surface.import", "params": {"path": path.to_string_lossy()}}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["profile"], "TactileBridge"); + let s = h.app.surface.settings(); + assert_eq!((s.motion.speed, s.tuning["wb.temp"].speed, s.osd.opacity), (1.2, 0.3, 0.6)); + assert!(r["result"]["report"]["mapped"].as_array().unwrap().len() > 3); + // junk is an error, not a crash + std::fs::write(&path, "{not json").unwrap(); + let r = h.request("engine.execute", json!({"command": "surface.import", "params": {"path": path.to_string_lossy()}}), T); + assert_eq!(r["ok"], false); + let r = h.request("engine.execute", json!({"command": "surface.import", "params": {"path": dir.join("missing.lp5").to_string_lossy()}}), T); + assert_eq!(r["ok"], false); + let _ = std::fs::remove_dir_all(&dir); + // a damaged settings file: defaults, a notice, the file kept until something changes + let store = MemStore::default(); + store.save("{ damaged").unwrap(); + let services = Services { png: None, surface_store: Some(Box::new(store.clone())), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1000.0, 700.0], 1.0); + h.settle(T); + assert!(h.app.surface.load_error.is_some()); + assert_eq!(store.load().unwrap().as_deref(), Some("{ damaged")); +} + +#[test] +fn surfaces_are_off_until_turned_on_and_hostile_input_is_refused() { + let mut h = demo_with(MemStore::default(), false); + let (sink1, _rx) = sink(); + let r = request_on(&mut h, 3, &sink1, "surface.subscribe", json!({})); + assert!(r["error"].as_str().unwrap().contains("switched off"), "{r}"); + h.app.surface.runtime.settings_mut().enabled = true; + for bad in [ + json!({}), + json!({"events": 5}), + json!({"events": [{"control": "dial"}]}), + json!({"events": [{"ticks": 1}]}), + json!({"events": [{"control": "dial", "ticks": "x"}]}), + ] { + let r = h.request("engine.execute", json!({"command": "surface.input", "params": bad}), T); + assert_eq!(r["ok"], false, "{r}"); + } + let many: Vec = (0..300).map(|_| json!({"control": "dial", "ticks": 1})).collect(); + assert_eq!(input(&mut h, Value::Array(many))["ok"], false); + let r = input(&mut h, json!([{"control": "dial", "ticks": 1e300}, {"control": "key.1", "press": true, "page": 99999}])); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + let r = h.request("surface.icons", json!({"names": ["exposure", "nope"]}), T); + assert!(r["result"]["exposure"].as_str().unwrap().contains(" 5); + // turning an action from the plugin's own list moves that value, one undo step per turn + let before = exposure(&h); + let r = request_on(&mut h, 0, &s, "surface.input", json!({"events": [{"action": "v.light.exposure", "ticks": 4}]})); + assert_eq!(r["ok"], true, "{r}"); + for _ in 0..3 { + h.step(); + } + assert!(exposure(&h) > before); + finish_gesture(&mut h); + // pressing it resets it + request_on( + &mut h, + 0, + &s, + "surface.input", + json!({"events": [{"action": "v.light.exposure", "press": true}, {"action": "v.light.exposure", "press": false}]}), + ); + h.settle(T); + assert!(exposure(&h).abs() < 1e-9, "{}", exposure(&h)); + // unknown actions are refused, not guessed + let r = request_on(&mut h, 0, &s, "surface.input", json!({"events": [{"action": "v.nope", "ticks": 1}]})); + assert_eq!(r["ok"], false, "{r}"); + // watched values come with the layout + let r = request_on(&mut h, 0, &s, "surface.watch", json!({"targets": ["light.contrast"]})); + assert_eq!(r["ok"], false, "subscribe first: {r}"); + assert_eq!(request_on(&mut h, 0, &s, "surface.subscribe", json!({}))["ok"], true); + let r = request_on(&mut h, 0, &s, "surface.watch", json!({"targets": ["light.contrast", "nope"]})); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + let pushed: Vec = events.try_iter().collect(); + let last = pushed.iter().rev().find(|e| e["event"] == "surface.layout").expect("a layout with values"); + assert_eq!(last["layout"]["values"]["light.contrast"]["value"], "0", "{last}"); + assert!(last["layout"]["values"].get("nope").is_none()); +} + +/// A Logi Options+ install with the LightCraft plugin, in memory: its data folder's token and port. +#[derive(Default)] +struct FakeLogi { + token: std::sync::Mutex>, + port: std::sync::Mutex>, +} + +impl crate::surface_plugin::PluginInstaller for FakeLogi { + fn name(&self) -> String { + "test plugin".into() + } + fn status(&self) -> crate::surface_plugin::PluginStatus { + crate::surface_plugin::PluginStatus { host: Some("Logi Options+".into()), installed: Some("1.0.2".into()), package: None, package_path: None } + } + fn install(&self, _port: u16) -> Result { + Ok(String::new()) + } + fn uninstall(&self) -> Result { + Ok(String::new()) + } + fn plugin_token(&self) -> Option { + self.token.lock().unwrap().clone() + } + fn provision(&self, token: Option<&str>, port: u16) -> Result<(), String> { + if let Some(t) = token { + *self.token.lock().unwrap() = Some(t.to_string()); + } + *self.port.lock().unwrap() = Some(port); + Ok(()) + } +} + +#[test] +fn an_installed_logi_plugin_works_with_no_setup_and_settings_show_the_edited_page() { + // first run: no settings file, the plugin installed + let store = MemStore::default(); + let logi = Arc::new(FakeLogi::default()); + let services = Services { png: None, surface_store: Some(Box::new(store.clone())), surface_plugin: Some(logi.clone()), ..Default::default() }; + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + let mut h = Headless::new(app, [1400.0, 900.0], 1.0); + h.settle(T); + open_photo(&mut h); + assert!(h.app.surface.settings().enabled, "on by itself"); + let token = logi.token.lock().unwrap().clone().expect("the plugin got a token"); + assert_eq!(*logi.port.lock().unwrap(), Some(lightcraft_surface::settings::DEFAULT_PORT)); + for _ in 0..40 { + h.step(); + } + assert!(store.load().unwrap().unwrap().contains("lightcraft-logi"), "trusted and saved"); + // the plugin connects with it: paired at once, no code to approve + let (s, events) = sink(); + let r = request_on(&mut h, 31, &s, "surface.hello", json!({"protocol": 1, "client": "lightcraft-logi", "token": token})); + assert_eq!(r["result"]["paired"], true, "{r}"); + assert_eq!(request_on(&mut h, 31, &s, "surface.subscribe", json!({}))["ok"], true); + assert_eq!(h.app.surface.pairing.waiting().count(), 0); + // a second start keeps the same token (nothing rewritten) + crate::surface_plugin::auto_setup(&mut h.app); + assert_eq!(logi.token.lock().unwrap().as_deref(), Some(token.as_str())); + // a dialog doesn't take over the keys (dialog pages are opt-in) + let page_before = h.app.surface.runtime.pages().clone(); + h.app.ui.dialog = Some(Dialog::Settings { tab: "general".into() }); + h.settle(T); + assert!(!h.app.surface.runtime.context().starts_with("dialog"), "{}", h.app.surface.runtime.context()); + assert_eq!(h.app.surface.runtime.pages(), &page_before); + // Settings ▸ Controls shows the device the page being edited, live + h.app.ui.dialog = Some(Dialog::Settings { tab: "controls".into() }); + h.app.surface.editor.window = true; + h.app.surface.editor.page = Some("Page 2".into()); + h.settle(T); + assert_eq!(h.app.surface.runtime.pages().get(&lightcraft_surface::PageGroup::Keys).map(String::as_str), Some("Page 2")); + let pushed: Vec = events.try_iter().collect(); + let last = pushed.iter().rev().find(|e| e["event"] == "surface.layout").expect("pushed"); + assert_eq!(last["layout"]["keyPage"], "Page 2", "the console follows the editor"); + // turned off by the user: stays off on the next start (the Keys and Dials window closed, so + // the Settings page under it takes the click) + h.app.surface.editor.window = false; + h.settle(T); + assert_eq!(h.request("ui.clickWidget", json!({"id": "check:surface.enabled"}), T)["ok"], true); + h.settle(T); + assert!(!h.app.surface.settings().enabled && h.app.surface.settings().off_by_user); + crate::surface_plugin::auto_setup(&mut h.app); + assert!(!h.app.surface.settings().enabled, "off stays off"); +} + +/// Bind `control` on the key page now showing. +fn bind_key(h: &mut Headless, control: &str, b: lightcraft_surface::Binding) { + let page = h.app.surface.runtime.pages().get(&lightcraft_surface::PageGroup::Keys).cloned().unwrap(); + let s = h.app.surface.runtime.settings_mut(); + let cur = s.profile.clone(); + let p = s.profiles.iter_mut().find(|p| p.name == cur).unwrap(); + p.pages.iter_mut().find(|q| q.name == page).unwrap().bindings.insert(control.into(), b); +} + +#[test] +fn console_erase_works_while_held_and_delete_needs_a_hold() { + use lightcraft_surface::Binding; + let mut h = demo(); + open_photo(&mut h); + bind_key(&mut h, "key.1", Binding::command("brush.erase")); + bind_key(&mut h, "key.4", Binding::command_with("tool.brush", json!({"new": true}))); + // Erase: on while the key is down (the brush comes up with it), off when it is let go + assert_eq!(input(&mut h, json!([{"control": "key.1", "press": true}]))["ok"], true); + h.settle(T); + assert!(h.app.ui.brush_erase, "erasing while held"); + assert_eq!(h.app.ui.tool, "brush"); + assert_eq!(input(&mut h, json!([{"control": "key.1", "press": false}]))["ok"], true); + h.settle(T); + assert!(!h.app.ui.brush_erase, "back to painting when let go"); + // New Brush runs once and is never lit + assert_eq!(input(&mut h, json!([{"control": "key.4", "press": true}, {"control": "key.4", "press": false}]))["ok"], true); + h.settle(T); + let layout = serde_json::to_value(crate::surface::layout(&h.app, &lightcraft_surface::devices::MX_CREATIVE_CONSOLE)).unwrap(); + let keys = layout["keys"].as_array().cloned().unwrap_or_default(); + let new_brush = keys.iter().find(|k| k["control"] == "key.4").cloned().unwrap_or_default(); + assert_ne!(new_brush["active"], true, "{new_brush}"); + // Delete (on the everyday page, the brush put away): a quick press does nothing but say to + // hold the key + assert_eq!(h.request("engine.execute", json!({"command": "tool.done"}), T)["ok"], true); + h.settle(T); + bind_key(&mut h, "key.3", Binding::command("photo.delete")); + let n = h.app.session.visible_cloned().len(); + assert_eq!(input(&mut h, json!([{"control": "key.3", "press": true}, {"control": "key.3", "press": false}]))["ok"], true); + let osd = h.request("engine.execute", json!({"command": "surface.state"}), T)["result"]["osd"].clone(); + assert!(osd["notice"].as_str().is_some_and(|t| t.starts_with("Hold the key")), "{osd}"); + h.settle(T); + assert_eq!(h.app.session.visible_cloned().len(), n, "a quick press deletes nothing"); + // held for a moment: it runs + assert_eq!(input(&mut h, json!([{"control": "key.3", "press": true}]))["ok"], true); + for _ in 0..60 { + h.step(); + } + assert_eq!(input(&mut h, json!([{"control": "key.3", "press": false}]))["ok"], true); + h.settle(T); + assert_eq!(h.app.session.visible_cloned().len(), n - 1, "held: deleted"); +} + +#[test] +fn a_loupedeck_plus_works_as_labelled_and_takes_a_loupedeck_profile() { + let mut h = demo(); + open_photo(&mut h); + // no setup: the knob labelled Exposure moves Exposure + let before = exposure(&h); + assert_eq!(input(&mut h, json!([{"control": "ld.r33", "ticks": 20}]))["ok"], true); + finish_gesture(&mut h); + assert!(exposure(&h) > before, "the Exposure knob"); + // a Loupedeck profile: that knob now moves Temperature, Undo stays on its button + let dir = std::env::temp_dir().join(format!("lc-surface-ld-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("ProfileInfo.json"); + let mut rotate = vec![Value::Null; 127]; + rotate[33] = json!("$Photo___Temperature"); + let mut press = vec![Value::Null; 127]; + press[95] = json!("$Photo___Undo"); + press[76] = json!("$@Generic___@Macro___0123"); + let profile = json!({"displayName": "Mine", "deviceType": "Loupedeck15", "layout": {"layoutModes": [ + {"modeName": "loupe", "workspaces": [{"pressActions": press, "rotateActions": rotate}]}]}}); + std::fs::write(&path, profile.to_string()).unwrap(); + let r = h.request("engine.execute", json!({"command": "surface.import", "params": {"path": path.to_string_lossy()}}), T); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["device"], "loupedeck-plus"); + assert_eq!(r["result"]["report"]["dropped"].as_array().map(Vec::len), Some(1), "the macro is listed as left out"); + for p in &h.app.surface.settings().profiles { + assert_eq!(p.base.get("ld.r33"), Some(&lightcraft_surface::Binding::value("wb.temp")), "{}", p.name); + } + let id = h.app.session.active().unwrap(); + let (exp, temp) = { + let d = h.app.session.develop_of(id).unwrap(); + (d.light.exposure, d.wb.temp) + }; + assert_eq!(input(&mut h, json!([{"control": "ld.r33", "ticks": 20}]))["ok"], true); + finish_gesture(&mut h); + let d = h.app.session.develop_of(id).unwrap(); + assert_eq!(d.light.exposure, exp); + assert_ne!(d.wb.temp, temp); + // a damaged Loupedeck profile is an error, not a crash + std::fs::write(&path, r#"{"deviceType": "Loupedeck15", "layout": 7}"#).unwrap(); + let r = h.request("engine.execute", json!({"command": "surface.import", "params": {"path": path.to_string_lossy()}}), T); + assert_eq!(r["ok"], false); + let _ = std::fs::remove_dir_all(&dir); +} + +fn widget(h: &Headless, id: &str) -> egui::Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("{id} is drawn")) +} + +#[test] +fn the_dialpad_is_drawn_like_the_device() { + let mut h = demo(); + assert_eq!(h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": "controls"}}), T)["ok"], true); + // the drawn device and its editor: Edit Keys and Dials… in Settings ▸ Controls + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceEditKeys"}), T)["ok"], true); + h.settle(T); + h.app.surface.editor.device = "dialpad".into(); + h.settle(T); + let r = |id: &str| widget(&h, &format!("button:surfaceControl-{id}")); + let (b1, b2, roller, dial, b3, b4) = (r("pad.1"), r("pad.2"), r("roller"), r("dial"), r("pad.3"), r("pad.4")); + // buttons 1 and 2 top left, the roller top right + assert!(b1.center().x < b2.center().x && b2.center().x < roller.center().x, "{b1:?} {b2:?} {roller:?}"); + assert!((b1.center().y - b2.center().y).abs() < 2.0 && (b2.center().y - roller.center().y).abs() < 4.0); + assert!(roller.width() > roller.height(), "the roller is a horizontal wheel"); + // the big dial in the middle, the biggest control + assert!(dial.top() > b1.bottom() && dial.bottom() < b3.bottom(), "{dial:?}"); + assert!(dial.width() > 2.0 * b1.width()); + // button 3 bottom left, button 4 bottom right + assert!(b3.center().x < dial.center().x && b4.center().x > dial.center().x); + assert!((b3.center().y - b4.center().y).abs() < 2.0 && b3.top() > dial.center().y); + for a in [b1, b2, roller, dial, b3, b4] { + for b in [b1, b2, roller, dial, b3, b4] { + if a != b { + assert!(!a.shrink(1.0).intersects(b.shrink(1.0)), "controls don't overlap: {a:?} {b:?}"); + } + } + } +} + +#[test] +fn the_actions_ring_takes_actions_dragged_onto_its_slots() { + let mut h = demo(); + assert_eq!(h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": "controls"}}), T)["ok"], true); + // the drawn device and its editor: Edit Keys and Dials… in Settings ▸ Controls + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceEditKeys"}), T)["ok"], true); + h.settle(T); + h.settle(T); + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceDevice-ring"}), T)["ok"], true); + h.settle(T); + // eight slots around a ring, with the built-in actions + let slots: Vec = (1..=8).map(|i| widget(&h, &format!("button:surfaceControl-ring.{i}"))).collect(); + let centre = slots.iter().fold(egui::Vec2::ZERO, |a, r| a + r.center().to_vec2()) / 8.0; + let radii: Vec = slots.iter().map(|r| (r.center().to_vec2() - centre).length()).collect(); + assert!(radii.iter().all(|r| (r - radii[0]).abs() < 2.0 && *r > 40.0), "on a circle: {radii:?}"); + assert!(slots[0].center().y < centre.y - 30.0, "slot 1 at the top"); + let base = |h: &Headless, c: &str| h.app.surface.settings().active_profile().unwrap().base.get(c).cloned(); + assert_eq!(base(&h, "ring.1"), Some(lightcraft_surface::Binding::command("edit.undo")), "zero setup: the ring has actions"); + // drag "Next photo"-like action from the list onto slot 3 + h.app.surface.editor.filter = "Highlights".into(); + h.settle(T); + let item = "item:surfaceAction-v.light.highlights"; + let to = widget(&h, "button:surfaceControl-ring.3").center(); + let r = h.request("ui.dragWidget", json!({"id": item, "toX": to.x, "toY": to.y, "steps": 12}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + assert_eq!(base(&h, "ring.3"), Some(lightcraft_surface::Binding::value("light.highlights")), "dropped on slot 3"); + assert_eq!(h.app.surface.editor.control.as_deref(), Some("ring.3"), "and selected"); + // the plugin sees the ring's slots in the layout + let layout = serde_json::to_value(crate::surface::layout(&h.app, &lightcraft_surface::devices::MX_CREATIVE_CONSOLE)).unwrap(); + let buttons = layout["buttons"].as_array().cloned().unwrap_or_default(); + assert!(buttons.iter().any(|b| b["control"] == "ring.3" && b["binding"]["target"] == "light.highlights"), "{layout}"); +} + +#[test] +fn a_dial_refuses_a_one_press_action_dropped_on_it() { + let mut h = demo(); + assert_eq!(h.request("engine.execute", json!({"command": "app.settings", "params": {"tab": "controls"}}), T)["ok"], true); + // the drawn device and its editor: Edit Keys and Dials… in Settings ▸ Controls + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceEditKeys"}), T)["ok"], true); + h.settle(T); + h.app.surface.editor.device = "dialpad".into(); + h.app.surface.editor.control = Some("pad.1".into()); + h.app.surface.editor.filter = "edit.undo".into(); + h.settle(T); + let before = h.app.surface.settings().clone(); + let key = lightcraft_surface::catalog::key_of(&lightcraft_surface::Binding::command("edit.undo")); + let to = widget(&h, "button:surfaceControl-dial").center(); + let r = h.request("ui.dragWidget", json!({"id": format!("item:surfaceAction-{key}"), "toX": to.x, "toY": to.y, "steps": 12}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + assert_eq!(*h.app.surface.settings(), before, "nothing changed"); + assert!(h.app.surface.editor.message.as_deref().is_some_and(|m| m.contains("dial")), "{:?}", h.app.surface.editor.message); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a9020892f27..5f4ff527b5e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -109,6 +109,7 @@ filmstrip is visible. | `engine.execute {command: "slideshow.exportStatus"}` | — | The last slideshow export: `{taskId, format, path, running, done, total, cancelled, result?, error?}`; `result` has `pages` (PDF), `files` (JPEG) or `frames`, `samples`, `keyFrames`, `seconds`, `fps`, `container`, `codec: "av1"`, `audio: false` (video), and `skipped` / `warnings` for photos that could not be rendered | | `engine.execute {command: "dialog.slideshowExport"}` / `app.slideshowExport` | `{format?}` / `{format, size?, quality?, fps?, container?, fullScreen?, path?}` | View ▸ Export Slideshow…: opens the dialog; `app.slideshowExport` asks for the path with a save dialog when none is given, then starts `slideshow.export` | | `app.quit` | — | Close the app | +| `surface.hello` / `surface.pair` / `surface.icons` / `surface.catalog` / `surface.subscribe` / `surface.unsubscribe` / `surface.layout` / `surface.watch` / `surface.input` | see [control-surfaces.md](control-surfaces.md#the-surface-protocol) | Control surfaces: pairing (approved in Settings ▸ Controls), a device layout pushed as `surface.layout` events between replies, dial ticks and key presses. Everything but `hello`, `pair`, `icons` and `catalog` needs a paired connection; the control-surface port (Settings ▸ Controls, `7981`) serves only these | White balance (`develop.set` with `wb.temp` / `wb.tint`, `develop.wb`, `develop.wbPick`) is in Kelvin and tint on raws with colour matrices — in the file (DNG) or measured for the camera model (`lightcraft_raw::spectral`; issue @@ -278,7 +279,8 @@ Replies use `{id, ok, result}` or `{id, ok: false, error}`. In the photo snapsho Local mask adjustments are in the photo snapshot's `develop.masks`; use the mask commands from the registry (e.g. `mask.adjust`) for those, rather than treating global control values as mask values. -Feedback uses polling: the channel sends replies to requests, with no unsolicited change events. +Feedback uses polling: the channel sends replies to requests, with no unsolicited change events (except to a +paired control surface that subscribed to its layout: [control-surfaces.md](control-surfaces.md)). Compare successive `photo.inspect` snapshots for photo-id or develop-setting changes, including GUI edits, photo navigation, presets and undo/redo. GUI slider updates are visible while a drag is in progress; ending a changed interaction commits it as one undo step (unchanged drags add none). diff --git a/docs/control-surfaces.md b/docs/control-surfaces.md new file mode 100644 index 00000000000..8baff5d7bde --- /dev/null +++ b/docs/control-surfaces.md @@ -0,0 +1,663 @@ +# Control surfaces + +> **Last reviewed:** 2026-10-16 · **Last updated:** 2026-10-25 · **Change:** minor (Keys and Dials in a window of its own, opened from Settings ▸ Controls, which follows the Settings window's one size; the Dialpad drawn as the device; the Actions Ring set up in LightCraft with drag and drop; Touch to find; the Loupedeck+ drawn by zones and set up with no driver steps); previously minor (Erase while held; destructive keys need a hold; no Delete on built-in layouts; lit keys say why they are lit) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 + +Hardware dials, keys and buttons that drive LightCraft: the **Logitech MX Creative Console** (Keypad + Dialpad) first, +MIDI controllers and Tangent panels later. LightCraft owns the whole engine — layouts, what each control does, dial +speed and acceleration, pages that follow the tool you use, one undo step per dial turn, the on-screen readout — and a +thin plugin on the device's side only forwards ticks and presses and draws what LightCraft sends. + +The engine is a port of **TactileBridge**, its author's own (never released) Capture One bridge for the MX Creative +Console, contributed under the MIT licence: Portions © RAD Films - Roman Alurkoff (from TactileBridge), MIT. Its +code, settings design, layouts, tuning values and hand-drawn icon pack came over; nothing specific to Capture One did +(no Capture One control lists, no reading of Capture One's files, no Tangent hub impersonation, no screen scraping for +the active tool, no simulated keystrokes): LightCraft knows its own state. + +Code: [`crates/surface`](../crates/surface) (`lightcraft-surface`, L2, no UI), `crates/ui-egui/src/surface.rs` (the +app side), `crates/ui-egui/src/panels/controls.rs` (Settings ▸ Controls), `crates/ui-egui/src/panels/surface_osd.rs` +(the readout), `apps/lightcraft/src/control_server.rs` (the transport). The MX Creative Console plugin lives in its own +repository (`lightcraft-logi`, a Logi Actions SDK plugin in C#). + +## Using it + +1. **Settings ▸ Controls ▸ Use control surfaces.** LightCraft then listens on `127.0.0.1:7981` (the **Port** field + under *Profiles and Setup*; loopback only) for surfaces. Off by default. +2. Install the surface's plugin. MX Creative Console: when Logi Options+ is on the computer and the plugin isn't, + Settings ▸ Controls says so with an **Install the plugin** button (also under *Profiles and Setup*, with Update and + Remove). LightCraft hands its copy of the plugin to Logi's own installer; **Logi Options+ asks you to confirm** + ("Ready to install plugins" → Continue), installs it with its default profiles and reloads its plugin service by + itself — a few seconds in which the console pauses. See [Installing the plugin](#installing-the-logi-plugin). +3. The plugin asks to pair: LightCraft shows "… asks to control LightCraft" and lists the request in Settings ▸ + Controls with a six-digit code; the keypad shows the same code. Check they match and click **Approve**. The plugin + keeps the token it gets; **Forget** under *Paired* revokes it. +4. Pick a **profile** (Default, Wedding, Portrait, Fashion, Landscape, Real Estate, or your own). + +What happens then: + +- **Dials** move develop values (Exposure, Temp, a mask's sliders, the brush size, the zoom…). Ticks are gathered and + applied once per *Apply movement every* (16 ms); turning fast accelerates on TactileBridge's curve. A turn is **one + undo step**: it ends when the dial rests for *Turn ends after* (800 ms), when another dial starts, when a key runs a + command, or when the photo changes. +- **Apply to Selected** (a key, or *Dials change every selected photo*) carries each turn to every selected photo, + in that same single undo step (LightCraft's Auto Sync at the end of the gesture). This is TactileBridge's Auto Sync + without the copy-and-paste round trip. +- **Keys** run commands (any engine or UI command, with parameters), switch pages or profiles, hold a modifier + (*fine* ¼× / *big* 4× steps while held), reset the dial's value, or — bound to a value — put that value on the dial + until pressed again (TactileBridge's adjustment dial toggle). A dial press resets its value. +- **Pages.** A profile's pages bind controls; keys and dials page separately (the Keypad and the Dialpad), and + controls a page leaves free fall back to the profile's base bindings (the Dialpad's buttons). The MX Creative + Keypad's own page buttons show key pages 1–3; the Dialpad's fourth button turns the dial pages in the built-in + profiles. +- **Pages follow the app** (TactileBridge's tool switching): Crop puts the crop page on the keypad and Straighten on + the dial; Masking shows mask tools, a selected mask its sliders, its brush the brush size and feather; Remove the + spot size; a dialog OK / Cancel. Leaving the tool brings back the page you chose. Any page can be mapped to any + context in Settings ▸ Controls ▸ *Pages that follow the app*. +- **The on-screen readout** (TactileBridge's OSD) shows the value being turned (name, value, a bar) or the command a + key ran, at the top or bottom of the photo, with its opacity, colour and display time (`panels::surface_osd`; + Settings ▸ Controls ▸ Readout and Look). +- **The surface** shows each key's icon (TactileBridge's hand-drawn pack), label and live value. A key is lit for one + of three reasons, each drawn its own way by the plugin: its value is on the dial (`focus`: the white key), it is + held down (`held`: a held modifier, or Erase), or a mode it switches is on (`on`: the brush, Before / After, Auto + Sync …). One-shot keys (New Brush, Add / Subtract) are never lit. +- **Own icons** for functions that shared one of the pack's generic drawings (Invert Mask, Erase, New Brush, + Previous / Next Mask, Mask On/Off, Zoom To Fit, Zoom 100%, Select All / None, Rotate Left / Right, Reset): drawn + for LightCraft in the pack's style, next to the pack's originals, which stay as they are. +- **Erase works while held**, like Alt with the brush: `cmd:brush.erase` with `{on}` (a console key sends on at the + press and off at the release; without `on` it toggles). The brush page has it, plus Brush Size and Feather keys. +- **Destructive keys need a hold.** Delete, Delete Permanently, Clear History, Delete All Masks, Reset, deleting a + version or a preset run from a console key only after it is held for 0.7 s; a quick press runs nothing and the + readout says *Hold the key: …*. The built-in layouts have no Delete key (their old Delete key clears the colour + label). Deleting photos, from anywhere, says they went to Recently Deleted, that the files stay on disk, and that + Undo brings them back. While LightCraft isn't running the keys keep the + icons they last showed, dimmed. Logi Options+ shows the same keys in its editor. +- **LightCraft's actions in Logi Options+.** Besides the keys LightCraft sets, the plugin lists every LightCraft + action and value in Options+'s actions panel, in numbered categories with their icons (*1. Light*, *2. Color* …, + then *Rating & Labels*, *Browse & Select*, *Edit* …), so they can also be dragged onto keys, dials or the Actions + Ring there. Values turn on a dial (one undo step per turn, pressing resets) and show their live value. + +## Settings ▸ Controls + +Built around the device, as Logi Options+ shows it. At the top: **Use control surfaces**, the **profile**, then any +pairing request (with its code, **Approve** / **Deny**) and, when Logi Options+ is installed without the plugin, an +**Install the plugin** button. Under it the **device bar** switches between surfaces, each with a status dot: + +| Surface | What it shows | +|---|---| +| MX Creative Keypad | a drawing of the 3 × 3 keys and the two page buttons at its lower corners; connected / offline | +| MX Creative Dialpad | drawn as the device: buttons 1 and 2 top left, the roller top right, the big dial in the middle, button 3 bottom left, button 4 bottom right; connected / offline | +| Actions Ring | its eight slots around a ring (`ring.1`–`ring.8`, the same on every page), with undo, redo, pick, reject, previous / next photo, before / after and fit to start with; the plugin puts its pass-through on the ring's slots in Logi Options+ (`DefaultProfile72.lp5`) | +| Loupedeck+ | drawn in zones as on the console: the colour knobs P1–P8 (one colour mode at a time, Hue / Sat / Lum / B&W) with the mode buttons, the tone knobs, the Control Dial with the arrows, C1–C6 and L1–L3, then the buttons; a knob's press is the small chip at its corner; Loupedeck's profiles found on this computer to import (see [Loupedeck+](#loupedeck)) | +| Loupedeck Live / CT, MIDI controllers, Tangent panels | coming later | + +The sections under the device bar: + +| Section | What it holds | +|---|---| +| Keys and Dials (**Edit Keys and Dials…**, a resizable window of its own over Settings; picking a device in the bar opens it too) | page tabs (the device's pages, **All pages** for what a control does wherever a page leaves it empty, tool pages in a menu); the drawing — every control shows its icon and name, a control a page leaves empty shows the All pages one dimmed; click a control, drag an action from the list onto it, or **touch it on the device** (*Touch to find*, on while Settings ▸ Controls or this window is open: the control touched is selected here, and the device doesn't change the photo meanwhile; it acts again the moment they close; switched off, **Learn** does it once) and its editor opens beside the drawing: what it does now, **Clear**, a value's own speed and acceleration, a command's JSON parameters (advanced), and the **action picker** — every action in categories with icons and a search box (keys list their one-press actions first, then the values they can put on the dial; dials list values and paging); show a page, switch profile and every other command of the app are there too. Narrow windows put the editor under the drawing | +| Pages and Tools | each page's groups (Keys / Dials) and *Tool page*, Rename / Delete, Add page; *Pages that follow the app*: on / off, one page per context | +| Dial Feel | global speed, acceleration, fine and big step factors, invert; one value's speed, acceleration, slow / fast turning (floor / ceiling), fast / slow thresholds, invert; TactileBridge's presets for every value (Wedding, Real Estate, Fashion, Landscape) | +| Readout and Look | apply to every selected photo, when a turn ends, how often movement is applied, steady readout while turning; the on-screen readout (on / off, for key presses too, opacity, display time, position, background colour); keys: values on the device, haptics, key colours | +| Profiles and Setup | the Logi Options+ plugin (found / installed version / connected; Install, Update, Reinstall, Remove); profiles (Duplicate / Rename / Delete, Add the built-in profiles, **Bring over my TactileBridge setup** when `%LOCALAPPDATA%\TactileBridge\settings.json` exists, Import… `settings.json` / `.lp5` / `.lcsurface`, Export… `.lcsurface`, the last import's report); connection (port, connected surfaces, paired surfaces with Forget) | + +Profiles are shared by the Keypad and the Dialpad (one MX Creative Console); surfaces that come later get their own. + +### Loupedeck+ + +The Loupedeck+ (knobs, the Control Dial and buttons, no displays; Loupedeck's device type `Loupedeck15`) works through +the same plugin. Its controls are Loupedeck's own numbers: `ld.r` turns (P1–P8 send 1–8, 9–16, 17–24 or 25–32 by +the console's Hue / Sat / Lum / B&W mode; the labelled knobs 33–47; the Control Dial 48) and `ld.b` presses (a +knob's press is its number; C1–C6 49–54; the rating keys 66–70, with Fn 71–75; the arrows 78 / 79; P1–P8's presses +80–87; Copy, Paste, Undo, Redo, Screen Mode, Hue, Sat, Lum, Col/BW and Before/After 92–102; Custom Mode 110; L1–L3 +114–116). The plugin's `DefaultProfile15.lp5` forwards every one of them, and is picked whenever LightCraft is the app +in front. The Logi service uses a plugin's default profile only when it first makes the app's profile, so a LightCraft +profile made by an older plugin stays empty and nothing reached LightCraft until each control was assigned by hand in +the driver: the plugin (1.0.7) fills such a profile with its pass-through actions when it loads, before the service +reads it (controls with no action, or one of LightCraft's own value actions assigned as that workaround; any other +action stays; the original is kept in `PluginDataLightCraftprofile-backups`). The Actions Ring's profile gets the +same. + +**No setup:** a control nothing binds does what its label says (Loupedeck's own default layout: the Exposure knob +moves Exposure, P1–P8 the colour mixer, Undo undoes, the rating keys rate …). **Import:** Settings ▸ Controls ▸ +Loupedeck+ lists the profiles Loupedeck's software keeps for the console on this computer +(`%LOCALAPPDATA%\Loupedeck\Applications\Loupedeck15\\Profiles\\ProfileInfo.json`, read only) with an +**Import** button each, and **Import a Loupedeck profile…** takes a `ProfileInfo.json` or an exported `.lp5`; +`cmd:surface.import` takes either too. The editor mode's layout (Loupedeck's `loupe` mode: its first workspace, then +the Fn workspace for what that leaves empty) goes into every LightCraft profile (the console has no pages), replacing +an earlier import; presets match LightCraft presets by name. Only the mapping is read: no icons or images. The report +lists what was left out (Loupedeck macros, presets LightCraft doesn't have, Loupedeck's own Custom Mode button, the +Hue / Sat / Lum mode buttons). Code: `crates/surface/src/loupedeck.rs`. + +### Installing the Logi plugin + +The plugin is built in its own repository (`lightcraft-logi`: `scripts/package.ps1` → `dist/LightCraft.lplug4`, a +ZIP of the plugin DLL, its `metadata/` and its default profiles `profiles/DefaultProfile70.lp5` / `…71.lp5`). +LightCraft looks for **`LightCraft.lplug4` next to its executable** (or in `plugins/` beside it), or at +`LIGHTCRAFT_LOGI_PLUGIN`. *Install the plugin* (`cmd:surface.installPlugin`) writes the plugin's +`%LOCALAPPDATA%\Logi\LogiPluginService\PluginData\LightCraft\config.json` (the port LightCraft listens on) and +runs `%ProgramFiles%\Logi\LogiPluginService\LogiPluginServiceTool.exe install-plugin LightCraft.lplug4` — what +double-clicking a `.lplug4` does. Logi Options+ then asks the user to confirm, installs the plugin into +`…\LogiPluginService\Plugins\LightCraft` and its profiles, and reloads its plugin service (Logi restarts it; the +devices pause for a few seconds). *Remove the plugin* (`cmd:surface.uninstallPlugin`) runs `uninstall-plugin` the same +way. `cmd:surface.plugin` reports `{status: {host, installed, package, packagePath}, busy, message}`. Nothing else in +Logi Options+ is touched: other plugins, their profiles and the user's Options+ settings stay as they are. Windows +only for now; elsewhere the page says to open `LightCraft.lplug4` by hand. + +**Releases (maintainer decision).** A release that ships the plugin builds `LightCraft.lplug4` from a pinned +`lightcraft-logi` commit (a .NET build on Windows) and puts it next to `lightcraft.exe` in the Windows package (and +the macOS app's `Contents/MacOS` once the macOS path is verified). Without it LightCraft runs as before and the page +says no package came with it. Publishing the plugin on the Logi Marketplace instead is the other option; then +LightCraft would only link to it. + +Every action of the editor is also a command (`cmd:surface.profile`, `cmd:surface.page`, `cmd:surface.pageNext`, +`cmd:surface.pagePrevious`, `cmd:surface.applyToSelected`, `cmd:surface.followContext`, `cmd:surface.import`, +`cmd:surface.export`, `cmd:surface.settings` (read or replace the whole settings), `cmd:surface.state`, +`cmd:surface.input` (the input a surface sends)), plus the commands keys need: `cmd:surface.maskPrevious`, +`cmd:surface.maskNext`, `cmd:surface.dialogConfirm`, `cmd:surface.dialogCancel`. + +## Settings file + +`control-surfaces.json` in LightCraft's settings folder (next to `ui.json`; `LIGHTCRAFT_CONFIG_DIR` moves it). Written +atomically half a second after a change. A damaged file, or one from a newer LightCraft, is reported (Settings ▸ +Controls and a notice), kept as it is, and LightCraft runs on the defaults until you change something. Every number is +clamped into range on reading. + +```jsonc +{ + "version": 1, // format version + "enabled": true, // surfaces may connect (the listener runs) + "port": 7981, + "profile": "Wedding", // the profile in use + "followContext": true, // pages follow the app + "applyToSelected": false, // turns go to every selected photo + "motion": {"speed": 1.0, "acceleration": 1.0, "invert": false, "fine": 0.25, "coarse": 4.0}, + "tuning": { // per value; absent = defaults + "wb.temp": {"speed": 0.3, "acceleration": 1.0, "accelerationMin": 1.0, "accelerationMax": 10.0, + "fastMs": 20, "slowMs": 200, "invert": false} + }, + "transport": {"flushMs": 16, "echoSuppression": true, "echoSuppressionMs": 100, "gestureEndMs": 800}, + "osd": {"enabled": true, "opacity": 0.9, "background": "#202020", "displayMs": 1800, + "position": "bottom", "showCommands": true}, + "look": {"background": "#000000", "foreground": "#FFFFFF", "showValues": true, "haptics": true}, + "profiles": [{ + "name": "Wedding", + "description": "…", + "base": {"pad.1": {"kind": "command", "command": "develop.copy"}, + "pad.4": {"kind": "pageNext", "group": "dials"}}, + "pages": [ + {"name": "Cull", "groups": ["keys"], "bindings": { + "key.1": {"kind": "command", "command": "library.previous"}, + "key.4": {"kind": "command", "command": "photo.rate", "params": {"rating": 1}}}}, + {"name": "Exposure/WB", "groups": ["dials"], "bindings": { + "dial": {"kind": "value", "target": "light.exposure"}, "roller": {"kind": "value", "target": "wb.temp"}}}, + {"name": "Crop", "auto": true, "bindings": {"dial": {"kind": "value", "target": "crop.angle"}}} + ], + "contexts": {"default": ["Cull", "Exposure/WB"], "crop": ["Crop"]} + }], + "paired": [{"client": "lightcraft-logi", "name": "LightCraft plugin for Logi Options+", + "tokenSha256": "…64 hex digits…", "approvedAt": 1792000000}] +} +``` + +- **Bindings** (`kind`): `value {target}`, `command {command, params?}`, `modifier {modifier: fine|coarse}`, + `pageNext {group?: keys|dials}`, `pagePrevious {group?}`, `page {page}`, `profile {profile}`, `profileNext`, `reset`, + `applyToSelected`, `followContext`. +- **Targets**: develop control ids (`develop.controls` lists them; indexed ones such as `pointColor.0.hueShift` too); + `mask.` for the selected mask (`exposure`, `contrast`, `highlights`, `shadows`, `whites`, `blacks`, `temp`, + `tint`, `texture`, `clarity`, `dehaze`, `hue`, `saturation`, `sharpness`, `noise`, `moire`, `defringe`, `amount`); + `ui.brushSize`, `ui.brushFeather`, `ui.brushFlow`, `ui.removeSize`, `ui.removeFeather`, `ui.removeOpacity`, + `ui.zoom` (tool and view values, no undo step). +- **Pages**: `groups` empty = keys and dials; `auto: true` = a tool page, shown only by its context (paging by hand + skips it). +- **Contexts**, most specific first; a context falls back to its parents, then `default`: + +| Context | When | +|---|---| +| `dialog.` | a dialog is open (`dialog.export`, `dialog.import`, `dialog.settings`, …; the dialog's `kind` as `ui.inspect` shows it) | +| `library` | the photo grid, Survey or People (or no photo open) | +| `develop`, `develop.
` | Detail; the Edit panel's section opened last (`light`, `color`, `effects`, `detail`, `optics`, …) | +| `crop`, `remove`, `redeye` | those tools | +| `masking`, `masking.mask`, `masking.mask.brush`, `masking.mask.gradient` | Masking; a mask selected; its brush or gradient tool | + +A **layout file** (`.lcsurface`) is one profile as JSON (the `profiles[]` element above). + +## The surface protocol + +Version **1**. JSON lines on a loopback TCP port, the same framing and rules as the +[control protocol](control-protocol.md): one request object per line, `{"id", "method", "params"}`, one reply per +line, `{"id", "ok": true, "result"}` or `{"id", "ok": false, "error"}`. The control-surface port (Settings ▸ Controls, +`7981`) serves only `surface.*` methods; an app started with `--control PORT` serves them there too, beside everything +else. Between replies, a subscribed connection receives **events**: lines with an `event` field and no `id`. A line is +never split between a reply and an event. + +**Pairing.** The control port has no authentication, so surfaces pair: only a paired connection may subscribe or send +input. `surface.pair` creates a request with a six-digit code; the user approves it in Settings ▸ Controls; polling +`surface.pair {request}` then returns a 64-hex-digit token, once. Every later connection presents it in +`surface.hello`. LightCraft stores only its SHA-256; re-pairing the same client replaces its token; Forget revokes it +and tells connected surfaces (`surface.unpaired`). Requests expire after 10 minutes; at most four wait at once. +In-process requests (headless scripts, tests) count as paired. + +| Method | Params | Result | Paired? | +|---|---|---|---| +| `surface.hello` | `{protocol: 1, client, name?, token?}` | `{protocol, app, version, paired, enabled, devices: [{id, name, controls: [{id, kind, label}]}]}`; a valid token pairs this connection | no | +| `surface.pair` | `{client, name}` → new or open request; `{request}` → poll | `{status: "pending", request, code}` / `{status: "approved", token}` (once) / `{status: "denied"}` | no | +| `surface.icons` | `{names?: [..]}` (all when omitted) | `{name: svg}` | no | +| `surface.catalog` | — | `{groups: [..], entries: [{key, group, label, icon, value}]}`: every action in categories, labels in the app's language (`lightcraft_surface::catalog`); `key` is stable (`v.light.exposure`, `c.photo.rate.rating-5`, `s.applyToSelected`) | no | +| `surface.subscribe` | `{device?: "mx-creative-console"}` | `{layout}`; then `surface.layout` events whenever it changes | yes | +| `surface.unsubscribe` | — | — | yes | +| `surface.layout` | `{device?}` | the layout now | yes | +| `surface.input` | `{events: [{control, ticks}` \| `{control, press: true\|false, page?}` \| `{action, ticks}` \| `{action, press}]}` (at most 256) | `{effects}` | yes | +| `surface.watch` | `{targets: ["light.exposure", …]}` (at most 128; after `subscribe`) | — ; the pushed layout then carries `values: {target: {value, position}}` | yes | + +`surface.input` is pipelined: LightCraft reads the next request on the connection without waiting for the reply to +this one, so a fast turn sent a tick per request never queues up one tick per frame in the socket (it used to: a busy +app took seconds to catch up, then "replayed" the turn and the key presses behind it). The app still runs a +connection's requests in order and answers them in order; every other method is answered before the next request is +read. Ticks are summed and applied once per frame; a key press runs at once (what the dial gathered goes first); a +dial turned back follows the new way at once (the old way's ticks not applied yet are dropped and its acceleration +starts again from the floor). Value feedback is pushed as events, never awaited. + +Errors: an unpaired connection gets *this surface isn't paired …*; switched off: *control surfaces are switched off*; +a newer client protocol: *this LightCraft speaks surface protocol 1*. Junk input is refused with an error, never +acted on: `ticks` must be a number (clamped to ±1000 per event), `page` 1–64, control ids are trimmed to 64 characters. + +**Events**: `{"event": "surface.layout", "layout": {…}}` (a subscriber's device layout changed: a value, a page, the +context, a toggle — sent at most once per frame, and held back while the turned value hasn't caught up with the dial), +`{"event": "surface.unpaired"}` (the user forgot this surface; the connection should pair again). + +**Layout** (`lightcraft_surface::layout::DeviceLayout`): + +```jsonc +{ + "device": "mx-creative-console", "profile": "Default", "context": "crop", + "keyPage": "Crop", "dialPage": "Crop", + "keys": [{"control": "key.1", "binding": {"kind": "command", "command": "crop.rotateAspect"}, + "label": "Crop Orient.", "icon": "switch-crop-orientation", "value": null, "active": false}, …], + "keyPages": [{"name": "Page 1", "keys": [ … nine keys … ]}, … at least three …], + "buttons": [ … pad.1–pad.4 … ], + "dials": [{"control": "dial", "binding": {"kind": "value", "target": "crop.angle"}, "label": "Straighten", + "icon": "straighten-tool", "value": "+1.25", "position": 0.51}, …], + "focus": null, "applyToSelected": false, "followContext": true, + "background": "#000000", "foreground": "#FFFFFF", "showValues": true, "haptics": true +} +``` + +Labels and values come translated and formatted; `icon` names an SVG from `surface.icons`. `keyPages[n-1]` is what a +keypad with its own page buttons shows on its page *n* (the context's page on every one while a tool page is active); +such a keypad sends `page` with its presses. + +**Actions** (`{action: key}` events) come from a plugin's own list of LightCraft's actions (`surface.catalog`): turning +a value moves it (one undo step per turn, with the value's dial feel), pressing a value resets it, pressing anything +else does what a key bound to it does (a modifier holds until the action is released). An unknown key is refused. + +**Devices and controls.** `mx-creative-console`: `key.1`–`key.9` (Keypad LCD keys, row by row), `dial` (the Dialpad's big dial, Logi encoder 1), `roller` (Logi encoder 0), +`pad.1`–`pad.4` (Dialpad buttons). A dial press is `{control: "dial", press: true}`; it runs `dial.press` if a page +binds it, else resets the dial's value. Logi's device types: `Loupedeck70` = MX Creative Keypad, `Loupedeck71` = MX +Creative Dialpad, `Loupedeck72` = the Actions Ring (TactileBridge's `…70` / `…71` / `…72` profile variants). + +## Coming next: MIDI and Tangent + +The engine is device-neutral: controls are string ids, a device is a list of them with their kind (encoder, button, +LCD key) and page group. What each still needs: + +- **MIDI**: an input backend that fits the pure-Rust rule (the common `midir` crate links ALSA's C library on Linux); a `midi` device whose controls are `midi.cc..` (relative encoders: two's-complement and + binary-offset modes; absolute faders as values) and `midi.note..` (buttons); learn mode already reports + any control id; feedback to motor faders / LED rings from the pushed layout (`position`). +- **Tangent** (Wave, Element, Ripple): written from Tangent's **public** developer documentation only (the TUBE / + Hub API); a `tangent` device mapping panel controls to ids, the same layouts and protocol. TactileBridge's Tangent + hub impersonation for Capture One is not part of LightCraft and is not used. +- Both reuse pairing (an in-process client counts as local), profiles, contexts, motion and the readout as they are. + +## From TactileBridge + +Settings ▸ Controls ▸ **Bring over my TactileBridge setup** (or `surface.import {path}` with its `settings.json`) +brings over the dial feel (global and per value), the readout, the key colours, haptics and LED switches, automatic +switching, Auto Sync and every tool context, as a new profile named *TactileBridge* (made active; your other profiles +stay). Import… takes TactileBridge's Logi profiles (`.lp5`) too. The report lists what came over and what was left +out, and why. Tuning is kept as it was; LightCraft's slider units differ from Capture One's in places (Contrast is +±100 per 1, Temp 50 K per tick at speed 1), so a value may want its speed retuned. + +### Every TactileBridge feature and setting + +✅ ported · 🔁 done natively by LightCraft · ✕ dropped (Capture One–specific or not needed) + +| TactileBridge | LightCraft | | +|---|---|---| +| Dial acceleration curve (`GetAcceleration`: floor, ceiling, fast / slow thresholds, quadratic ramp) | `lightcraft_surface::motion` | ✅ | +| Global speed, acceleration, invert (`Controls.*`) | `motion.speed`, `motion.acceleration`, `motion.invert`; Settings ▸ Controls ▸ Dial Feel | ✅ | +| Per-adjustment tuning (`AdjustmentProfiles`: speed, acceleration, min, max, fast ms, slow ms, invert) | `tuning.`; Dial Feel ▸ Value | ✅ (keys mapped to LightCraft targets) | +| Workflow presets (Wedding, Real Estate, Fashion, Landscape) | Dial Feel ▸ Presets for every value | ✅ (Landscape's 18× ceiling is 15×, as TactileBridge's own clamp made it) | +| Echo suppression (`EnableEchoSuppression`, `EchoSuppressionMs`) | `transport.echoSuppression(Ms)`: pushes held while the turned value catches up | ✅ | +| Flush interval (`Bridge.FlushIntervalMs`, defined but unused in TactileBridge) | `transport.flushMs`: ticks coalesced, applied once per interval | ✅ (implemented) | +| Idle reconcile, state retention, periodic value poll, coalescing diagnostics (`Bridge.*`) | — | 🔁 LightCraft's values are authoritative and pushed on change: nothing to poll or reconcile | +| On-screen display (`OsdOverlay`: pill, title, value, bar, icon; enabled, opacity, colour, display time, 4 positions, fade) | `panels::surface_osd` in the window | ✅ (with the icon) | +| Plugin colours (`PluginColors`) | `look.background`, `look.foreground`, pushed live | ✅ (no plugin redeploy needed) | +| Haptic feedback switch | `look.haptics`: the plugin raises Logi plugin events (key pressed, value reset, value at its limit) Options+ can map to haptics | ✅ (TactileBridge had the switch only) | +| LED value indicator | `look.showValues` | ✅ | +| Tool contexts (`ToolContext.Contexts`: 9 keys + up to 4 encoders per Capture One tool) | profile pages with `auto: true`, mapped to contexts | ✅ (Crop → `crop`; Draw / Erase Mask → `masking.mask.brush`; Draw Healing Mask → `remove`; Direct Color Editor → `develop.color`; Import / Export / Process → `dialog.import` / `dialog.export`) | +| Automatic tool switching (`ToolStateAutomation`: UI Automation + BitBlt scan for the orange tool highlight; dialog detection by window title) | contexts read from LightCraft's own state | 🔁 (`followContext`) | +| Adjustment dial toggle on a pad key (focus, lit rounded border) | a key bound to a value; the plugin draws the lit border | ✅ | +| Modifier keys (keystrokes with Ctrl / Shift sent to Capture One) | commands run directly; new *hold for fine / big steps* modifiers | 🔁 / ✅ | +| Auto Sync (debounced Copy + Apply after the dial rests; `IdleTimeoutMs`, `CopyApplyDelayMs`; the AutoSync key) | Apply to Selected: the gesture's change goes to every selected photo in its one undo step; `gestureEndMs` | 🔁 (copy-apply delay dropped) | +| Dial press resets the parameter | dial press resets its value (or runs `dial.press`) | ✅ | +| Display smoothing on the dial tile | — | ✕ the plugin shows LightCraft's value as pushed | +| Kelvin conversion (`KelvinConvert`) | LightCraft's own Kelvin scale | 🔁 | +| Curated profiles (Default, Wedding, Portrait, Fashion, Landscape, Real Estate; `…70` Keypad, `…71` Dialpad, `…72` Actions Ring) | built-in profiles (`lightcraft_surface::defaults`): key pages from `70`, dial pages and buttons from `71` (`72` repeats them) | ✅ (the Dialpad's fourth button turns the dial pages; its TactileBridge action is on a key page, except Fashion's *Layer on/off*, which the Brush and Mask tool pages have) | +| Default Options+ profiles shipped by the plugin | the LightCraft plugin ships one Keypad and one Dialpad profile of generic keys | ✅ (layouts live in LightCraft, so nothing to assign in Options+) | +| Icon pack (`actionicons` = `actionsymbols` = `customicons`, 336 SVGs) | `assets/surface-icons` (335, kebab-case names) | ✅ (the duplicate `Clarity.min.svg` left out; the Keystone icons since 2026-10-16) | +| Icon map (`CaptureOneIconMap`) | `lightcraft_surface::icons::icon_for` | ✅ | +| Settings window (`SettingsForm`: Global, Per Adjustment with filter, Bridge, Hardware, OSD, Plugin Colors, Tool Context, Tool Switching tabs) | Settings ▸ Controls | ✅ (the Redeploy Plugin button is gone: changes apply live) | +| Capture One actions and parameters (`CaptureOneCommand`, `CaptureOneAdjustment`) | LightCraft commands and targets, table below | ✅ / ✕ per action | +| Color Editor values via UI Automation (`CE*`) | colour mixer targets (`mixer..`) | 🔁 | +| Mode buttons switching the dial (SPEC 7.1) | `pageNext {group: dials}` on a button | ✅ | +| Tangent TIPC hub impersonation (`TipcBridge`, `TipcProtocol`, `TipcConnection`, `CaptureOneConfig`) | — | ✕ Capture One–specific | +| Capture One control list (`ControlDatabase`, `controls.xml`), inspection tools (`_inspect`, `temp_inspect*`, `reflect_lr.ps1`, `inspect_sdk*`) | — | ✕ never ported | +| Keyboard simulation (`KeyboardSimulator`) | — | ✕ commands instead | +| Named-pipe bridge (`PipeServer`, `BridgeClient`, `PipeProtocol`) | the surface protocol on the control channel | 🔁 | +| Tray app, hub window, telemetry, logs (`Program`, `HubWindow`, `BridgeTelemetry`, `Log`) | LightCraft's own log and Settings ▸ Controls status | 🔁 | +| Production plans (installer, auto-update, crash reporting, licensing, code signing, Windows service) | — | ✕ LightCraft has its own release process | +| Branding and design references (`media/`, `design-mockups/`) | — | ✕ not shipped | + +### Every TactileBridge action + +Generated from `lightcraft_surface::tactilebridge::mapping_table()` (its tests check that every target exists and +every dropped action says why). + +**Dial values** + +| TactileBridge | LightCraft | Note | +|---|---|---| +| `Kelvin` | `wb.temp` | | +| `Tint` | `wb.tint` | | +| `Exposure` | `light.exposure` | | +| `Contrast` | `light.contrast` | | +| `Brightness` | — | Lightroom and LightCraft have no Brightness slider (use Exposure, Whites or the Tone Curve) | +| `Saturation` | `color.saturation` | | +| `Highlight` | `light.highlights` | | +| `Shadow` | `light.shadows` | | +| `White` | `light.whites` | | +| `Black` | `light.blacks` | | +| `MasterToneX` | `grading.global.hue` | Color Grading uses hue and saturation where Capture One's Color Balance uses x / y | +| `MasterToneY` | `grading.global.sat` | Color Grading uses hue and saturation where Capture One's Color Balance uses x / y | +| `ShadowToneX` | `grading.shadows.hue` | Color Grading uses hue and saturation where Capture One's Color Balance uses x / y | +| `ShadowToneY` | `grading.shadows.sat` | Color Grading uses hue and saturation where Capture One's Color Balance uses x / y | +| `ShadowLightness` | `grading.shadows.lum` | | +| `MidtoneToneX` | `grading.midtones.hue` | Color Grading uses hue and saturation where Capture One's Color Balance uses x / y | +| `MidtoneToneY` | `grading.midtones.sat` | Color Grading uses hue and saturation where Capture One's Color Balance uses x / y | +| `MidtoneLightness` | `grading.midtones.lum` | | +| `HighlightToneX` | `grading.highlights.hue` | Color Grading uses hue and saturation where Capture One's Color Balance uses x / y | +| `HighlightToneY` | `grading.highlights.sat` | Color Grading uses hue and saturation where Capture One's Color Balance uses x / y | +| `HighlightLightness` | `grading.highlights.lum` | | +| `BWRed` | `bw.red` | | +| `BWYellow` | `bw.yellow` | | +| `BWGreen` | `bw.green` | | +| `BWCyan` | `bw.aqua` | Cyan is called Aqua in the B&W mixer | +| `BWBlue` | `bw.blue` | | +| `BWMagenta` | `bw.magenta` | | +| `BWHighlightsHue` | `grading.highlights.hue` | B&W split toning is done with Color Grading | +| `BWHighlightsSat` | `grading.highlights.sat` | B&W split toning is done with Color Grading | +| `BWShadowsHue` | `grading.shadows.hue` | B&W split toning is done with Color Grading | +| `BWShadowsSat` | `grading.shadows.sat` | B&W split toning is done with Color Grading | +| `Clarity` | `effects.clarity` | | +| `Structure` | `effects.texture` | Texture is the closest to Capture One's Structure | +| `Vignetting` | `vignette.amount` | post-crop vignette | +| `Distortion` | `optics.distortion` | | +| `SharpnessFalloff` | — | LightCraft has no sharpness falloff correction | +| `LightFalloff` | `optics.vignetting` | lens vignetting (light falloff) correction | +| `Defringe` | `optics.defringePurple` | purple fringe amount | +| `UniformLight` | — | a Capture One feature LightCraft does not have | +| `SharpeningAmount` | `detail.sharpenAmount` | | +| `SharpeningRadius` | `detail.sharpenRadius` | | +| `SharpeningThreshold` | `detail.sharpenMasking` | Masking is the closest to a sharpening threshold | +| `SharpeningHalo` | — | LightCraft has no halo suppression slider | +| `NRLuminance` | `detail.nrLuminance` | | +| `NRDetail` | `detail.nrDetail` | | +| `NRColor` | `detail.nrColor` | | +| `NRSinglePixel` | — | LightCraft has no single-pixel noise slider | +| `GrainImpact` | `grain.amount` | | +| `GrainGranularity` | `grain.size` | | +| `MoireAmount` | `mask.moire` | moiré is a mask adjustment in LightCraft (as in Lightroom) | +| `MoirePattern` | — | LightCraft's moiré reduction has no pattern size | +| `LayerOpacity` | `mask.amount` | a mask's Amount | +| `SpotRadius` | `ui.removeSize` | the Remove brush size | +| `BrushSize` | `ui.brushSize` | | +| `BrushHardness` | `ui.brushFeather` | Feather (softness) — turn the other way for harder | +| `BrushOpacity` | — | LightCraft brushes have Size, Feather and Flow | +| `BrushFlow` | `ui.brushFlow` | | +| `Zoom` | `ui.zoom` | | +| `OverlayOpacity` | — | a Capture One feature LightCraft does not have | +| `OverlayScale` | — | a Capture One feature LightCraft does not have | +| `OverlayHorizontal` | — | a Capture One feature LightCraft does not have | +| `OverlayVertical` | — | a Capture One feature LightCraft does not have | +| `PenSize` | — | LightCraft has no annotations | +| `CERedHue` | `mixer.red.hue` | | +| `CERedSat` | `mixer.red.sat` | | +| `CERedLight` | `mixer.red.lum` | | +| `CEOrangeHue` | `mixer.orange.hue` | | +| `CEOrangeSat` | `mixer.orange.sat` | | +| `CEOrangeLight` | `mixer.orange.lum` | | +| `CEYellowHue` | `mixer.yellow.hue` | | +| `CEYellowSat` | `mixer.yellow.sat` | | +| `CEYellowLight` | `mixer.yellow.lum` | | +| `CEGreenHue` | `mixer.green.hue` | | +| `CEGreenSat` | `mixer.green.sat` | | +| `CEGreenLight` | `mixer.green.lum` | | +| `CECyanHue` | `mixer.aqua.hue` | Cyan is called Aqua in the colour mixer | +| `CECyanSat` | `mixer.aqua.sat` | Cyan is called Aqua in the colour mixer | +| `CECyanLight` | `mixer.aqua.lum` | Cyan is called Aqua in the colour mixer | +| `CEBlueHue` | `mixer.blue.hue` | | +| `CEBlueSat` | `mixer.blue.sat` | | +| `CEBlueLight` | `mixer.blue.lum` | | +| `CEPurpleHue` | `mixer.purple.hue` | | +| `CEPurpleSat` | `mixer.purple.sat` | | +| `CEPurpleLight` | `mixer.purple.lum` | | +| `CEMagentaHue` | `mixer.magenta.hue` | | +| `CEMagentaSat` | `mixer.magenta.sat` | | +| `CEMagentaLight` | `mixer.magenta.lum` | | + +**Keys** + +| TactileBridge | LightCraft | Note | +|---|---|---| +| `ClearRating` | `cmd:photo.rate` `{"rating":0}` | | +| `Rate1Star` | `cmd:photo.rate` `{"rating":1}` | | +| `Rate2Stars` | `cmd:photo.rate` `{"rating":2}` | | +| `Rate3Stars` | `cmd:photo.rate` `{"rating":3}` | | +| `Rate4Stars` | `cmd:photo.rate` `{"rating":4}` | | +| `Rate5Stars` | `cmd:photo.rate` `{"rating":5}` | | +| `ColorTagNone` | `cmd:photo.label` `{"label":"none"}` | | +| `ColorTagRed` | `cmd:photo.label` `{"label":"red"}` | | +| `ColorTagOrange` | — | LightCraft's colour labels are red, yellow, green, blue and purple (as Lightroom's) | +| `ColorTagYellow` | `cmd:photo.label` `{"label":"yellow"}` | | +| `ColorTagGreen` | `cmd:photo.label` `{"label":"green"}` | | +| `ColorTagBlue` | `cmd:photo.label` `{"label":"blue"}` | | +| `ColorTagPink` | — | LightCraft's colour labels are red, yellow, green, blue and purple (as Lightroom's) | +| `ColorTagPurple` | `cmd:photo.label` `{"label":"purple"}` | | +| `PreviousImage` | `cmd:library.previous` | | +| `NextImage` | `cmd:library.next` | | +| `FirstImage` | — | no LightCraft command jumps to the first or last photo yet | +| `LastImage` | — | no LightCraft command jumps to the first or last photo yet | +| `SelectAll` | `cmd:library.selectAll` | | +| `DeselectAll` | `cmd:library.selectNone` | | +| `InvertSelection` | — | no LightCraft command inverts the selection yet | +| `SelectPrimaryOnly` | — | a Capture One feature LightCraft does not have | +| `DeselectPrimary` | — | a Capture One feature LightCraft does not have | +| `SelectSameColorTag` | — | a Capture One feature LightCraft does not have | +| `SelectSameSequenceId` | — | a Capture One feature LightCraft does not have | +| `SelectSameVariantPos` | — | a Capture One feature LightCraft does not have | +| `PreviousSet` | — | a Capture One feature LightCraft does not have | +| `NextSet` | — | a Capture One feature LightCraft does not have | +| `PreviousCollection` | — | a Capture One feature LightCraft does not have | +| `NextCollection` | — | a Capture One feature LightCraft does not have | +| `Undo` | `cmd:edit.undo` | | +| `Redo` | `cmd:edit.redo` | | +| `ResetAdjustments` | `cmd:develop.reset` | | +| `CopyAdjustments` | `cmd:develop.copy` | | +| `ApplyAdjustments` | `cmd:develop.paste` | | +| `CopyAndApplyAdj` | `cmd:develop.sync` | copies the active photo's settings to the other selected photos | +| `AutoAdjust` | `cmd:develop.auto` | | +| `RotateLeft` | `cmd:photo.rotateLeft` | | +| `RotateRight` | `cmd:photo.rotateRight` | | +| `SnapTo90` | `cmd:develop.resetControl` `{"control":"crop.angle"}` | straightens back to 0° | +| `NewEmptyLayer` | `cmd:mask.add` `{"kind":"brush"}` | a new brush mask | +| `NewFilledLayer` | `cmd:mask.add` `{"center":[0.5,0.5],"feather":0.0,"kind":"radial","rx":1.0,"ry":1.0}` | a new mask over the whole photo | +| `NewCloneLayer` | `cmd:panel.remove` | the Remove tool (heal and clone) | +| `NewHealLayer` | `cmd:panel.remove` | the Remove tool (heal and clone) | +| `RemoveLayer` | `cmd:mask.delete` | deletes the selected mask | +| `SelectLayerUp` | `cmd:surface.maskPrevious` | selects the mask above | +| `SelectLayerDown` | `cmd:surface.maskNext` | selects the mask below | +| `SelectBackground` | `cmd:mask.select` `{"id":null}` | deselects the mask | +| `ToggleLayerOnOff` | `cmd:mask.visible` | shows or hides the selected mask | +| `InvertMask` | `cmd:mask.invert` | | +| `FillMask` | — | a Capture One feature LightCraft does not have | +| `ClearMask` | — | a Capture One feature LightCraft does not have | +| `RasterizeMask` | — | a Capture One feature LightCraft does not have | +| `RefineMask` | — | Refine runs on a mask's own component in LightCraft | +| `FeatherMask` | — | a Capture One feature LightCraft does not have | +| `LumaRange` | `cmd:mask.add` `{"kind":"luminanceRange"}` | a new luminance range mask | +| `ToggleSelectionPoints` | `cmd:view.maskPins` | mask pins | +| `ZoomIn` | `cmd:view.zoomIn` | | +| `ZoomOut` | `cmd:view.zoomOut` | | +| `ZoomToFit` | `cmd:view.zoomFit` | | +| `Zoom100` | `cmd:view.zoom100` | | +| `Zoom200` | `cmd:view.navigate` `{"zoom":{"percent":200}}` | | +| `Zoom400` | `cmd:view.navigate` `{"zoom":{"percent":400}}` | | +| `IncreaseZoom` | `cmd:view.zoomIn` | | +| `DecreaseZoom` | `cmd:view.zoomOut` | | +| `ToggleMultiView` | `cmd:view.survey` | Survey view | +| `ToggleExposureWarn` | `cmd:view.clipping` | clipping warnings | +| `ToggleFocusMask` | — | LightCraft has no focus mask yet | +| `ToggleOverlay` | — | a Capture One feature LightCraft does not have | +| `ToggleBeforeAfter` | `cmd:view.beforeAfter` | | +| `ShowGuides` | `cmd:view.cropOverlay` | cycles the crop overlay | +| `ShowGrid` | `cmd:view.cropOverlay` | cycles the crop overlay | +| `RecipeProofing` | `cmd:view.softProof` | soft proofing | +| `FullScreen` | `cmd:view.fullScreenPreview` | | +| `SlideShow` | `cmd:view.slideshow` | | +| `ShowHideViewer` | — | a Capture One feature LightCraft does not have | +| `ShowHideBrowser` | `cmd:view.filmstrip` | the filmstrip | +| `ToggleTools` | `cmd:panel.edit` | opens or closes the Edit panel | +| `SelectTool` | `cmd:tool.none` | no tool: click and drag pans | +| `MoveTool` | `cmd:tool.none` | no tool: click and drag pans | +| `PanTool` | `cmd:tool.none` | no tool: click and drag pans | +| `ZoomInTool` | `cmd:view.zoomIn` | | +| `ZoomOutTool` | `cmd:view.zoomOut` | | +| `CropTool` | `cmd:panel.crop` | Crop & Rotate (straighten there) | +| `SwitchCropOrientation` | `cmd:crop.rotateAspect` | | +| `StraightenTool` | `cmd:panel.crop` | Crop & Rotate (straighten there) | +| `RotateFreehandTool` | `cmd:panel.crop` | Crop & Rotate (straighten there) | +| `SpotRemovalTool` | `cmd:panel.remove` | the Remove tool (heal and clone) | +| `WBPickerTool` | `cmd:tool.wbPicker` | | +| `ApplyNormalization` | — | a Capture One feature LightCraft does not have | +| `PickNormTarget` | — | a Capture One feature LightCraft does not have | +| `PickHighlightLevel` | — | LightCraft's targeted adjustment works on the photo with the pointer | +| `PickShadowLevel` | — | LightCraft's targeted adjustment works on the photo with the pointer | +| `PickCurvePoint` | — | LightCraft's targeted adjustment works on the photo with the pointer | +| `PickLumaCurve` | — | LightCraft's targeted adjustment works on the photo with the pointer | +| `PickColorCorrection` | — | LightCraft's targeted adjustment works on the photo with the pointer | +| `DirectColorEditor` | `cmd:section.color` | the Color section (Point Color is there) | +| `PickSkinColor` | — | a Capture One feature LightCraft does not have | +| `AddColorReadout` | — | a Capture One feature LightCraft does not have | +| `DeleteColorReadout` | — | a Capture One feature LightCraft does not have | +| `OverlayTool` | — | a Capture One feature LightCraft does not have | +| `WatermarkTool` | — | a Capture One feature LightCraft does not have | +| `FocusMeterTool` | — | a Capture One feature LightCraft does not have | +| `PickFocusPoint` | — | a Capture One feature LightCraft does not have | +| `LoupeTool` | `cmd:view.zoomToggle` | zooms to 100 % and back | +| `KeystoneTool` | `cmd:tool.guidedUpright` | Guided Upright | +| `KeystoneVertical` | `cmd:geometry.upright` `{"mode":"vertical"}` | Upright: Vertical | +| `KeystoneHorizontal` | `cmd:geometry.upright` `{"mode":"level"}` | Upright: Level | +| `DrawMaskTool` | `cmd:tool.brush` | | +| `DrawHealTool` | `cmd:panel.remove` | the Remove tool (heal and clone) | +| `DrawCloneTool` | `cmd:panel.remove` | the Remove tool (heal and clone) | +| `EraseMaskTool` | `cmd:tool.brush` `{"op":"subtract"}` | a subtracting brush on the selected mask | +| `LinearGradientTool` | `cmd:tool.linear` | | +| `RadialGradientTool` | `cmd:tool.radial` | | +| `Process` | `cmd:dialog.export` | the Export dialog | +| `ExportOriginals` | `cmd:dialog.export` | the Export dialog | +| `ExportVariants` | `cmd:dialog.export` | the Export dialog | +| `ImportImages` | `cmd:file.addPhotos` | | +| `Print` | `cmd:dialog.contactSheet` | LightCraft prints contact sheets as PDF | +| `EditAllSelected` | `cmd:develop.autoSync` | Auto Sync: edits change every selected photo | +| `Rename` | `cmd:dialog.rename` | | +| `NewVariant` | `cmd:photo.virtualCopy` | a virtual copy | +| `CloneVariant` | `cmd:photo.virtualCopy` | a virtual copy | +| `Delete` | `cmd:photo.delete` | moves to Recently Deleted | +| `MoveToTrash` | `cmd:photo.delete` | moves to Recently Deleted | +| `RegeneratePreviews` | `cmd:library.buildPreviews` | | +| `SetCompareVariant` | `cmd:photo.setReference` | the reference photo | +| `ClearCompareVariant` | — | a Capture One feature LightCraft does not have | +| `PickVariant` | `cmd:photo.pick` | flags as Pick | +| `PromoteVariant` | `cmd:stack.moveUp` | one place up in the stack | +| `DemoteVariant` | `cmd:stack.moveDown` | one place down in the stack | +| `ShowInLibrary` | `cmd:view.back` | back to the grid | +| `ShowInFileSystem` | `cmd:app.showInFinder` | | +| `Capture` | — | tethered capture is not in LightCraft yet | +| `CompositionMode` | — | tethered capture is not in LightCraft yet | +| `LiveView` | — | tethered capture is not in LightCraft yet | +| `AutoFocus` | — | tethered capture is not in LightCraft yet | +| `AutoFocusFine` | — | tethered capture is not in LightCraft yet | +| `ShutterSpeedUp` | — | tethered capture is not in LightCraft yet | +| `ShutterSpeedDown` | — | tethered capture is not in LightCraft yet | +| `ApertureUp` | — | tethered capture is not in LightCraft yet | +| `ApertureDown` | — | tethered capture is not in LightCraft yet | +| `ExposureBiasUp` | — | tethered capture is not in LightCraft yet | +| `ExposureBiasDown` | — | tethered capture is not in LightCraft yet | +| `ISOUp` | — | tethered capture is not in LightCraft yet | +| `ISODown` | — | tethered capture is not in LightCraft yet | +| `BWEnable` | `cmd:develop.treatment` | | +| `ToggleGrading` | — | Capture One's grading switch has no single LightCraft counterpart | +| `SelectPen` | — | LightCraft has no annotations | +| `SelectEraser` | — | LightCraft has no annotations | +| `PenBlack` | — | LightCraft has no annotations | +| `PenWhite` | — | LightCraft has no annotations | +| `PenRed` | — | LightCraft has no annotations | +| `PenYellow` | — | LightCraft has no annotations | +| `PenGreen` | — | LightCraft has no annotations | +| `PenBlue` | — | LightCraft has no annotations | +| `ToggleSelectImage` | — | these sent keystrokes to Capture One's import window; LightCraft's import dialog takes the keyboard directly | +| `NextGroup` | — | these sent keystrokes to Capture One's import window; LightCraft's import dialog takes the keyboard directly | +| `PreviousGroup` | — | these sent keystrokes to Capture One's import window; LightCraft's import dialog takes the keyboard directly | +| `NextImageImport` | — | these sent keystrokes to Capture One's import window; LightCraft's import dialog takes the keyboard directly | +| `PreviousImageImport` | — | these sent keystrokes to Capture One's import window; LightCraft's import dialog takes the keyboard directly | +| `FilterRatingNone` | `cmd:library.filter` `{"rating":0,"ratingOp":"exactly"}` | shows unrated photos | +| `FilterRating1Star` | `cmd:library.filter` `{"rating":1,"ratingOp":"atLeast"}` | | +| `FilterRating2Stars` | `cmd:library.filter` `{"rating":2,"ratingOp":"atLeast"}` | | +| `FilterRating3Stars` | `cmd:library.filter` `{"rating":3,"ratingOp":"atLeast"}` | | +| `FilterRating4Stars` | `cmd:library.filter` `{"rating":4,"ratingOp":"atLeast"}` | | +| `FilterRating5Stars` | `cmd:library.filter` `{"rating":5,"ratingOp":"atLeast"}` | | +| `FilterTagNone` | `cmd:library.filter` `{"label":null}` | | +| `FilterTagRed` | `cmd:library.filter` `{"label":"red"}` | | +| `FilterTagOrange` | — | LightCraft's colour labels are red, yellow, green, blue and purple (as Lightroom's) | +| `FilterTagYellow` | `cmd:library.filter` `{"label":"yellow"}` | | +| `FilterTagGreen` | `cmd:library.filter` `{"label":"green"}` | | +| `FilterTagBlue` | `cmd:library.filter` `{"label":"blue"}` | | +| `FilterTagPink` | — | LightCraft's colour labels are red, yellow, green, blue and purple (as Lightroom's) | +| `FilterTagPurple` | `cmd:library.filter` `{"label":"purple"}` | | +| `SelectUnrated` | `cmd:library.selectBy` `{"rating":0,"ratingOp":"eq"}` | | +| `Select1Star` | `cmd:library.selectBy` `{"rating":1,"ratingOp":"eq"}` | | +| `Select2Stars` | `cmd:library.selectBy` `{"rating":2,"ratingOp":"eq"}` | | +| `Select3Stars` | `cmd:library.selectBy` `{"rating":3,"ratingOp":"eq"}` | | +| `Select4Stars` | `cmd:library.selectBy` `{"rating":4,"ratingOp":"eq"}` | | +| `Select5Stars` | `cmd:library.selectBy` `{"rating":5,"ratingOp":"eq"}` | | +| `SelectTagNone` | `cmd:library.selectBy` `{"label":"none"}` | | +| `SelectTagRed` | `cmd:library.selectBy` `{"label":"red"}` | | +| `SelectTagOrange` | — | LightCraft's colour labels are red, yellow, green, blue and purple (as Lightroom's) | +| `SelectTagYellow` | `cmd:library.selectBy` `{"label":"yellow"}` | | +| `SelectTagGreen` | `cmd:library.selectBy` `{"label":"green"}` | | +| `SelectTagBlue` | `cmd:library.selectBy` `{"label":"blue"}` | | +| `SelectTagPink` | — | LightCraft's colour labels are red, yellow, green, blue and purple (as Lightroom's) | +| `SelectTagPurple` | `cmd:library.selectBy` `{"label":"purple"}` | | +| `AutoSync` | Apply to Selected | dials change every selected photo | + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-10-25 | minor | Keys and Dials (the drawn device and its editor) in a resizable window of its own, opened from Settings ▸ Controls, which keeps the Settings window's one size | +| 2026-10-14 | major | Created: the control-surface engine (ported from TactileBridge), Settings ▸ Controls, the surface protocol v1, the MX Creative Console | +| 2026-10-15 | major | Settings ▸ Controls rebuilt around a drawing of the device with a side editor and categorised action picker; device bar; installing the Logi plugin from LightCraft (`surface.installPlugin` / `uninstallPlugin` / `plugin`); `surface.catalog`, `surface.watch` and action events, so Logi Options+ lists LightCraft's actions and values; icons in the readout | +| 2026-10-17 | minor | Dialpad drawn as the device, Keypad page buttons at its corners, Loupedeck+ in zones; Actions Ring slots set in LightCraft; drag and drop from the action list; Touch to find | +| 2026-10-16 | minor | Loupedeck+: a device of its own (`ld.r` / `ld.b`), works as labelled with no setup, imports a Loupedeck profile's layout (`surface.import`, Settings ▸ Controls ▸ Loupedeck+) | +| 2026-10-16 | minor | 13 icons of LightCraft's own in the pack's style for functions that shared a generic icon | +| 2026-10-16 | minor | Erase while held (`brush.erase`), key states (focus / held / on), destructive keys need a 0.7 s hold, no Delete key on built-in layouts, Previous / Next Mask, the brush page's size and feather keys; settings format 3 | +| 2026-10-15 | minor | Zero setup for the Logi plugin (on by itself, trusted through its data folder); the console shows the page being edited; dialog pages opt-in; `dial` / `roller` are the real big dial / roller (settings format 2 swaps older files), so a value key's value lands on the big dial | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index a6c63b816a5..bee43bc1617 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (pen pressure for brush masks; monitor profile from colord on Linux); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (control surfaces: the engine ported from TactileBridge, Settings ▸ Controls, the MX Creative Console and the Loupedeck+ through the LightCraft Logi plugin); previously minor (pen pressure for brush masks; monitor profile from colord on Linux); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 What Lightroom does with the machine's hardware, per platform, and what LightCraft does. Sources: [gpu-pipeline.md](gpu-pipeline.md), [display-profiles.md](display-profiles.md), [denoise.md](denoise.md), @@ -19,7 +19,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra | Card readers / cameras as import sources | ✅ (devices panel, eject after import) | ✅ mounted volumes with DCIM | ✅ | ✅ | — | 🟡 no eject-after-import check, no MTP / PTP phones | | Tethered capture | ✅ Classic (Canon, Nikon, Sony, Leica) | ⬜ | ⬜ | ⬜ | — | ⬜ | | Printers | ✅ Print module, printer colour management | ⬜ (PDF contact sheets only) | ⬜ | ⬜ | — | ⬜ | -| Control surfaces (MIDI / Loupedeck via plug-ins) | via SDK plug-ins | control channel and MCP can drive every command | same | same | — | 🟡 different mechanism; no MIDI mapping | +| Control surfaces (MIDI / Loupedeck via plug-ins) | via SDK plug-ins | built-in surface engine ([control-surfaces.md](control-surfaces.md)): profiles and pages, pages that follow the tool, dial feel and acceleration, one undo step per turn, apply to every selected photo, on-screen readout, Settings ▸ Controls with a Keys and Dials window drawing each device as it is laid out (action picker by category, drag and drop, Touch to find), the Actions Ring's slots, pairing; Logitech MX Creative Console through the LightCraft Logi plugin, installed from Settings ▸ Controls, with LightCraft's actions listed in Logi Options+; the Loupedeck+ through the same plugin (works as labelled, imports a Loupedeck profile's layout); TactileBridge setups import | same (plugin verified on Windows) | engine and protocol, no Logi Options+ there | — | 🟡 MX Creative Console ✅; Loupedeck+ (untested on the hardware); MIDI and Tangent panels not yet | | Multi-core CPU | ✅ | ✅ worker pools, parallel JPEG decode, parallel import copy | ✅ | ✅ | single thread | ✅ | | Memory pressure | managed | ✅ memory budget, `crates/sysmem` returns allocator pages on macOS | ✅ budget | ✅ budget | — | ✅ | @@ -49,6 +49,7 @@ NVIDIA, Intel and Windows DX12 still rely on user reports. | Date | Change | Summary | |---|---|---| +| 2026-10-25 | minor | Control surfaces: the built-in engine (ported from TactileBridge), Settings ▸ Controls and its Keys and Dials window, the surface protocol, the MX Creative Console and the Loupedeck+ via the LightCraft Logi plugin, the Actions Ring, Touch to find; MIDI and Tangent still to come | | 2026-10-12 | minor | Monitor profile: Linux reads the display profile from colord; macOS row reflects #787 | | 2026-10-12 | minor | CPU ↔ GPU equivalence suite run on an AMD Radeon 8060S (Vulkan, RADV, Linux): 16 tests / 135 cases pass, max 2 LSB, mean ≤ 0.0003; first GPU verified outside Apple | | 2026-10-12 | minor | Pen pressure: strokes record per-point pressure from egui touch force, scaling dab size and flow; per-platform status | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..c2c91df7ac2 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,19 @@ # What's new in LightCraft +## 2026-10-25 + +### Control surfaces +- **Edit from a console.** LightCraft has its own control-surface engine (ported from TactileBridge): the Logitech + MX Creative Console's keys, dials and Actions Ring, and the Loupedeck+, drive LightCraft through the LightCraft Logi + plugin, which Settings ▸ Controls installs. Dials move a slider with acceleration and fine control; a whole turn + is one undo step, on the active photo or every selected one; keys run any command. +- **Pages that follow what you do:** separate pages for editing, masks, the brush, crop and more, chosen by the tool + in use; a short readout on the photo shows what a dial or key just did. +- **Settings ▸ Controls** sets it up: the device's status, profiles, pages, dial feel and the readout. **Edit Keys + and Dials…** opens the device as it is laid out, in a window of its own: click a key, button or dial, or touch it + on the device (Touch to find), and choose what it does, or drag an action onto it. +- See [control-surfaces.md](control-surfaces.md) for the protocol other surfaces can use. + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock From 76ec912df0d4c3749bcf8211c9e16567841c051e Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 01:52:20 +1000 Subject: [PATCH 03/16] HW-SURFACE: ci --quick counts a surface icon change as a change to lightcraft-surface Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci_quick.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index 3242c95afad..a7e472562f7 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -37,6 +37,7 @@ const EMBEDDED: &[(&str, &[&str])] = &[ ("assets/camera-profiles/", &["lightcraft-engine"]), ("assets/camera-tone/", &["lightcraft-engine"]), ("assets/fonts/", &["lightcraft-engine", "lightcraft-ui-egui"]), + ("assets/surface-icons/", &["lightcraft-surface"]), ("contributors/", &["lightcraft-ui-egui"]), ("docs/whats-new.md", &["lightcraft-ui-egui"]), ("docs/raw/coverage-sweep.tsv", &["lightcraft-raw"]), From b38d468776f24ecf77b97a606cff36b217e92084 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 02:44:33 +1000 Subject: [PATCH 04/16] HW-SURFACE: review fixes (pairing, dial press, imports, profiles, web, docs) - Asking to pair again withdraws the client's waiting request: a request's id and code go only to the caller that made it. - Pressing the dial resets the value a key put on it, instead of taking the value off the dial. - A Loupedeck profile's control ids are bounded and checked against the devices before use. - The Loupedeck profile list is read at most every 10 s, not every frame. - Duplicate and Add page give new names; deleting the active profile makes another one active. - The web build doesn't ask for a process id. - The icon licence names the 15 icons drawn for LightCraft; docs say the in-app plugin install is Windows-only; the settings example is format 3. Co-Authored-By: Claude Opus 5.5 --- assets/ATTRIBUTION.md | 2 +- assets/surface-icons/LICENSE.txt | 13 +++++- crates/surface/src/protocol.rs | 16 +++++--- crates/surface/src/runtime.rs | 10 ++++- crates/surface/src/tactilebridge.rs | 16 +++++++- crates/ui-egui/src/panels/controls.rs | 57 ++++++++++++++++++++++----- crates/ui-egui/src/surface.rs | 2 + crates/ui-egui/src/tests_surface.rs | 25 ++++++++++++ docs/control-surfaces.md | 4 +- docs/hardware-parity.md | 2 +- docs/whats-new.md | 2 +- 11 files changed, 125 insertions(+), 24 deletions(-) diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index adfe4ce2414..9f327def53f 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -20,7 +20,7 @@ covers a whole directory), or if a licence file referenced in the Licence column | `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none | | `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix | | `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none | -| `assets/surface-icons/*.svg` (335 icons from the pack, plus the 13 below: dial values and key actions for control surfaces) | TactileBridge icon pack | RAD Films - Roman Alurkoff | original hand-drawn work from TactileBridge (the author's own project, contributed to LightCraft) | MIT (`assets/surface-icons/LICENSE.txt`) | 2026-10-14 | renamed from `CaptureOneAdj___.svg` / `CaptureOneCmd___.svg` to kebab-case `.svg`; the authoring tool's generator comment removed from two files; `Clarity.min.svg` (a duplicate) left out; the three Keystone icons added 2026-10-16 as `keystone-tool` / `keystone-vertical` / `keystone-horizontal` (the author confirmed every icon of the pack is their own drawing; a likeness to other apps comes from the generic subject); 2026-10-15: 81 icons that spilled over the edge, sat off-centre or were much smaller than the rest wrapped in one `data-normalized` transform (scaled and placed like the others; drawings unchanged) | +| `assets/surface-icons/*.svg` (335 icons from the pack, plus the 15 below: dial values and key actions for control surfaces) | TactileBridge icon pack | RAD Films - Roman Alurkoff | original hand-drawn work from TactileBridge (the author's own project, contributed to LightCraft) | MIT (`assets/surface-icons/LICENSE.txt`) | 2026-10-14 | renamed from `CaptureOneAdj___.svg` / `CaptureOneCmd___.svg` to kebab-case `.svg`; the authoring tool's generator comment removed from two files; `Clarity.min.svg` (a duplicate) left out; the three Keystone icons added 2026-10-16 as `keystone-tool` / `keystone-vertical` / `keystone-horizontal` (the author confirmed every icon of the pack is their own drawing; a likeness to other apps comes from the generic subject); 2026-10-15: 81 icons that spilled over the edge, sat off-centre or were much smaller than the rest wrapped in one `data-normalized` transform (scaled and placed like the others; drawings unchanged) | | `assets/surface-icons/{mask-invert,brush-erase,brush-new,mask-previous,mask-next,mask-visible,zoom-fit-view,zoom-actual-size,select-all-photos,select-no-photos,rotate-photo-left,rotate-photo-right,reset-develop,preset-apply,preset-apply-ai}.svg` (15 icons) | Surface icons for functions that shared one generic pack icon (the two preset icons, 2026-10-22: a key that applies a preset, with an "AI" mark for AI-mask presets) | drawn by an AI agent (Claude) for LightCraft in the TactileBridge pack's style | original work | MIT, part of the pack (`assets/surface-icons/LICENSE.txt`) | 2026-10-16 | none; new files beside the pack's originals, which are unchanged | | `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a | diff --git a/assets/surface-icons/LICENSE.txt b/assets/surface-icons/LICENSE.txt index c71be31e931..7aa9305a51d 100644 --- a/assets/surface-icons/LICENSE.txt +++ b/assets/surface-icons/LICENSE.txt @@ -2,8 +2,17 @@ MIT License Copyright (c) 2026 RAD Films - Roman Alurkoff -The icons in this folder are original hand-drawn work from TactileBridge, contributed to -LightCraft by their author under the MIT licence. +Covers every icon in this folder: + +- 335 icons are original hand-drawn work from TactileBridge, contributed to LightCraft by their + author under the MIT licence (the copyright notice above). +- 15 icons were drawn for LightCraft in the same style, by an AI agent (Claude) working for the + same author, and are released under the same licence: mask-invert, brush-erase, brush-new, + mask-previous, mask-next, mask-visible, zoom-fit-view, zoom-actual-size, select-all-photos, + select-no-photos, rotate-photo-left, rotate-photo-right, reset-develop, preset-apply and + preset-apply-ai. + +assets/ATTRIBUTION.md lists both groups. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/crates/surface/src/protocol.rs b/crates/surface/src/protocol.rs index 14cbbdb24ff..a74013691b7 100644 --- a/crates/surface/src/protocol.rs +++ b/crates/surface/src/protocol.rs @@ -115,16 +115,17 @@ impl Pairing { self.requests.retain(|r| (now_ms.saturating_sub(r.created_ms) as f64) < REQUEST_TTL_MS); } - /// A client asks to pair (`surface.pair {client, name}`): its open request, or a new one. + /// A client asks to pair (`surface.pair {client, name}`): a new request. One that client id + /// already had waiting is withdrawn, its id and code with it: a request's id and code go + /// only to the caller that made it, so another program asking under the same client id can't + /// pick up the token, and the user sees the code change. pub fn ask(&mut self, client: &str, name: &str, now_ms: u64) -> Result { self.expire(now_ms); let client = clean(client); if client.is_empty() { return Err("surface.pair: give a `client` id".into()); } - if let Some(r) = self.requests.iter().find(|r| r.client == client && matches!(r.state, PairState::Pending { .. })) { - return Ok(r.clone()); - } + self.requests.retain(|r| !(r.client == client && matches!(r.state, PairState::Pending { .. }))); if self.waiting().count() >= MAX_PENDING { return Err("surface.pair: too many pairing requests are waiting; answer them in Settings ▸ Controls first".into()); } @@ -217,7 +218,12 @@ mod tests { let mut s = SurfaceSettings::default(); let r = p.ask("lightcraft-logi", "Logi Actions plugin", 0).unwrap(); assert_eq!(r.code.len(), 6); - assert_eq!(p.ask("lightcraft-logi", "again", 1).unwrap().request, r.request, "one open request per client"); + // asking again withdraws the open request: its id and code never go to a second caller + let again = p.ask("lightcraft-logi", "again", 1).unwrap(); + assert_ne!(again.request, r.request); + assert_eq!(p.poll(&r.request, 2), None, "the first request is withdrawn"); + assert_eq!(p.waiting().count(), 1, "one open request per client"); + let r = again; assert_eq!(p.poll(&r.request, 2), Some(PairState::Pending { code: r.code.clone() })); let token = p.approve(&r.request, &mut s, 100).unwrap(); assert_eq!(token.len(), 64); diff --git a/crates/surface/src/runtime.rs b/crates/surface/src/runtime.rs index 20b5fb33c2d..5adc9ec1dd1 100644 --- a/crates/surface/src/runtime.rs +++ b/crates/surface/src/runtime.rs @@ -546,7 +546,9 @@ impl Runtime { if is_encoder(control) { // a dial press: its own binding (`dial.press`), else reset what the dial moves let own = format!("{control}.press"); - if let Some(b) = self.binding(&own, None) { + // (its own binding only: the dial focus moves the dial, it doesn't bind its press) + let bound = self.profile().and_then(|p| p.binding(&own, &self.pages).cloned()).or_else(|| crate::loupedeck::default_binding(&own)); + if let Some(b) = bound { return self.perform(&own, &b, now_ms); } return match self.binding(control, None) { @@ -960,6 +962,12 @@ mod tests { assert_eq!(r.input(turn("dial", 1), 10.0), [Effect::Begin { target: "light.contrast".into() }]); r.input(press("key.2"), 20.0); assert_eq!(r.focus(), None); + // pressing the dial resets the value on it, and keeps it there + r.input(press("key.2"), 25.0); + // (the turn still open goes to the photo first) + assert_eq!(r.input(press("dial"), 26.0).last(), Some(&Effect::Reset { target: "light.contrast".into() })); + assert_eq!(r.focus(), Some("light.contrast")); + r.input(press("key.2"), 27.0); // a context change drops the focus too r.input(press("key.2"), 30.0); r.set_context("crop"); diff --git a/crates/surface/src/tactilebridge.rs b/crates/surface/src/tactilebridge.rs index c86fee58941..8df378e4623 100644 --- a/crates/surface/src/tactilebridge.rs +++ b/crates/surface/src/tactilebridge.rs @@ -874,7 +874,8 @@ pub fn import_lp5(bytes: &[u8]) -> Result<(Profile, Report), String> { let pname = page.get("displayName").and_then(Value::as_str).unwrap_or("Page").to_string(); let mut bindings = BTreeMap::new(); for ctl in page.get("controls").and_then(Value::as_array).into_iter().flatten().take(64) { - let Some(id) = ctl.get("controlId").and_then(Value::as_u64) else { continue }; + // (an id from the file: only one some device has is taken) + let Some(id) = ctl.get("controlId").and_then(Value::as_u64).filter(|n| *n < 64) else { continue }; let action = ctl.get(if rotate { "rotateAction" } else { "pressAction" }).and_then(Value::as_str).unwrap_or(""); // "$______" let Some(key) = action.rsplit("___").next().filter(|k| !k.is_empty() && *k != action) else { continue }; @@ -886,6 +887,9 @@ pub fn import_lp5(bytes: &[u8]) -> Result<(Profile, Report), String> { (false, "Loupedeck71", n) => format!("pad.{}", n + 1), (false, _, n) => format!("key.{}", n + 1), }; + if crate::devices::find_control(&slot).is_none() { + continue; + } if let Some(b) = report.note(format!("{pname}: {slot} ({key})"), key) { bindings.insert(slot, b); } @@ -1045,6 +1049,16 @@ mod tests { // encoder 0 (Highlight) is the roller, encoder 1 (Shadow) the big dial ([PageGroup::Dials].as_slice(), &Binding::value("light.shadows"), &Binding::value("light.highlights")) ); + // ids no device has (or that overflow) are left out, not wrapped round or panicked on + let hostile = lp5( + "Loupedeck70", + json!([{"displayName": "Junk", "controls": [ + {"controlId": u64::MAX, "pressAction": "$CaptureOne___CaptureOneCmd___PreviousImage"}, + {"controlId": 99, "pressAction": "$CaptureOne___CaptureOneCmd___PreviousImage"}]}]), + json!([{"displayName": "Junk dials", "controls": [{"controlId": u64::MAX, "rotateAction": "$CaptureOne___CaptureOneAdj___Highlight"}]}]), + ); + let (p, _) = import_lp5(&hostile).unwrap(); + assert!(p.pages.iter().all(|pg| pg.bindings.is_empty()), "{:?}", p.pages); assert!(import_lp5(b"not a zip").is_err()); assert!(import_lp5(&make_zip(&[("ProfileInfo.json", b"{\"layout\": 5}", false)])).is_err()); } diff --git a/crates/ui-egui/src/panels/controls.rs b/crates/ui-egui/src/panels/controls.rs index 8ffb866dd50..c1afa9f6439 100644 --- a/crates/ui-egui/src/panels/controls.rs +++ b/crates/ui-egui/src/panels/controls.rs @@ -505,7 +505,17 @@ fn loupedeck_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max ); ui.horizontal_wrapped(|ui| { // Loupedeck's own profiles on this computer, the last changed first: pick one, Import - let found = crate::surface::loupedeck_profiles(); + // (listed once, then again every 10 s at most: the folders aren't read every frame) + let now = ui.ctx().input(|i| i.time); + let cache = egui::Id::new("surfaceLoupedeckFound"); + let found = match ui.ctx().data(|d| d.get_temp::<(f64, Vec<(String, std::path::PathBuf)>)>(cache)) { + Some((at, found)) if now - at < 10.0 && now >= at => found, + _ => { + let found = crate::surface::loupedeck_profiles(); + ui.ctx().data_mut(|d| d.insert_temp(cache, (now, found.clone()))); + found + } + }; if !found.is_empty() { let mut pick = ui.ctx().data(|d| d.get_temp::(egui::Id::new("surfaceLoupedeckPick"))).unwrap_or(0).min(found.len() - 1); ui.label(RichText::new(tr("Loupedeck profile")).color(t.text_label)); @@ -1270,6 +1280,8 @@ fn pages_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { if button(ui, "surfaceAddPage", "Add page") { let name = app.surface.editor.new_name.trim().to_string(); let name = if name.is_empty() { format!("Page {}", profile.pages.len() + 1) } else { name }; + // (pages are found by name: a second one of the same name could never be edited) + let name = unique_name(&name, |n| profile.page(n).is_some()); edit_profile(app, |p| p.pages.push(ls::Page { name: name.clone(), groups: vec![PageGroup::Keys], ..Default::default() })); app.surface.editor.new_name.clear(); } @@ -1431,6 +1443,38 @@ fn connection(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } +/// `base`, or `base 2`, `base 3`… : the first that isn't `taken` (profiles and pages are found by +/// name, so two of one name would leave the second unreachable). +pub(crate) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String { + if !taken(base) { + return base.to_string(); + } + (2..1000).map(|n| format!("{base} {n}")).find(|n| !taken(n)).unwrap_or_else(|| format!("{base} {}", 1000)) +} + +/// Duplicate the active profile as `name` (or " copy"), made unique, and make it active. +pub(crate) fn duplicate_profile(s: &mut ls::SurfaceSettings, name: &str) -> bool { + let Some(mut p) = s.active_profile().cloned() else { return false }; + let base = if name.is_empty() { format!("{} copy", p.name) } else { name.to_string() }; + p.name = unique_name(&base, |n| s.profiles.iter().any(|q| q.name == n)); + p.description.clear(); + s.profile = p.name.clone(); + s.profiles.push(p); + true +} + +/// Delete the active profile; the first one left becomes active (the last one is kept). +pub(crate) fn delete_profile(s: &mut ls::SurfaceSettings) { + if s.profiles.len() < 2 { + return; + } + let cur = s.profile.clone(); + s.profiles.retain(|p| p.name != cur); + if let Some(first) = s.profiles.first() { + s.profile = first.name.clone(); + } +} + fn profiles(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { heading(ui, t, "Profiles"); let names: Vec = app.surface.settings().profiles.iter().map(|p| p.name.clone()).collect(); @@ -1441,12 +1485,7 @@ fn profiles(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { crate::text_field::TextField::singleline("field:surfaceProfileName", &mut app.surface.editor.new_name).hint(tr("Name")).width(160.0).show(ui); if button(ui, "surfaceDuplicate", "Duplicate") { let name = app.surface.editor.new_name.trim().to_string(); - let s = app.surface.runtime.settings_mut(); - if let Some(mut p) = s.active_profile().cloned() { - p.name = if name.is_empty() { format!("{} copy", p.name) } else { name }; - p.description.clear(); - s.profile = p.name.clone(); - s.profiles.push(p); + if duplicate_profile(app.surface.runtime.settings_mut(), &name) { app.surface.editor.new_name.clear(); app.surface.changed(); } @@ -1465,9 +1504,7 @@ fn profiles(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } if names.len() > 1 && button(ui, "surfaceDeleteProfile", "Delete") { - let s = app.surface.runtime.settings_mut(); - let cur = s.profile.clone(); - s.profiles.retain(|p| p.name != cur); + delete_profile(app.surface.runtime.settings_mut()); app.surface.changed(); } if button(ui, "surfaceRestore", "Add the built-in profiles") { diff --git a/crates/ui-egui/src/surface.rs b/crates/ui-egui/src/surface.rs index 5c99ec6e134..f17c35ac2c3 100644 --- a/crates/ui-egui/src/surface.rs +++ b/crates/ui-egui/src/surface.rs @@ -158,6 +158,8 @@ fn seed() -> Vec { h.write_u128(web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); out.extend_from_slice(&h.finish().to_le_bytes()); } + // (the web build has no process id: std panics there) + #[cfg(not(target_arch = "wasm32"))] out.extend_from_slice(&std::process::id().to_le_bytes()); out } diff --git a/crates/ui-egui/src/tests_surface.rs b/crates/ui-egui/src/tests_surface.rs index b1469004e8c..d0ac169f58e 100644 --- a/crates/ui-egui/src/tests_surface.rs +++ b/crates/ui-egui/src/tests_surface.rs @@ -683,3 +683,28 @@ fn a_dial_refuses_a_one_press_action_dropped_on_it() { assert_eq!(*h.app.surface.settings(), before, "nothing changed"); assert!(h.app.surface.editor.message.as_deref().is_some_and(|m| m.contains("dial")), "{:?}", h.app.surface.editor.message); } + +/// Profiles are found by name: Duplicate twice makes two names, a typed name that is taken gets a +/// number, and deleting the active profile makes another one active instead of leaving none. +#[test] +fn duplicated_profiles_get_their_own_names_and_deleting_one_keeps_one_active() { + use crate::panels::controls::{delete_profile, duplicate_profile, unique_name}; + let mut s = lightcraft_surface::SurfaceSettings::default(); + let first = s.profile.clone(); + assert!(duplicate_profile(&mut s, "")); + assert!(duplicate_profile(&mut s, "")); + let names: Vec<&str> = s.profiles.iter().map(|p| p.name.as_str()).collect(); + let unique: std::collections::BTreeSet<&str> = names.iter().copied().collect(); + assert_eq!(unique.len(), names.len(), "{names:?}"); + assert!(duplicate_profile(&mut s, &first)); + assert_eq!(s.profile, format!("{first} 2")); + assert!(s.active_profile().is_some()); + delete_profile(&mut s); + assert!(s.active_profile().is_some(), "another profile is active: {}", s.profile); + while s.profiles.len() > 1 { + delete_profile(&mut s); + } + delete_profile(&mut s); + assert_eq!(s.profiles.len(), 1, "the last profile stays"); + assert_eq!(unique_name("Page 1", |n| n == "Page 1" || n == "Page 1 2"), "Page 1 3"); +} diff --git a/docs/control-surfaces.md b/docs/control-surfaces.md index 8baff5d7bde..a4e7774d94f 100644 --- a/docs/control-surfaces.md +++ b/docs/control-surfaces.md @@ -163,7 +163,7 @@ clamped into range on reading. ```jsonc { - "version": 1, // format version + "version": 3, // format version "enabled": true, // surfaces may connect (the listener runs) "port": 7981, "profile": "Wedding", // the profile in use @@ -239,7 +239,7 @@ In-process requests (headless scripts, tests) count as paired. | Method | Params | Result | Paired? | |---|---|---|---| | `surface.hello` | `{protocol: 1, client, name?, token?}` | `{protocol, app, version, paired, enabled, devices: [{id, name, controls: [{id, kind, label}]}]}`; a valid token pairs this connection | no | -| `surface.pair` | `{client, name}` → new or open request; `{request}` → poll | `{status: "pending", request, code}` / `{status: "approved", token}` (once) / `{status: "denied"}` | no | +| `surface.pair` | `{client, name}` → a new request (one the same client id had waiting is withdrawn); `{request}` → poll | `{status: "pending", request, code}` / `{status: "approved", token}` (once) / `{status: "denied"}` | no | | `surface.icons` | `{names?: [..]}` (all when omitted) | `{name: svg}` | no | | `surface.catalog` | — | `{groups: [..], entries: [{key, group, label, icon, value}]}`: every action in categories, labels in the app's language (`lightcraft_surface::catalog`); `key` is stable (`v.light.exposure`, `c.photo.rate.rating-5`, `s.applyToSelected`) | no | | `surface.subscribe` | `{device?: "mx-creative-console"}` | `{layout}`; then `surface.layout` events whenever it changes | yes | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index bee43bc1617..29b2e840a24 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -19,7 +19,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra | Card readers / cameras as import sources | ✅ (devices panel, eject after import) | ✅ mounted volumes with DCIM | ✅ | ✅ | — | 🟡 no eject-after-import check, no MTP / PTP phones | | Tethered capture | ✅ Classic (Canon, Nikon, Sony, Leica) | ⬜ | ⬜ | ⬜ | — | ⬜ | | Printers | ✅ Print module, printer colour management | ⬜ (PDF contact sheets only) | ⬜ | ⬜ | — | ⬜ | -| Control surfaces (MIDI / Loupedeck via plug-ins) | via SDK plug-ins | built-in surface engine ([control-surfaces.md](control-surfaces.md)): profiles and pages, pages that follow the tool, dial feel and acceleration, one undo step per turn, apply to every selected photo, on-screen readout, Settings ▸ Controls with a Keys and Dials window drawing each device as it is laid out (action picker by category, drag and drop, Touch to find), the Actions Ring's slots, pairing; Logitech MX Creative Console through the LightCraft Logi plugin, installed from Settings ▸ Controls, with LightCraft's actions listed in Logi Options+; the Loupedeck+ through the same plugin (works as labelled, imports a Loupedeck profile's layout); TactileBridge setups import | same (plugin verified on Windows) | engine and protocol, no Logi Options+ there | — | 🟡 MX Creative Console ✅; Loupedeck+ (untested on the hardware); MIDI and Tangent panels not yet | +| Control surfaces (MIDI / Loupedeck via plug-ins) | via SDK plug-ins | built-in surface engine ([control-surfaces.md](control-surfaces.md)): profiles and pages, pages that follow the tool, dial feel and acceleration, one undo step per turn, apply to every selected photo, on-screen readout, Settings ▸ Controls with a Keys and Dials window drawing each device as it is laid out (action picker by category, drag and drop, Touch to find), the Actions Ring's slots, pairing; Logitech MX Creative Console through the LightCraft Logi plugin (Settings ▸ Controls installs it on Windows; on macOS, open `LightCraft.lplug4`), with LightCraft's actions listed in Logi Options+; the Loupedeck+ through the same plugin (works as labelled, imports a Loupedeck profile's layout); TactileBridge setups import | same (plugin verified on Windows) | engine and protocol, no Logi Options+ there | — | 🟡 MX Creative Console ✅; Loupedeck+ (untested on the hardware); MIDI and Tangent panels not yet | | Multi-core CPU | ✅ | ✅ worker pools, parallel JPEG decode, parallel import copy | ✅ | ✅ | single thread | ✅ | | Memory pressure | managed | ✅ memory budget, `crates/sysmem` returns allocator pages on macOS | ✅ budget | ✅ budget | — | ✅ | diff --git a/docs/whats-new.md b/docs/whats-new.md index c2c91df7ac2..7ddaf4a9a56 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -5,7 +5,7 @@ ### Control surfaces - **Edit from a console.** LightCraft has its own control-surface engine (ported from TactileBridge): the Logitech MX Creative Console's keys, dials and Actions Ring, and the Loupedeck+, drive LightCraft through the LightCraft Logi - plugin, which Settings ▸ Controls installs. Dials move a slider with acceleration and fine control; a whole turn + plugin, which Settings ▸ Controls installs on Windows (on macOS, open `LightCraft.lplug4`). Dials move a slider with acceleration and fine control; a whole turn is one undo step, on the active photo or every selected one; keys run any command. - **Pages that follow what you do:** separate pages for editing, masks, the brush, crop and more, chosen by the tool in use; a short readout on the photo shows what a dial or key just did. From 6d39567f121062a8ba79f6d5c6e39402f0a2b8c5 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 05:00:40 +1000 Subject: [PATCH 05/16] HW-SURFACE: plain wording in two control-server comments Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/control_server.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/apps/lightcraft/src/control_server.rs b/apps/lightcraft/src/control_server.rs index 859319abd55..5bd6d9d3bb7 100644 --- a/apps/lightcraft/src/control_server.rs +++ b/apps/lightcraft/src/control_server.rs @@ -314,9 +314,9 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) - /// Methods whose requests are pipelined: the next line is read (and handed to the app) without /// waiting for this one's reply, so a control surface's dial ticks never queue up one per frame in -/// the socket (TEST-NOTES 2026-10-16 item 8: a knob turned quickly sent ticks faster than the app -/// drew frames, and they drained seconds late, presses included). The app still runs them in -/// order, and their replies go out in order, after the replies to every earlier request. +/// the socket (a knob turned quickly sent ticks faster than the app drew frames, and they drained +/// seconds late, presses included). The app still runs them in order, and their replies go out in +/// order, after the replies to every earlier request. pub const PIPELINED: &[&str] = &["surface.input"]; /// Requests of one connection handed to the app but not answered yet, at most (the reader waits @@ -717,12 +717,11 @@ mod tests { stop.store(true, Ordering::SeqCst); } - /// TEST-NOTES 2026-10-16 item 8: a knob turned fast sends a tick per request, faster than the - /// app draws frames. Ticks used to wait for a frame each (the connection read its next request - /// only after the reply), so they queued in the socket and were applied seconds late, a press - /// behind them "clicking itself" later. Now hundreds of ticks sent at once, with slow frames - /// (40 ms), are all applied within a few frames, the value is their sum, and a press sent - /// after them runs in the same breath. + /// A knob turned fast sends a tick per request, faster than the app draws frames. Ticks used to + /// wait for a frame each (the connection read its next request only after the reply), so they + /// queued in the socket and were applied seconds late, a press behind them "clicking itself" + /// later. Now hundreds of ticks sent at once, with slow frames (40 ms), are all applied within a + /// few frames, the value is their sum, and a press sent after them runs in the same breath. #[test] fn a_burst_of_dial_ticks_is_applied_within_a_few_frames_without_a_backlog() { use std::time::Instant; From eff519fb27d812e748cec70f028fd54407dfefec Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 11:53:52 +1000 Subject: [PATCH 06/16] HW-SURFACE: egui 0.37 ids (Id::unique, Ui::scope_id) and register_geometry for window-level rects Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/controls.rs | 62 ++++++++++++------------ crates/ui-egui/src/panels/surface_osd.rs | 4 +- crates/ui-egui/src/surface_icons.rs | 2 +- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/panels/controls.rs b/crates/ui-egui/src/panels/controls.rs index a16f26616c1..f2923b229a9 100644 --- a/crates/ui-egui/src/panels/controls.rs +++ b/crates/ui-egui/src/panels/controls.rs @@ -97,25 +97,25 @@ fn device_status(app: &LightcraftApp, drawing: Drawing) -> (bool, &'static str) fn slider(ui: &mut egui::Ui, id: &str, v: &mut f64, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> bool { let r = ui.add(egui::Slider::new(v, range).fixed_decimals(decimals).suffix(suffix)); - register(ui.ctx(), format!("slider:{id}"), r.rect); + register(ui, format!("slider:{id}"), r.rect); r.changed() } fn slider_u32(ui: &mut egui::Ui, id: &str, v: &mut u32, range: std::ops::RangeInclusive, suffix: &str) -> bool { let r = ui.add(egui::Slider::new(v, range).suffix(suffix)); - register(ui.ctx(), format!("slider:{id}"), r.rect); + register(ui, format!("slider:{id}"), r.rect); r.changed() } fn button(ui: &mut egui::Ui, id: &str, label: &str) -> bool { let r = ui.button(tr(label)); - register(ui.ctx(), format!("button:{id}"), r.rect); + register(ui, format!("button:{id}"), r.rect); r.clicked() } fn button_enabled(ui: &mut egui::Ui, id: &str, label: &str, enabled: bool) -> bool { let r = ui.add_enabled(enabled, egui::Button::new(tr(label))); - register(ui.ctx(), format!("button:{id}"), r.rect); + register(ui, format!("button:{id}"), r.rect); r.clicked() } @@ -194,7 +194,7 @@ pub fn editor_window(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool let screen = ctx.content_rect(); let mut open = true; let r = egui::Window::new(tr("Keys and Dials")) - .id(egui::Id::new("surfaceEditorWindow")) + .id(egui::Id::unique("surfaceEditorWindow")) // over the Settings window it was opened from .order(egui::Order::Foreground) .open(&mut open) @@ -213,7 +213,7 @@ pub fn editor_window(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool layout_section(app, ui, &t, max_h); }); if let Some(r) = r { - register(ctx, "window:surfaceEditor", r.response.rect); + crate::widgets::register_geometry(ctx, "window:surfaceEditor", r.response.rect); } if !open && !blocked { app.surface.editor.window = false; @@ -228,7 +228,7 @@ fn learn_and_listen(app: &mut LightcraftApp, ctx: &egui::Context) { app.surface.editor.window = true; // a Loupedeck+ colour knob: show the colour mode it was turned in if let Some(n) = c.strip_prefix("ld.r").and_then(|n| n.parse::().ok()).filter(|n| (1..=32).contains(n)) { - ctx.data_mut(|d| d.insert_temp(egui::Id::new("surfaceLoupedeckMode"), (n - 1) / 8)); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("surfaceLoupedeckMode"), (n - 1) / 8)); } app.surface.editor.control = Some(c); app.surface.editor.params_text.clear(); @@ -269,7 +269,7 @@ fn top_bar(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } }); - register(ui.ctx(), "combo:surfaceProfile", r.response.rect); + register(ui, "combo:surfaceProfile", r.response.rect); }); } @@ -346,8 +346,8 @@ fn device_bar(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { }; ui.painter().circle_filled(pos2(rect.left() + 12.0, rect.center().y), 3.5, dot); ui.painter().galley(pos2(rect.left() + 22.0, rect.center().y - galley.size().y / 2.0), galley, color); - let r = ui.interact(rect, ui.id().with(("surfaceDevice", *id)), Sense::click()); - register(ui.ctx(), format!("button:surfaceDevice-{id}"), r.rect); + let r = ui.interact(rect, ui.scope_id().with(("surfaceDevice", *id)), Sense::click()); + register(ui, format!("button:surfaceDevice-{id}"), r.rect); let (_, text) = device_status(app, *drawing); let r = r.on_hover_text(tr(text)); if r.clicked() { @@ -426,7 +426,7 @@ fn layout_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: } } }); - register(ui.ctx(), "combo:surfaceToolPage", r.response.rect); + register(ui, "combo:surfaceToolPage", r.response.rect); } }); ui.add_space(4.0); @@ -511,7 +511,7 @@ fn loupedeck_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max // Loupedeck's own profiles on this computer, the last changed first: pick one, Import // (listed once, then again every 10 s at most: the folders aren't read every frame) let now = ui.ctx().input(|i| i.time); - let cache = egui::Id::new("surfaceLoupedeckFound"); + let cache = egui::Id::unique("surfaceLoupedeckFound"); let found = match ui.ctx().data(|d| d.get_temp::<(f64, Vec<(String, std::path::PathBuf)>)>(cache)) { Some((at, found)) if now - at < 10.0 && now >= at => found, _ => { @@ -521,7 +521,7 @@ fn loupedeck_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max } }; if !found.is_empty() { - let mut pick = ui.ctx().data(|d| d.get_temp::(egui::Id::new("surfaceLoupedeckPick"))).unwrap_or(0).min(found.len() - 1); + let mut pick = ui.ctx().data(|d| d.get_temp::(egui::Id::unique("surfaceLoupedeckPick"))).unwrap_or(0).min(found.len() - 1); ui.label(RichText::new(tr("Loupedeck profile")).color(t.text_label)); let r = egui::ComboBox::from_id_salt("surfaceLoupedeckProfile").selected_text(found[pick].0.clone()).width(240.0).show_ui(ui, |ui| { for (i, (name, path)) in found.iter().enumerate() { @@ -530,8 +530,8 @@ fn loupedeck_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max } } }); - register(ui.ctx(), "combo:surfaceLoupedeckProfile", r.response.rect); - ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("surfaceLoupedeckPick"), pick)); + register(ui, "combo:surfaceLoupedeckProfile", r.response.rect); + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique("surfaceLoupedeckPick"), pick)); if button(ui, "surfaceImportLoupedeck", "Import") { let r = app_run_import(app, &found[pick].1.to_string_lossy()); report(app, r); @@ -554,7 +554,7 @@ fn loupedeck_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max let selected = app.surface.editor.control.clone(); let mut clicked: Option = None; // the P1–P8 knobs send other numbers in each of the console's colour modes: show one mode - let mode_id = egui::Id::new("surfaceLoupedeckMode"); + let mode_id = egui::Id::unique("surfaceLoupedeckMode"); let mut mode = ui.ctx().data(|d| d.get_temp::(mode_id)).unwrap_or(0).min(3); let mut grid = |app: &LightcraftApp, ui: &mut egui::Ui| { let cell = |ui: &mut egui::Ui, id: &str, size: f32, clicked: &mut Option| { @@ -574,8 +574,8 @@ fn loupedeck_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max let name_rect = Rect::from_min_size(pos2(area.left(), face.bottom() + 1.0), vec2(size, 14.0)); if let Some(p) = press { let chip = Rect::from_center_size(pos2(face.right() - 9.0, face.bottom() - 6.0), vec2(16.0, 12.0)); - let r = ui.interact(chip, ui.id().with(("surfacePress", &p)), Sense::click()); - register(ui.ctx(), format!("button:surfaceControl-{p}"), chip); + let r = ui.interact(chip, ui.scope_id().with(("surfacePress", &p)), Sense::click()); + register(ui, format!("button:surfaceControl-{p}"), chip); let on = selected.as_deref() == Some(p.as_str()); let has = profile.base.contains_key(&p) || ls::loupedeck::default_binding(&p).is_some(); ui.painter().rect_filled( @@ -773,13 +773,13 @@ fn draw_ring(ui: &mut egui::Ui, t: &Tokens, w: f32, slots: &[View], selected: Op #[allow(clippy::too_many_arguments)] fn draw_control(ui: &mut egui::Ui, t: &Tokens, rect: Rect, control: &str, view: (&str, Option<&str>, bool), selected: bool, round: bool) -> bool { let (label, icon, inherited) = view; - let id = ui.id().with(("surfaceControl", control)); + let id = ui.scope_id().with(("surfaceControl", control)); let r = ui.interact(rect, id, Sense::click()); - register(ui.ctx(), format!("button:surfaceControl-{control}"), rect); + register(ui, format!("button:surfaceControl-{control}"), rect); // an action dragged from the list onto this control: it does that from now on let dragging = r.dnd_hover_payload::().is_some(); if let Some(p) = r.dnd_release_payload::() { - ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new(DROP_ID), (control.to_string(), (*p).clone()))); + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique(DROP_ID), (control.to_string(), (*p).clone()))); } let p = ui.painter(); let fill = if r.hovered() || dragging { Color32::from_gray(42) } else { Color32::from_gray(26) }; @@ -840,7 +840,7 @@ const DROP_ID: &str = "surfaceDrop"; fn drag_preview(ui: &egui::Ui, t: &Tokens) { let Some(d) = egui::DragAndDrop::payload::(ui.ctx()) else { return }; let Some(at) = ui.ctx().pointer_latest_pos() else { return }; - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("surfaceDragPreview"))); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("surfaceDragPreview"))); let galley = painter.layout_no_wrap(d.label.clone(), FontId::proportional(12.0), t.text); let rect = Rect::from_min_size(at + vec2(14.0, 6.0), vec2(galley.size().x + 36.0, 26.0)); painter.rect_filled(rect, CornerRadius::same(5), t.inset); @@ -854,7 +854,7 @@ fn drag_preview(ui: &egui::Ui, t: &Tokens) { /// An action dropped on a control this frame: set it (on `page`) and select the control. A dial /// takes only values and page turns. fn apply_drop(app: &mut LightcraftApp, ui: &egui::Ui, page: &str) { - let id = egui::Id::new(DROP_ID); + let id = egui::Id::unique(DROP_ID); let Some((control, d)) = ui.ctx().data_mut(|m| { let v = m.get_temp::<(String, DragAction)>(id); m.remove::<(String, DragAction)>(id); @@ -894,8 +894,8 @@ fn draw_keypad(ui: &mut egui::Ui, t: &Tokens, w: f32, keys: &[View], selected: O for (i, (s, glyph)) in [(-1, "‹"), (1, "›")].into_iter().enumerate() { let x = if s < 0 { body.left() + pad } else { body.right() - pad - bw }; let r = Rect::from_min_size(pos2(x, y), vec2(bw, 26.0)); - let resp = ui.interact(r, ui.id().with(("surfacePageButton", i)), Sense::click()); - register(ui.ctx(), format!("button:surfaceKeypadPage-{}", if s < 0 { "previous" } else { "next" }), r); + let resp = ui.interact(r, ui.scope_id().with(("surfacePageButton", i)), Sense::click()); + register(ui, format!("button:surfaceKeypadPage-{}", if s < 0 { "previous" } else { "next" }), r); ui.painter().rect_filled(r, CornerRadius::same(6), if resp.hovered() { Color32::from_gray(42) } else { Color32::from_gray(30) }); ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, glyph, FontId::proportional(16.0), t.text); if resp.on_hover_text(tr(if s < 0 { "Previous page" } else { "Next page" })).clicked() { @@ -1213,7 +1213,7 @@ fn action_picker(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, control } ui.add(egui::Button::selectable(selected, label.as_str())).interact(Sense::click_and_drag()) }); - register(ui.ctx(), format!("item:surfaceAction-{key}"), resp.inner.rect); + register(ui, format!("item:surfaceAction-{key}"), resp.inner.rect); // drag it onto a key, button or dial of the drawing resp.inner.dnd_set_drag_payload(DragAction { binding: b.clone(), label: label.clone(), icon }); if resp.inner.clicked() { @@ -1221,7 +1221,7 @@ fn action_picker(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, control } } }); - register(ui.ctx(), format!("group:surfaceActions-{g}"), r.header_response.rect); + register(ui, format!("group:surfaceActions-{g}"), r.header_response.rect); } if shown == 0 { hint(ui, t, "No action matches."); @@ -1333,7 +1333,7 @@ fn contexts(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } }); - register(ui.ctx(), format!("combo:surfaceContext-{key}"), r.response.rect); + register(ui, format!("combo:surfaceContext-{key}"), r.response.rect); }); } } @@ -1410,7 +1410,7 @@ fn connection(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { row(ui, t, "Port", |ui| { let mut port = u32::from(app.surface.settings().port); let r = ui.add(egui::DragValue::new(&mut port).range(1024..=65535)); - register(ui.ctx(), "drag:surfacePort", r.rect); + register(ui, "drag:surfacePort", r.rect); if r.changed() { app.surface.runtime.settings_mut().port = u16::try_from(port).unwrap_or(ls::settings::DEFAULT_PORT); app.surface.changed(); @@ -1612,7 +1612,7 @@ fn feel(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } } }); - register(ui.ctx(), "combo:surfaceTuningTarget", r.response.rect); + register(ui, "combo:surfaceTuningTarget", r.response.rect); }); let mut tu = app.surface.settings().tuning_of(&target); let mut c = false; @@ -1631,7 +1631,7 @@ fn feel(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ui.label(RichText::new(tr("Presets for every value:")).color(t.text_label)); for (name, desc, tuning) in ls::settings::tuning_presets() { let r = ui.button(tr(name)).on_hover_text(tr(desc)); - register(ui.ctx(), format!("button:surfacePreset-{name}"), r.rect); + register(ui, format!("button:surfacePreset-{name}"), r.rect); if r.clicked() { let s = app.surface.runtime.settings_mut(); for spec in ls::targets::all_targets() { diff --git a/crates/ui-egui/src/panels/surface_osd.rs b/crates/ui-egui/src/panels/surface_osd.rs index f2ad764cd1b..c86c0688a9a 100644 --- a/crates/ui-egui/src/panels/surface_osd.rs +++ b/crates/ui-egui/src/panels/surface_osd.rs @@ -83,12 +83,12 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { let opacity = osd.opacity.clamp(0.1, 1.0) as f32 * fade; let (r, g, b) = ls::settings::rgb(&osd.background).unwrap_or((32, 32, 32)); let t = Tokens::get(ctx); - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("surface_osd"))); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("surface_osd"))); let width = WIDTH.min(area.width() - 16.0).max(160.0); let rect = Rect::from_center_size(pos2(center_x, y), vec2(width, HEIGHT)); painter.rect_filled(rect, HEIGHT / 2.0, Color32::from_rgb(r, g, b).gamma_multiply(opacity)); painter.rect_stroke(rect, HEIGHT / 2.0, egui::Stroke::new(1.0, Color32::from_white_alpha(40).gamma_multiply(fade)), egui::StrokeKind::Inside); - crate::widgets::register(ctx, "osd:surface", rect); + crate::widgets::register_geometry(ctx, "osd:surface", rect); let title_c = Color32::from_rgb(220, 220, 220).gamma_multiply(fade); let value_c = Color32::WHITE.gamma_multiply(fade); // the action's icon (the same one the surface's key shows) at the left of the pill diff --git a/crates/ui-egui/src/surface_icons.rs b/crates/ui-egui/src/surface_icons.rs index e9acf3be3c2..0fe65bb7411 100644 --- a/crates/ui-egui/src/surface_icons.rs +++ b/crates/ui-egui/src/surface_icons.rs @@ -13,7 +13,7 @@ type Cache = Arc>>>; const MAX_CACHED: usize = 1024; fn cache(ctx: &egui::Context) -> Cache { - ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::new("surfaceIcons")).clone()) + ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("surfaceIcons")).clone()) } /// Rasterise an SVG to `px` × `px` straight RGBA (`None`: not an SVG resvg reads). From 2450d2aceac97e9d3a0db8a0dda32d9ae78967b2 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 12:26:42 +1000 Subject: [PATCH 07/16] HW-SURFACE: a client that stops reading loses its connection; Loupedeck actions for no control are reported, not kept Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/control_server.rs | 43 ++++++++++++++++++++++++++- crates/surface/src/loupedeck.rs | 15 ++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/apps/lightcraft/src/control_server.rs b/apps/lightcraft/src/control_server.rs index 5bd6d9d3bb7..c3469af0ed1 100644 --- a/apps/lightcraft/src/control_server.rs +++ b/apps/lightcraft/src/control_server.rs @@ -13,7 +13,7 @@ //! Controls) serves nothing but `surface.*` methods, which need pairing. use std::io::{BufRead, BufReader, Read, Write}; -use std::net::{TcpListener, TcpStream}; +use std::net::{Shutdown, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; use std::sync::{Arc, Mutex, PoisonError}; @@ -145,7 +145,10 @@ fn pump_events(events: Receiver, mut out: LineWriter, open: Arc { if writeln!(out, "{v}").and_then(|()| out.flush()).is_err() { + // (a client that stopped reading: the write timed out. Closing the socket + // also wakes the connection's reader, so its slot is freed) open.store(false, Ordering::SeqCst); + let _ = out.out.shutdown(Shutdown::Both); return; } } @@ -160,6 +163,8 @@ const IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60); /// How long a request waits for its reply. const REPLY_TIMEOUT: Duration = Duration::from_secs(60); +/// How long a write to a client may block: one that stopped reading loses its connection. +const WRITE_TIMEOUT: Duration = Duration::from_secs(30); /// A request the app has not picked up while it drew no frame for this long is given up: the /// window is not being redrawn (on Wayland, a window on a hidden workspace or minimized gets no /// frame callbacks, so the app's loop is paused: issue #718). @@ -181,6 +186,10 @@ fn serve(stream: TcpStream, tx: &Sender, ctx: &egui::Context, mo log::warn!("control connection closed: could not set idle read timeout: {e}"); return; } + if let Err(e) = stream.set_write_timeout(Some(WRITE_TIMEOUT)) { + log::warn!("control connection closed: could not set write timeout: {e}"); + return; + } let stream = Arc::new(stream); let conn = NEXT_CONN.fetch_add(1, Ordering::SeqCst); let open = Arc::new(AtomicBool::new(true)); @@ -567,6 +576,38 @@ mod tests { } /// A pushed event and a reply never share a line, and events stop when the peer goes. + /// A subscriber that stops reading: the event writer gives up when a write times out, and + /// closes the connection, so the slot comes free. + #[test] + fn a_client_that_stops_reading_loses_its_connection() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let client = TcpStream::connect(addr).unwrap(); + let (server, _) = listener.accept().unwrap(); + server.set_write_timeout(Some(Duration::from_millis(200))).unwrap(); + let open = Arc::new(AtomicBool::new(true)); + let (etx, erx) = channel::(); + let out = LineWriter::new(Arc::new(server)); + let pump = { + let open = Arc::clone(&open); + std::thread::spawn(move || pump_events(erx, out, open)) + }; + // far more than the socket buffers hold, never read + let big = "x".repeat(64 * 1024); + for i in 0..1000 { + if etx.send(json!({"event": "surface.layout", "n": i, "pad": big})).is_err() { + break; + } + } + let t = std::time::Instant::now(); + while !pump.is_finished() { + assert!(t.elapsed() < Duration::from_secs(20), "the writer never gave up"); + std::thread::sleep(Duration::from_millis(20)); + } + assert!(!open.load(Ordering::SeqCst)); + drop(client); + } + #[test] fn pushed_events_and_replies_arrive_as_whole_lines() { let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); diff --git a/crates/surface/src/loupedeck.rs b/crates/surface/src/loupedeck.rs index c1b08c33796..c860fa3841f 100644 --- a/crates/surface/src/loupedeck.rs +++ b/crates/surface/src/loupedeck.rs @@ -501,6 +501,11 @@ pub fn import(bytes: &[u8], preset: &dyn Fn(&str) -> Option) -> Result raw.strip_prefix("LR:").unwrap_or(raw), }; let from = format!("{}: {}", label(&control), pretty(action)); + // (an index the Loupedeck+ has no control for could never be pressed or turned) + if !CONTROLS.iter().any(|c| c.id == control) { + out.report.dropped.push(ReportLine { from, to: String::new(), note: "no such control on the Loupedeck+".into() }); + continue; + } match map_action(action, preset) { Mapped::To(b, note) => { out.report.mapped.push(ReportLine { from, to: b.describe(), note: note.unwrap_or_default().into() }); @@ -577,6 +582,16 @@ mod tests { assert!(out.report.dropped[0].from.contains("Button 76"), "{:?}", out.report.dropped); } + /// An action at an index no control sends is skipped and reported, not kept as a binding. + #[test] + fn an_action_for_no_control_is_reported_not_kept() { + let bytes = profile(&[(0, "$Lightroom___Undo")], &[(43, "$Lightroom___Exposure"), (33, "$Lightroom___Exposure")]); + let out = import(&bytes, &|_| None).unwrap(); + assert!(!out.bindings.contains_key("ld.b0") && !out.bindings.contains_key("ld.r43"), "{:?}", out.bindings); + assert!(out.bindings.contains_key("ld.r33")); + assert_eq!(out.report.dropped.iter().filter(|l| l.note == "no such control on the Loupedeck+").count(), 2, "{:?}", out.report.dropped); + } + #[test] fn bad_files_are_errors() { assert!(import(b"not json", &|_| None).is_err()); From 25fbc8534c1d0f902088fa773e77fa78cf03d1a7 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 13:35:46 +1000 Subject: [PATCH 08/16] HW-SURFACE: refresh Cargo.lock after the main merge Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 207 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 193 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a9a326ab8d5..24a7e936db1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -321,6 +321,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + [[package]] name = "arrayvec" version = "0.7.8" @@ -595,6 +601,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64" version = "0.23.1" @@ -1324,6 +1336,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + [[package]] name = "der" version = "0.7.10" @@ -1799,7 +1817,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1949,6 +1967,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + [[package]] name = "float8" version = "0.6.1" @@ -2801,7 +2825,7 @@ dependencies = [ "image-webp", "moxcms 0.8.1", "num-traits", - "png", + "png 0.18.1", "tiff", "zune-core", "zune-jpeg", @@ -2817,6 +2841,12 @@ dependencies = [ "quick-error 2.0.1", ] +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + [[package]] name = "imgref" version = "1.12.3" @@ -3209,6 +3239,17 @@ dependencies = [ "accesskit_consumer", ] +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + [[package]] name = "kurbo" version = "0.13.1" @@ -3285,6 +3326,7 @@ dependencies = [ "lightcraft-codecs", "lightcraft-engine", "lightcraft-raster", + "lightcraft-surface", "lightcraft-sysmem", "lightcraft-testkit", "lightcraft-ui-egui", @@ -3354,7 +3396,7 @@ dependencies = [ "lightcraft-raster", "lightcraft-testkit", "moxcms 0.9.1", - "png", + "png 0.18.1", "proptest", "rav1e", "ravif", @@ -3691,6 +3733,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "lightcraft-surface" +version = "0.14.0" +dependencies = [ + "lightcraft-develop", + "miniz_oxide 0.9.1", + "serde", + "serde_json", + "sha2", +] + [[package]] name = "lightcraft-sysmem" version = "0.14.0" @@ -3730,8 +3783,10 @@ dependencies = [ "lightcraft-preview", "lightcraft-raster", "lightcraft-slideshow", + "lightcraft-surface", "lightcraft-testkit", "log", + "resvg", "serde", "serde_json", "toml", @@ -3941,7 +3996,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", - "png", + "png 0.18.1", "thiserror 2.0.21", "windows-sys 0.61.2", ] @@ -4612,7 +4667,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4706,7 +4761,7 @@ checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" dependencies = [ "bytemuck", "color", - "kurbo", + "kurbo 0.13.1", "linebender_resource_handle", "smallvec", ] @@ -4771,6 +4826,12 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project" version = "1.1.13" @@ -4858,13 +4919,26 @@ version = "1.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" dependencies = [ - "base64", + "base64 0.23.1", "indexmap", "quick-xml 0.42.0", "serde", "time", ] +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "png" version = "0.18.1" @@ -5422,6 +5496,20 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "resvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" +dependencies = [ + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + [[package]] name = "rfc6979" version = "0.4.0" @@ -5464,6 +5552,9 @@ name = "rgb" version = "0.8.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] [[package]] name = "ring" @@ -5479,6 +5570,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + [[package]] name = "rsa" version = "0.9.10" @@ -5550,7 +5647,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5607,7 +5704,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5933,6 +6030,15 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + [[package]] name = "siphasher" version = "1.0.4" @@ -6079,12 +6185,31 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + [[package]] name = "subtle" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo 0.11.3", + "siphasher", +] + [[package]] name = "syn" version = "2.0.119" @@ -6174,10 +6299,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -6279,6 +6404,32 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.17.16", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "tokio" version = "1.53.1" @@ -6525,7 +6676,7 @@ version = "3.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" dependencies = [ - "base64", + "base64 0.23.1", "flate2", "log", "percent-encoding", @@ -6542,12 +6693,34 @@ version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" dependencies = [ - "base64", + "base64 0.23.1", "http", "httparse", "log", ] +[[package]] +name = "usvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "imagesize", + "kurbo 0.11.3", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "xmlwriter", +] + [[package]] name = "utf8-zero" version = "0.8.1" @@ -7077,7 +7250,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -7464,6 +7637,12 @@ version = "0.8.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + [[package]] name = "xtask" version = "0.14.0" From f8f46d2ecbe3d4d933c52c1b846898961550cfad Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 19:45:37 +1000 Subject: [PATCH 09/16] HW-SURFACE: the Settings section test closes Keys and Dials before clicking under it Since egui 0.37 (#2913) a control-channel click must land on the topmost widget at its point. The Keys and Dials window (16,16 - 996,657 at 1400x900) covers the Settings window's section buttons, so the click was rightly refused. The test now proves the covered button takes no click, closes the window, opens each section, and opens Keys and Dials again from its button. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tests_surface.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tests_surface.rs b/crates/ui-egui/src/tests_surface.rs index d0ac169f58e..747827b2152 100644 --- a/crates/ui-egui/src/tests_surface.rs +++ b/crates/ui-egui/src/tests_surface.rs @@ -269,11 +269,23 @@ fn settings_tab_learn_and_edit_a_key() { p.pages.iter().any(|pg| pg.bindings.get("dial") == Some(&lightcraft_surface::Binding::value("light.highlights"))), "the dial moves Highlights now" ); - // the other sections open + // the other sections open. They are in the Settings window, under the Keys and Dials window + // while that is open: a covered button takes no click, so close it first (as its close box does) + let covered = h.request("ui.clickWidget", json!({"id": "button:surfaceSection-feel"}), T); + assert_eq!(covered["ok"], false, "a section button under the Keys and Dials window can't be clicked: {covered}"); + h.app.surface.editor.window = false; + h.settle(T); + assert!(!h.app.widgets.iter().any(|(w, _)| w == "window:surfaceEditor"), "the Keys and Dials window is closed"); for s in ["pages", "feel", "readout", "setup"] { - assert_eq!(h.request("ui.clickWidget", json!({"id": format!("button:surfaceSection-{s}")}), T)["ok"], true); + assert_eq!(h.request("ui.clickWidget", json!({"id": format!("button:surfaceSection-{s}")}), T)["ok"], true, "{s}"); h.settle(T); + assert_eq!(h.app.surface.editor.section, s); } + // and Keys and Dials opens again from its button + assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceEditKeys"}), T)["ok"], true); + h.settle(T); + assert!(h.app.surface.editor.window); + assert!(h.app.widgets.iter().any(|(w, _)| w == "window:surfaceEditor"), "the Keys and Dials window is back"); assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceDevice-keypad"}), T)["ok"], true); h.settle(T); // make key 5 put Contrast on the dial From ed3fdba0dcfcb5c90e11b87142bfbbfad7e9fa90 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Tue, 27 Oct 2026 01:22:56 +1000 Subject: [PATCH 10/16] HW-SURFACE: review fixes: no surface settings file for --memory, a page cap on .lp5 import, a new port reaches the plugin - A --memory session gets no control-surface store, so it neither reads nor writes control-surfaces.json (like its other settings, issue #164). Test: a_memory_session_has_no_control_surface_store. - An imported .lp5 keeps at most 256 pages (the per-level limits multiply to 32,768), and Profile::sanitize continues each name's suffix counter instead of restarting it, so naming duplicates is linear. Test: a_profile_with_too_many_pages_keeps_the_first_ones. - Changing the port in Settings hands it to the installed Logi plugin once the value is set (not on every drag step), leaving its token and the on/off setting alone. Test: a_changed_port_is_handed_to_the_plugin. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/main.rs | 22 +++++++++++++++------- crates/surface/src/profile.rs | 7 +++++-- crates/surface/src/tactilebridge.rs | 20 +++++++++++++++++++- crates/ui-egui/src/panels/controls.rs | 4 ++++ crates/ui-egui/src/surface_plugin.rs | 13 +++++++++++++ crates/ui-egui/src/tests_surface.rs | 18 ++++++++++++++++++ 6 files changed, 74 insertions(+), 10 deletions(-) diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index d9097378c4a..053a04e8c3b 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -513,8 +513,9 @@ fn file_dialog() -> rfd::FileDialog { } /// The platform services; `cc` is the window the file dialogs belong to (its `egui_ctx` repaints -/// when a dialog closes), and `log_file` is for Help ▸ Open Log Folder. -fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path>) -> Services { +/// when a dialog closes), `log_file` is for Help ▸ Open Log Folder, and a `--memory` session (`in_memory`) keeps its +/// control-surface settings to itself. +fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path>, in_memory: bool) -> Services { let ctx = cc.egui_ctx.clone(); #[cfg(any(target_os = "linux", target_os = "freebsd"))] let _ = DIALOG_PARENT.set(rfd::FileDialog::new().set_parent(cc)); @@ -751,7 +752,7 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path> backup_library: None, restore_library: None, system_theme: appearance::service(), - surface_store: surface_store(), + surface_store: surface_store(in_memory), pick_surface_file: Some(Box::new(|| { file_dialog() .set_title(lightcraft_ui_egui::i18n::tr("Import Control Surface Setup")) @@ -797,9 +798,10 @@ impl lightcraft_ui_egui::surface::SurfaceStore for SurfaceFile { } } -/// Where control-surface settings live (none with `LIGHTCRAFT_NO_PREFS` or no settings folder). -fn surface_store() -> Option> { - if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() { +/// Where control-surface settings live (none in a `--memory` session, which writes nothing (issue #164), with +/// `LIGHTCRAFT_NO_PREFS` or without a settings folder). +fn surface_store(in_memory: bool) -> Option> { + if in_memory || std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() { return None; } config_dir().map(|d| Box::new(SurfaceFile(d.join("control-surfaces.json"))) as Box) @@ -1067,7 +1069,7 @@ fn main() -> eframe::Result { session = session.with_default_sam3_model(); // HDR display: SDR unless the surface, platform and display all allow HDR hdr_display::report(cc.wgpu_render_state.as_ref().map(|r| r.target_format)); - let mut app = LightcraftApp::new(session, services(cc, app_log_file.as_deref())); + let mut app = LightcraftApp::new(session, services(cc, app_log_file.as_deref(), in_memory)); app.set_startup_update_check(true); if let Some(ui) = prefs { app.ui = ui; @@ -1418,6 +1420,12 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A `--memory` session neither reads nor writes the control-surface settings file (CodeRabbit on #2947). + #[test] + fn a_memory_session_has_no_control_surface_store() { + assert!(surface_store(true).is_none()); + } + /// Issue #169: a `--memory` session neither arms the GPU crash sentinel (which would create /// the settings folder) nor removes a marker a crashed launch left; it still reports it, and /// the next ordinary launch finds it, reports it and clears it. diff --git a/crates/surface/src/profile.rs b/crates/surface/src/profile.rs index 2dd400d44a1..9d3f0ee9d92 100644 --- a/crates/surface/src/profile.rs +++ b/crates/surface/src/profile.rs @@ -123,16 +123,19 @@ impl Profile { /// entries that name existing pages. pub fn sanitize(&mut self) { let mut seen = std::collections::BTreeSet::new(); + // the next suffix to try per name: a suffix taken once stays taken, so each is tried once in all + let mut next = std::collections::BTreeMap::::new(); for (i, p) in self.pages.iter_mut().enumerate() { if p.name.trim().is_empty() { p.name = format!("Page {}", i + 1); } let base = p.name.clone(); - let mut n = 2; + let mut n = next.get(&base).copied().unwrap_or(2); while !seen.insert(p.name.clone()) { p.name = format!("{base} {n}"); - n += 1; + n = n.saturating_add(1); } + next.insert(base, n); } let names: std::collections::BTreeSet = self.pages.iter().map(|p| p.name.clone()).collect(); for list in self.contexts.values_mut() { diff --git a/crates/surface/src/tactilebridge.rs b/crates/surface/src/tactilebridge.rs index 8df378e4623..44728babed3 100644 --- a/crates/surface/src/tactilebridge.rs +++ b/crates/surface/src/tactilebridge.rs @@ -855,9 +855,13 @@ fn unique_name(s: &SurfaceSettings, base: &str) -> String { name } +/// The most pages one imported `.lp5` profile keeps. +pub const MAX_IMPORTED_PAGES: usize = 256; + /// Read a Logi profile package (`.lp5`) TactileBridge shipped or the user saved: its pages, with /// TactileBridge actions mapped. Keypad profiles (`Loupedeck70`) give key pages, Dialpad profiles /// (`Loupedeck71`) dial pages and base buttons; Actions Ring profiles (`Loupedeck72`) both. +/// At most [`MAX_IMPORTED_PAGES`] pages are kept: the per-level limits multiply to far more. pub fn import_lp5(bytes: &[u8]) -> Result<(Profile, Report), String> { let info = crate::zip::read_member(bytes, "ProfileInfo.json")?; let text = String::from_utf8_lossy(&info); @@ -898,7 +902,7 @@ pub fn import_lp5(bytes: &[u8]) -> Result<(Profile, Report), String> { if is_pads { // the Dialpad's buttons stay put while its dial pages change profile.base.extend(bindings); - } else { + } else if profile.pages.len() < MAX_IMPORTED_PAGES { let group = if rotate { PageGroup::Dials } else { PageGroup::Keys }; profile.pages.push(Page { name: pname, groups: vec![group], bindings, auto: false }); } @@ -1062,4 +1066,18 @@ mod tests { assert!(import_lp5(b"not a zip").is_err()); assert!(import_lp5(&make_zip(&[("ProfileInfo.json", b"{\"layout\": 5}", false)])).is_err()); } + + /// A small file that lists thousands of same-named pages is cut to [`MAX_IMPORTED_PAGES`] and named quickly + /// (CodeRabbit on #2947). + #[test] + fn a_profile_with_too_many_pages_keeps_the_first_ones() { + let pages = json!(vec![json!({"controls": []}); 64]); + let ws = json!({"pressPages": pages, "rotatePages": pages}); + let info = json!({"deviceType": "Loupedeck70", "layout": {"layoutModes": vec![json!({"workspaces": vec![ws; 16]}); 16]}}); + let text = info.to_string(); + let (p, _) = import_lp5(&make_zip(&[("ProfileInfo.json", text.as_bytes(), true)])).unwrap(); + assert_eq!(p.pages.len(), MAX_IMPORTED_PAGES); + assert_eq!((p.pages[0].name.as_str(), p.pages[1].name.as_str()), ("Page", "Page 2")); + assert_eq!(p.pages[MAX_IMPORTED_PAGES - 1].name, format!("Page {MAX_IMPORTED_PAGES}")); + } } diff --git a/crates/ui-egui/src/panels/controls.rs b/crates/ui-egui/src/panels/controls.rs index f2923b229a9..c30029e156c 100644 --- a/crates/ui-egui/src/panels/controls.rs +++ b/crates/ui-egui/src/panels/controls.rs @@ -1415,6 +1415,10 @@ fn connection(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { app.surface.runtime.settings_mut().port = u16::try_from(port).unwrap_or(ls::settings::DEFAULT_PORT); app.surface.changed(); } + // the plugin learns the new port once it is set (not on every step of a drag or keystroke) + if r.drag_stopped() || r.lost_focus() || (r.changed() && !r.dragged() && !r.has_focus()) { + crate::surface_plugin::provision_port(app); + } match (app.surface.listening, &app.surface.listen_error) { (Some(p), _) => { ui.label(RichText::new(crate::i18n::tr_format!("Listening on 127.0.0.1:{port}", port = p)).size(11.0).color(t.text_dim)); diff --git a/crates/ui-egui/src/surface_plugin.rs b/crates/ui-egui/src/surface_plugin.rs index a0648056058..1a4cbad09e3 100644 --- a/crates/ui-egui/src/surface_plugin.rs +++ b/crates/ui-egui/src/surface_plugin.rs @@ -111,6 +111,19 @@ pub fn auto_setup(app: &mut LightcraftApp) { } } +/// Tell the installed plugin the port LightCraft now listens on (after the user changed it), so it +/// connects there without a restart. The trust token and the on/off setting are left alone. +pub fn provision_port(app: &mut LightcraftApp) { + let Some(i) = installer(app) else { return }; + if i.status().installed.is_none() { + return; + } + if let Err(e) = i.provision(None, app.surface.settings().port) { + log::warn!("Logi plugin: {e}"); + app.surface.plugin.message = Some(Err(e)); + } +} + /// An install or uninstall on its way. pub struct PluginJob { rx: Receiver>, diff --git a/crates/ui-egui/src/tests_surface.rs b/crates/ui-egui/src/tests_surface.rs index 747827b2152..953e4cfd62f 100644 --- a/crates/ui-egui/src/tests_surface.rs +++ b/crates/ui-egui/src/tests_surface.rs @@ -510,6 +510,24 @@ fn an_installed_logi_plugin_works_with_no_setup_and_settings_show_the_edited_pag assert!(!h.app.surface.settings().enabled, "off stays off"); } +/// A port changed in Settings reaches the installed plugin at once, without touching its token +/// (CodeRabbit on #2947). +#[test] +fn a_changed_port_is_handed_to_the_plugin() { + let logi = Arc::new(FakeLogi::default()); + let services = + Services { png: None, surface_store: Some(Box::new(MemStore::default())), surface_plugin: Some(logi.clone()), ..Default::default() }; + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services); + crate::surface_plugin::auto_setup(&mut app); + let token = logi.token.lock().unwrap().clone(); + assert!(token.is_some()); + app.surface.runtime.settings_mut().port = 18123; + app.surface.changed(); + crate::surface_plugin::provision_port(&mut app); + assert_eq!(*logi.port.lock().unwrap(), Some(18123)); + assert_eq!(*logi.token.lock().unwrap(), token, "the token stays"); +} + /// Bind `control` on the key page now showing. fn bind_key(h: &mut Headless, control: &str, b: lightcraft_surface::Binding) { let page = h.app.surface.runtime.pages().get(&lightcraft_surface::PageGroup::Keys).cloned().unwrap(); From 955b031a38eec1bbaf528238d66838a355eab760 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Tue, 27 Oct 2026 08:51:22 +1000 Subject: [PATCH 11/16] HW-SURFACE: an .lp5 import reports only the pages it keeps A page past the 256-page limit is skipped before its controls are read, so the import report no longer lists actions the profile doesn't have. Dialpad button pages still go into the base bindings past the limit. Co-Authored-By: Claude Opus 5.5 --- crates/surface/src/tactilebridge.rs | 39 ++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/surface/src/tactilebridge.rs b/crates/surface/src/tactilebridge.rs index 44728babed3..ed269a2d621 100644 --- a/crates/surface/src/tactilebridge.rs +++ b/crates/surface/src/tactilebridge.rs @@ -875,6 +875,12 @@ pub fn import_lp5(bytes: &[u8]) -> Result<(Profile, Report), String> { for ws in mode.get("workspaces").and_then(Value::as_array).into_iter().flatten().take(16) { for (pages_key, rotate) in [("pressPages", false), ("rotatePages", true)] { for page in ws.get(pages_key).and_then(Value::as_array).into_iter().flatten().take(64) { + // the Dialpad's buttons stay put while its dial pages change + let is_pads = !rotate && device == "Loupedeck71"; + if !is_pads && profile.pages.len() >= MAX_IMPORTED_PAGES { + // a page past the limit is left out, so its actions don't go in the report + continue; + } let pname = page.get("displayName").and_then(Value::as_str).unwrap_or("Page").to_string(); let mut bindings = BTreeMap::new(); for ctl in page.get("controls").and_then(Value::as_array).into_iter().flatten().take(64) { @@ -898,11 +904,9 @@ pub fn import_lp5(bytes: &[u8]) -> Result<(Profile, Report), String> { bindings.insert(slot, b); } } - let is_pads = !rotate && device == "Loupedeck71"; if is_pads { - // the Dialpad's buttons stay put while its dial pages change profile.base.extend(bindings); - } else if profile.pages.len() < MAX_IMPORTED_PAGES { + } else { let group = if rotate { PageGroup::Dials } else { PageGroup::Keys }; profile.pages.push(Page { name: pname, groups: vec![group], bindings, auto: false }); } @@ -1080,4 +1084,33 @@ mod tests { assert_eq!((p.pages[0].name.as_str(), p.pages[1].name.as_str()), ("Page", "Page 2")); assert_eq!(p.pages[MAX_IMPORTED_PAGES - 1].name, format!("Page {MAX_IMPORTED_PAGES}")); } + + /// The report lists only actions on pages the import keeps; Dialpad buttons count past the page limit + /// (CodeRabbit on #2947). + #[test] + fn the_report_leaves_out_pages_past_the_limit() { + let page = |name: String, key: &str| json!({"displayName": name, "controls": [{"controlId": 0, "pressAction": format!("$X___Cmd___{key}"), "rotateAction": "$X___Adj___Highlight"}]}); + // one list holds at most 64 pages, so the limit is reached over four workspaces + let full = |kind: &str| -> Vec { + (0..MAX_IMPORTED_PAGES / 64) + .map(|w| json!({kind: (0..64).map(|i| page(format!("Keep {w}.{i}"), "Rate5Stars")).collect::>()})) + .collect() + }; + let import = |device: &str, mut workspaces: Vec, extra: Value| { + workspaces.push(extra); + let info = json!({"deviceType": device, "layout": {"layoutModes": [{"workspaces": workspaces}]}}); + import_lp5(&make_zip(&[("ProfileInfo.json", info.to_string().as_bytes(), true)])).unwrap() + }; + let (p, r) = import("Loupedeck70", full("pressPages"), json!({"pressPages": [page("Past".into(), "Rate3Stars")]})); + assert_eq!(p.pages.len(), MAX_IMPORTED_PAGES); + assert!(!r.mapped.iter().any(|l| l.from.starts_with("Past:")), "a dropped page's action is reported"); + assert_eq!(r.mapped.len(), MAX_IMPORTED_PAGES); + // a Dialpad full of dial pages still takes its button page, listed after them + let extra = json!({"pressPages": [page("Buttons".into(), "CopyAdjustments")], "rotatePages": [page("Too many".into(), "Rate5Stars")]}); + let (p, r) = import("Loupedeck71", full("rotatePages"), extra); + assert_eq!(p.pages.len(), MAX_IMPORTED_PAGES); + assert_eq!(p.base["pad.1"], Binding::command("develop.copy")); + assert!(r.mapped.iter().any(|l| l.from.starts_with("Buttons:"))); + assert!(!r.mapped.iter().any(|l| l.from.starts_with("Too many:"))); + } } From c69d0a20abac617d7176bec1f60c0e01e0749dbb Mon Sep 17 00:00:00 2001 From: OneSlips Date: Tue, 27 Oct 2026 13:44:44 +1000 Subject: [PATCH 12/16] HW-SURFACE: import config_dir in the split session module Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/session.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/lightcraft/src/session.rs b/apps/lightcraft/src/session.rs index 289b14ca7d3..cab3d6106a8 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -1,7 +1,7 @@ #[cfg(any(target_os = "freebsd", target_os = "linux"))] use super::platform::DIALOG_PARENT; use super::platform::{explorer_select_command, file_dialog, windows_open_url_command}; -use super::prefs::display_profile_dir; +use super::prefs::{config_dir, display_profile_dir}; use super::*; /// The platform services; `cc` is the window the file dialogs belong to (its `egui_ctx` repaints From c1d2a7c450b8667dcea2b88e154f2d96c5b3e32b Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sat, 31 Oct 2026 13:19:40 +1000 Subject: [PATCH 13/16] HW-SURFACE: control-surface paths compile after main's explicit-import refactor Main (6774d1419) replaced wildcard imports with explicit lists; the frame tick and the services' surface store / plugin installer now name `crate::surface` and `crate::surface_plugin`. Cargo.lock: lightcraft-surface follows the workspace version (0.15.0). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 +- crates/ui-egui/src/app/frame.rs | 2 +- crates/ui-egui/src/services.rs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 903d7584390..318f93d69ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3997,7 +3997,7 @@ dependencies = [ [[package]] name = "lightcraft-surface" -version = "0.14.0" +version = "0.15.0" dependencies = [ "lightcraft-develop", "miniz_oxide 0.9.1", diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 000532dd48a..7454114fd7a 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -53,7 +53,7 @@ impl LightcraftApp { self.drain_control(ctx); // (once a frame: a second layout pass has no input of its own) if ctx.current_pass_index() == 0 { - surface::tick(self, ctx); + crate::surface::tick(self, ctx); } self.apply_settings(ctx); if self.queued_input_needs_repaint() { diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 0b7fdeb745f..5aadd03fc0d 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -133,7 +133,7 @@ pub struct Services { /// The system appearance for Appearance Mode ▸ Auto, ahead of egui's own report. pub system_theme: Option, /// Where control-surface settings are kept (`control-surfaces.json`; none: in memory). - pub surface_store: Option>, + pub surface_store: Option>, /// Open dialog for control-surface files (TactileBridge `settings.json`, `.lp5`, `.lcsurface`). pub pick_surface_file: Option, /// Save dialog for an exported `.lcsurface` layout file. @@ -143,5 +143,5 @@ pub struct Services { pub surface_listener: Option, /// Installs a surface's plugin into its maker's app (the LightCraft plugin for Logi /// Options+; desktop only): Settings ▸ Controls, `surface.installPlugin`. - pub surface_plugin: Option>, + pub surface_plugin: Option>, } From 7805fb0cd4bdb6f419f76c02e9c8e3a4e560b8cd Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sat, 31 Oct 2026 13:41:59 +1000 Subject: [PATCH 14/16] HW-SURFACE: the TactileBridge import is split by section and the table constructor allows its columns (main's new clippy lints) Main now denies cognitive_complexity (threshold 30) and too_many_arguments workspace-wide. import_settings reads each settings.json section in a helper of its own; behaviour unchanged (the crate's 64 tests pass). `st`, one argument per table column, allows too_many_arguments. Co-Authored-By: Claude Opus 5.5 --- crates/surface/src/tactilebridge.rs | 258 +++++++++++++++------------- crates/surface/src/targets.rs | 2 + 2 files changed, 141 insertions(+), 119 deletions(-) diff --git a/crates/surface/src/tactilebridge.rs b/crates/surface/src/tactilebridge.rs index ed269a2d621..d91c0ebd5fc 100644 --- a/crates/surface/src/tactilebridge.rs +++ b/crates/surface/src/tactilebridge.rs @@ -661,79 +661,103 @@ pub fn import_settings(s: &mut SurfaceSettings, text: &str) -> Result Result OsdPosition::Bottom, }; } - line(&mut r, "On-screen display", "On-Screen Readout", "drawn inside the LightCraft window"); + line(r, "On-screen display", "On-Screen Readout", "drawn inside the LightCraft window"); } - if let Some(c) = field(&root, "pluginColors") { + if let Some(c) = field(root, "pluginColors") { if let Some(x) = c.get("backgroundColor").and_then(Value::as_str) { s.look.background = hex_color(x, "#000000"); } if let Some(x) = c.get("foregroundColor").and_then(Value::as_str) { s.look.foreground = hex_color(x, "#FFFFFF"); } - line(&mut r, "Plugin colours", "Surface ▸ Key background, Key text", ""); + line(r, "Plugin colours", "Surface ▸ Key background, Key text", ""); } - if let Some(x) = field(&root, "toolSwitching").and_then(|t| boolean(t, "enabled")) { + if let Some(x) = field(root, "toolSwitching").and_then(|t| boolean(t, "enabled")) { s.follow_context = x; - line(&mut r, "Automatic tool switching", "Pages That Follow the App", ""); + line(r, "Automatic tool switching", "Pages That Follow the App", ""); } - if let Some(a) = field(&root, "autoSync") { + if let Some(a) = field(root, "autoSync") { if let Some(x) = boolean(a, "enabled") { s.apply_to_selected = x; } if let Some(x) = int(a, "idleTimeoutMs") { s.transport.gesture_end_ms = x; } - line(&mut r, "Auto Sync", "Editing ▸ Dials change every selected photo", "one undo step per dial gesture"); + line(r, "Auto Sync", "Editing ▸ Dials change every selected photo", "one undo step per dial gesture"); if a.get("copyApplyDelayMs").is_some() { r.dropped.push(ReportLine { from: "Auto Sync: copy-apply delay".into(), @@ -785,64 +809,60 @@ pub fn import_settings(s: &mut SurfaceSettings, text: &str) -> Result = std::collections::BTreeSet::new(); - for (tool, m) in ctx { - let Some(context) = context_of(tool) else { - r.dropped.push(ReportLine { - from: format!("Tool context: {tool}"), - to: String::new(), - note: "no matching LightCraft context".into(), - }); - continue; - }; - let mut bindings = BTreeMap::new(); - let buttons = field(m, "buttons").and_then(Value::as_array).cloned().unwrap_or_default(); - for (i, k) in buttons.iter().filter_map(Value::as_str).take(9).enumerate() { - if let Some(b) = r.note(format!("{tool}: key {} ({k})", i + 1), k) { - bindings.insert(format!("key.{}", i + 1), b); - } +} + +/// `toolContext.contexts`: the tool layouts, as pages of a new "TactileBridge" profile (made active). +fn import_tool_contexts(s: &mut SurfaceSettings, ctx: &serde_json::Map, r: &mut Report) { + let mut p = crate::defaults::profiles().into_iter().find(|p| p.name == "Default").unwrap_or_default(); + p.name = unique_name(s, "TactileBridge"); + p.description = "Imported from TactileBridge".into(); + // TactileBridge's tool layouts take the contexts they cover; LightCraft's own tool pages stay + // for the rest (a selected mask, Masking without a tool, …) + let mut taken: std::collections::BTreeSet = std::collections::BTreeSet::new(); + for (tool, m) in ctx { + let Some(context) = context_of(tool) else { + r.dropped.push(ReportLine { from: format!("Tool context: {tool}"), to: String::new(), note: "no matching LightCraft context".into() }); + continue; + }; + let mut bindings = BTreeMap::new(); + let buttons = field(m, "buttons").and_then(Value::as_array).cloned().unwrap_or_default(); + for (i, k) in buttons.iter().filter_map(Value::as_str).take(9).enumerate() { + if let Some(b) = r.note(format!("{tool}: key {} ({k})", i + 1), k) { + bindings.insert(format!("key.{}", i + 1), b); } - let encoders = field(m, "encoders").and_then(Value::as_array).cloned().unwrap_or_default(); - // the Dialpad's encoder 0 is its roller, 1 its big dial - let slots = ["roller", "dial", "knob.3", "knob.4"]; - for (slot, k) in slots.iter().zip(encoders.iter().filter_map(Value::as_str)) { - if let Some(b) = r.note(format!("{tool}: {slot} ({k})"), k) { - bindings.insert((*slot).to_string(), b); - } + } + let encoders = field(m, "encoders").and_then(Value::as_array).cloned().unwrap_or_default(); + // the Dialpad's encoder 0 is its roller, 1 its big dial + let slots = ["roller", "dial", "knob.3", "knob.4"]; + for (slot, k) in slots.iter().zip(encoders.iter().filter_map(Value::as_str)) { + if let Some(b) = r.note(format!("{tool}: {slot} ({k})"), k) { + bindings.insert((*slot).to_string(), b); } - let name = if tool == "default" { "Tool: Default".to_string() } else { format!("Tool: {tool}") }; - // TactileBridge's default and Select layouts were its everyday ones (Select is Capture - // One's normal cursor): ordinary pages, first, so the Keypad's own page 1 shows them; the - // other tools' layouts are tool pages shown by their context - let everyday = tool == "default" || tool == "Select"; - let page = Page { name: name.clone(), groups: Vec::new(), bindings, auto: !everyday }; - if everyday { - let at = if tool == "default" { 0 } else { usize::from(p.pages.first().is_some_and(|f| f.name == "Tool: Default")) }; - p.pages.insert(at.min(p.pages.len()), page); - if tool == "default" { - p.contexts.insert("default".into(), vec![name]); - } + } + let name = if tool == "default" { "Tool: Default".to_string() } else { format!("Tool: {tool}") }; + // TactileBridge's default and Select layouts were its everyday ones (Select is Capture + // One's normal cursor): ordinary pages, first, so the Keypad's own page 1 shows them; the + // other tools' layouts are tool pages shown by their context + let everyday = tool == "default" || tool == "Select"; + let page = Page { name: name.clone(), groups: Vec::new(), bindings, auto: !everyday }; + if everyday { + let at = if tool == "default" { 0 } else { usize::from(p.pages.first().is_some_and(|f| f.name == "Tool: Default")) }; + p.pages.insert(at.min(p.pages.len()), page); + if tool == "default" { + p.contexts.insert("default".into(), vec![name]); + } + } else { + p.pages.push(page); + if taken.insert(context.to_string()) { + p.contexts.insert(context.to_string(), vec![name]); } else { - p.pages.push(page); - if taken.insert(context.to_string()) { - p.contexts.insert(context.to_string(), vec![name]); - } else { - p.contexts.entry(context.to_string()).or_default().push(name); - } + p.contexts.entry(context.to_string()).or_default().push(name); } } - p.sanitize(); - s.profile = p.name.clone(); - s.profiles.push(p); } - s.sanitize(); - Ok(r) + p.sanitize(); + s.profile = p.name.clone(); + s.profiles.push(p); } fn unique_name(s: &SurfaceSettings, base: &str) -> String { diff --git a/crates/surface/src/targets.rs b/crates/surface/src/targets.rs index 24913773b9e..7b66daa0741 100644 --- a/crates/surface/src/targets.rs +++ b/crates/surface/src/targets.rs @@ -89,6 +89,8 @@ struct Static { decimals: u8, } +// a table row's constructor: one argument per column of the tables below +#[allow(clippy::too_many_arguments)] const fn st(id: &'static str, label: &'static str, group: &'static str, min: f64, max: f64, default: f64, step: f64, decimals: u8) -> Static { Static { id, label, group, min, max, default, step, decimals } } From af864399fdc5b5c79d92058928183eb1ae9e845a Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 1 Nov 2026 09:33:35 +1000 Subject: [PATCH 15/16] HW-SURFACE: the Keys and Dials settings test is split into steps (main's cognitive-complexity lint) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tests/surface.rs | 34 +++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/tests/surface.rs b/crates/ui-egui/src/tests/surface.rs index 953e4cfd62f..53d8faa3dc5 100644 --- a/crates/ui-egui/src/tests/surface.rs +++ b/crates/ui-egui/src/tests/surface.rs @@ -239,26 +239,38 @@ fn settings_tab_learn_and_edit_a_key() { ] { assert!(h.app.widgets.iter().any(|(w, _)| w == id), "{id}"); } + touch_to_find_selects_keys_and_dials(&mut h); + an_action_picked_from_the_list_is_bound(&mut h); + the_other_sections_open(&mut h); + a_rebound_key_shows_runs_and_is_saved(&mut h, &store); +} + +/// Touch to find (on while the Keys and Dials page is open): a touched key or dial is selected, and nothing runs. +fn touch_to_find_selects_keys_and_dials(h: &mut Headless) { // Touch to find (on while this page is open): touch key 5 on the surface: it is selected, // and nothing runs let clip = h.app.widgets.iter().find(|(w, _)| w == "check:surface.touchFind").map(|(_, r)| *r).unwrap(); assert!(clip.bottom() < 900.0, "Touch to find is on screen: {clip:?}"); assert!(h.app.surface.runtime.learning()); let before = h.app.session.active(); - assert_eq!(input(&mut h, json!([{"control": "key.5", "press": true}]))["ok"], true); + assert_eq!(input(h, json!([{"control": "key.5", "press": true}]))["ok"], true); h.settle(T); assert_eq!(h.app.surface.editor.control.as_deref(), Some("key.5")); assert_eq!(h.app.session.active(), before, "a learnt press doesn't act"); assert!(h.app.widgets.iter().any(|(w, _)| w == "field:surfaceActionSearch"), "the selected key's editor"); // touching a dial switches the drawing to the Dialpad, and the photo doesn't change - let exposure_before = exposure(&h); - assert_eq!(input(&mut h, json!([{"control": "dial", "ticks": 1}]))["ok"], true); - assert_eq!(input(&mut h, json!([{"control": "dial", "ticks": 3}]))["ok"], true); + let exposure_before = exposure(h); + assert_eq!(input(h, json!([{"control": "dial", "ticks": 1}]))["ok"], true); + assert_eq!(input(h, json!([{"control": "dial", "ticks": 3}]))["ok"], true); h.settle(T); assert_eq!(h.app.surface.editor.device, "dialpad"); assert_eq!(h.app.surface.editor.control.as_deref(), Some("dial")); - assert_eq!(exposure(&h), exposure_before, "a touched dial is found, not turned"); + assert_eq!(exposure(h), exposure_before, "a touched dial is found, not turned"); assert!(h.app.widgets.iter().any(|(w, _)| w == "button:surfaceControl-dial"), "the Dialpad is drawn"); +} + +/// An action picked from the list (search, click) is bound to the selected dial. +fn an_action_picked_from_the_list_is_bound(h: &mut Headless) { // pick an action from the list: search, click h.app.surface.editor.filter = "Highlights".into(); h.settle(T); @@ -269,6 +281,10 @@ fn settings_tab_learn_and_edit_a_key() { p.pages.iter().any(|pg| pg.bindings.get("dial") == Some(&lightcraft_surface::Binding::value("light.highlights"))), "the dial moves Highlights now" ); +} + +/// The other sections of the Controls tab open, once the Keys and Dials window over them is closed. +fn the_other_sections_open(h: &mut Headless) { // the other sections open. They are in the Settings window, under the Keys and Dials window // while that is open: a covered button takes no click, so close it first (as its close box does) let covered = h.request("ui.clickWidget", json!({"id": "button:surfaceSection-feel"}), T); @@ -288,6 +304,10 @@ fn settings_tab_learn_and_edit_a_key() { assert!(h.app.widgets.iter().any(|(w, _)| w == "window:surfaceEditor"), "the Keys and Dials window is back"); assert_eq!(h.request("ui.clickWidget", json!({"id": "button:surfaceDevice-keypad"}), T)["ok"], true); h.settle(T); +} + +/// Key 5 rebound to Contrast shows its new label, moves Contrast on the dial, and is saved. +fn a_rebound_key_shows_runs_and_is_saved(h: &mut Headless, store: &MemStore) { // make key 5 put Contrast on the dial let profile = h.app.surface.settings().profile.clone(); let mut s = h.app.surface.settings().clone(); @@ -304,8 +324,8 @@ fn settings_tab_learn_and_edit_a_key() { } assert!(!h.app.surface.runtime.learning(), "Touch to find stopped with the page"); // press it: the dial moves Contrast until pressed again - assert_eq!(input(&mut h, json!([{"control": "key.5", "press": true}, {"control": "dial", "ticks": 4}]))["ok"], true); - finish_gesture(&mut h); + assert_eq!(input(h, json!([{"control": "key.5", "press": true}, {"control": "dial", "ticks": 4}]))["ok"], true); + finish_gesture(h); let id = h.app.session.active().unwrap(); assert!(h.app.session.develop_of(id).unwrap().light.contrast > 0.0); // saved From 80429d228d2be705cfdf204f464f9ba34e15487f Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 1 Nov 2026 19:01:56 +1000 Subject: [PATCH 16/16] HW-SURFACE: Cargo.lock records lightcraft-surface 0.16.0 The merge of main bumped the crate to 0.16.0 but kept the old lock entry, so `cargo --locked` on GitHub refused to build. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 451f45df6a7..daa35fe52ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4000,7 +4000,7 @@ dependencies = [ [[package]] name = "lightcraft-surface" -version = "0.15.0" +version = "0.16.0" dependencies = [ "lightcraft-develop", "miniz_oxide 0.9.1",