PhotoCraft on the craft UI framework (#15449)

PhotoCraft's UI moves onto the shared craft UI framework in storytold/craft-libs (next branch): shell, dock and panels, hosted dialogs, keyboard, focus, IME and pointer routing, the canvas's view commands, themes and tokens. The engine, document model, file formats, commands and automation stay. PhotoCraft pins storytold/craft-libs next.
This commit is contained in:
aiongg authored and GitHub committed 2026-11-17 10:41:35 -05:00
1 parent 01b79958a7
commit ed14e1c413
1529 files changed
+109611 -284552

No files matched your search

+2 -30
View File
@@ -14,40 +14,12 @@ next to them.
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/text/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
| `assets/icons/*.svg` except `vector-shape.svg`, `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (117 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in,zoom-out}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{arrow-left-right,circle-dashed,ellipsis,file-plus,folder-plus,grid-2x2,house,link-2,message-square,panel-left,pipette,rectangle-horizontal,rectangle-vertical,redo-2,square-dashed,square-dashed-mouse-pointer,triangle-alert,type,x}.svg` | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{link-2,type,x}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/vector-shape.svg` | Vector path shape-layer glyph with four anchor points | @superplay2021 | Original work for PhotoCraft | MIT OR Apache-2.0 |
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/crop-overlay-*.svg` | Crop overlay glyphs: Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio and Golden Spiral inside the crop-mark frame | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/spirit-level.svg` | Straighten tool glyph: a spirit level with its vial and bubble under a dotted arc | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/font-similar.svg`, `assets/icons/font-variable.svg` | Font menu filter glyphs: two waves (Show Similar Fonts) and a T over a slider (Show Variable Fonts), drawn on the 24 px icon grid | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/convert-point.svg` | Convert Point tool glyph: an angle with a square anchor on its apex, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/artboard.svg` | Artboard tool glyph: a board with a tick at each end of its edges | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/perspective-crop.svg` | Perspective Crop tool glyph: a crop frame in perspective with its grid and crop-mark ticks | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/type-mask.svg`, `assets/icons/type-mask-vertical.svg` | Horizontal and Vertical Type Mask tool glyphs: a T drawn as marching ants (the vertical one beside a downward arrow), on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/path-op-{new-layer,combine,subtract,intersect,exclude,merge}.svg` | Path Operations glyphs (Pen options bar): a single square for New Layer, and two overlapping squares showing the area each operation keeps (union, back minus front, overlap, everything but the overlap, the merged outline), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/text-warp.svg` | Create Warped Text glyph (Type tool options bar): a T above a bowed arc, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/layer-mask.svg`, `assets/icons/adjustment-layer.svg` | Layers panel footer glyphs: Add a mask (a frame around a solid disc) and New Fill or Adjustment Layer (a circle, one half solid), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/vertical-align-{top,middle,bottom}.svg` | Type options-bar alignment glyphs for vertical text: three columns hanging from a top line, centred on a middle line, or standing on a bottom line, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/align-edge-*.svg`, `assets/icons/distribute-*.svg` | Move tool options-bar glyphs: Align (six edges/centres) and Distribute (edges, centres, spacing), a guide line or edge lines with bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/ellipse-dashed.svg` | Elliptical Marquee tool glyph: a dashed horizontal ellipse, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/frame-placeholder.svg` | Frame tool glyph: an empty placeholder frame, crossed corner to corner | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/gradient.svg` | Gradient tool glyph: a rounded rectangle filled with a left-to-right linear ramp, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/eraser-background.svg`, `assets/icons/eraser-magic.svg` | Background Eraser and Magic Eraser tool glyphs: Lucide `eraser` plus added marks | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/eraser.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/history-brush.svg` | History Brush tool glyph: Lucide `brush` plus counter-clockwise history rewind arrow | Lucide Icons and Contributors; arrow by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/quick-selection.svg` | Quick Selection tool glyph: Lucide `brush`, scaled to 70%, inside a dashed upright rounded "C" selection | Lucide Icons and Contributors; selection by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/pen-freeform.svg`, `assets/icons/pen-curvature.svg` | Freeform Pen and Curvature Pen tool glyphs: Lucide `pen-tool` scaled down, plus a freehand squiggle or a curve through two points | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/pen-add-anchor.svg`, `assets/icons/pen-delete-anchor.svg` | Add Anchor Point and Delete Anchor Point tool glyphs: Lucide `pen-tool` plus a + or − mark | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/painting-symmetry.svg` | Painting symmetry glyph: Lucide `heart` with a central axis | Lucide Icons and Contributors; adapted by @shorbank | Derived from <https://github.com/lucide-icons/lucide> `icons/heart.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/symmetry-{vertical,horizontal,dual,diagonal}.svg` | Painting symmetry axis glyphs | @shorbank | Original work; supplied SVG line geometry centred on a common square canvas, stroke adjusted to match the painting-symmetry glyph | MIT OR Apache-2.0, [`assets/icons/LICENSE-symmetry-axes.txt`](assets/icons/LICENSE-symmetry-axes.txt) |
| `assets/icons/lasso-magnetic.svg` | Magnetic Lasso tool glyph, adapted from "Magnetic Lasso Tool" (redrawn on the 24 px toolbar grid) | Lil' Seal (Noun Project); adapted by PhotoCraft contributors | <https://thenounproject.com/icon/magnetic-lasso-tool-177513/> | CC BY 3.0, [`assets/icons/LICENSE-noun-magnetic-lasso.txt`](assets/icons/LICENSE-noun-magnetic-lasso.txt) |
| `assets/dict/en_US-scowl-50.txt.gz` | English word list for Check Spelling (SCOWL 2020.12.07, size 50, en_US; 72,403 words) | Kevin Atkinson and the SCOWL contributors | <http://wordlist.aspell.net/> | SCOWL license (permissive, keep the notice), [`assets/dict/LICENSE-SCOWL.txt`](assets/dict/LICENSE-SCOWL.txt), which also has the build recipe |
| `assets/app-icon/` (all files) | PhotoCraft app icon (nine-tailed kitsune) | The project owner (drawn in ArtCraft, vectorised) | Original work, see [`assets/app-icon/README.md`](assets/app-icon/README.md) | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) |
| `packaging/macos/dmg/` (all files) | PhotoCraft DMG window background and layout | @XusBadia, from the PhotoCraft app icon | Original work, see [`packaging/macos/dmg/README.md`](packaging/macos/dmg/README.md) | MIT OR Apache-2.0, like the code |
Generated
+1367 -534
View File
File diff suppressed because it is too large. Load diff
+91 -53
View File
@@ -10,25 +10,21 @@ license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["serde"] }
# Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119).
craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
# The ArtCraft Launcher's agents switch and app list, shared with the launcher, the MCP gateway and
# every Craft app (storytold/craft-ai-integrations#195). Pinned to the head of
# storytold/craft-ai-integrations#197 until it merges.
craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" }
# The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match
# `craft::egui_fork::REV` (checked by `cargo xtask ci`).
craft = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
# internal
photocraft-geom = { path = "crates/geom" }
photocraft-color = { path = "crates/color" }
photocraft-raster = { path = "crates/raster" }
photocraft-doc = { path = "crates/doc" }
photocraft-ops = { path = "crates/ops" }
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "e2e3b4213afb2b5e7651bc1b1a1cf72a8bb6313d" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "eafb50aff3c6b1acc14dff53060157877e3e4fce" }
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
photocraft-raw = { path = "crates/raw" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
photocraft-compose = { path = "crates/compose" }
photocraft-gpu = { path = "crates/gpu" }
photocraft-paint = { path = "crates/paint" }
@@ -47,33 +43,33 @@ photocraft-ipp = { path = "crates/ipp" }
# external
# ICC colour management: the shared crate (replaces crates/cms; craft-libs#779).
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c6eb84d427d81b6d64207654c8ee0516cd3d7324" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["raster", "write-raster"] }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9", features = ["raster", "write-raster"] }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
# Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563.
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "163f1b20315ffacaf8a6e085f4ae7fc568c08ff2" }
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
# the commit in `craft-i18n.rev`). Already in the tree through craft-ui.
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
# the commit in `craft-i18n.rev`). Already in the tree through craft.
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9", features = ["ui"] }
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
@@ -114,6 +110,42 @@ wildcard_imports = "deny"
dbg_macro = "warn"
todo = "warn"
# The settings of craft-libs' `tools/cl` for this workspace (craft-libs docs/development.md, "App workspaces").
[workspace.metadata.cl]
# Every cl command selects these packages: each brings features the others lack, so a command that drops one
# builds a second copy of egui, photocraft-io or craft-affinity and of everything above them.
selection = [
"photocraft-ui-egui", "photocraft-engine", "photocraft", "photocraft-algo", "photocraft-automation",
"photocraft-text", "photocraft-tablet", "photocraft-cli", "photocraft-paint", "photocraft-io", "photocraft-gpu",
]
# Crates whose new builds cl names after a command, besides the framework's.
tracked = ["egui", "eframe", "photocraft-ui-egui", "photocraft-io", "craft-affinity"]
# Each changes a build input (the text crate's build script tracks CRAFT_FONTS_DIR), so a command run with a
# different value rebuilds.
unset_env = ["RUST_MIN_STACK", "CARGO_INCREMENTAL", "CRAFT_FONTS_DIR"]
# The tests keep a 5% scratch reserve, which a TMPDIR on a nearly full disk trips.
set_env = { TMPDIR = "/tmp" }
run_slots = 3
test_threads = 4
# The one build of each crate a target dir holds after the selection's test build (`cl doctor` compares).
[workspace.metadata.cl.expected_features]
egui = ["bytemuck", "default_fonts", "monochrome_emoji_fonts", "persistence", "ron", "serde"]
photocraft-io = ["pdf-editable", "testgen"]
craft-affinity = ["synth"]
craft-ui-contract = ["default", "snapshot", "testing"]
craft-imaging = ["default", "screen-testing", "ui"]
# The ui-egui lib binary holds most of the unit tests; split, it no longer sets the run's wall time.
[workspace.metadata.cl.shard]
"photocraft-ui-egui/photocraft_ui_egui" = 3
# Seconds per test binary, ordering the first run longest first (later runs use the recorded times).
[workspace.metadata.cl.default_seconds]
"photocraft-ui-egui/photocraft_ui_egui" = 389.0
"photocraft-ui-egui/it" = 221.0
"photocraft-engine/photocraft_engine" = 97.0
# Dependencies carry no debug info: their frames in a backtrace lose file:line, and the target dir
# and link times shrink. The test profile inherits both settings.
[profile.dev.package."*"]
@@ -215,24 +247,30 @@ opt-level = "z"
opt-level = 3
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
emath = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README).
hayro = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
+2
View File
@@ -31,6 +31,8 @@ required-features = ["gpu"]
[dependencies]
photocraft-automation = { path = "../../crates/automation" }
# The suite's AI-MCP flag (`craft::automation::agents::mcp_flag`): `mcp` reaches the open window only with it.
craft = { workspace = true, features = ["automation-agents"] }
photocraft-doc = { workspace = true }
photocraft-engine = { workspace = true }
photocraft-io = { workspace = true, features = ["pdf-editable"] }
+1 -1
View File
@@ -73,7 +73,7 @@ pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result {
/// `--bridge` (or PHOTOCRAFT_CONTROL_PORT) a `photocraft --control` app.
pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result {
let server = match &a.bridge {
None if !a.headless && photocraft_automation::agent_link::mcp_flag() => PhotocraftMcp::live(live_config(a)?),
None if !a.headless && craft::automation::agents::mcp_flag() => PhotocraftMcp::live(live_config(a)?),
Some(addr) => {
if a.bridge_from_env {
// Name the mode switch, as `serve` does: the way back to headless is to unset it.
+5 -5
View File
@@ -2,7 +2,7 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use photocraft_automation::Headless;
use photocraft_engine::actions_cmds::Action;
use photocraft_engine::actions_cmds::{Action, ActionList, ActionsFile};
use photocraft_io::ExportOptions;
use serde_json::json;
@@ -32,8 +32,8 @@ pub(crate) fn is_input(p: &Path) -> bool {
fn strip_shell_steps(action: &mut Action) {
use photocraft_engine::actions_cmds::{shell_save_command, shell_view_command};
let (mut steps, mut disabled, mut dialogs) = (Vec::new(), std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
for (i, (id, p)) in std::mem::take(&mut action.steps).into_iter().enumerate() {
if shell_save_command(&id) || shell_view_command(&id) {
for (i, step) in std::mem::take(&mut action.steps).into_iter().enumerate() {
if shell_save_command(&step.command) || shell_view_command(&step.command) {
continue;
}
if action.disabled.contains(&i) {
@@ -42,7 +42,7 @@ fn strip_shell_steps(action: &mut Action) {
if action.dialogs.contains(&i) {
dialogs.insert(steps.len());
}
steps.push((id, p));
steps.push(step);
}
(action.steps, action.disabled, action.dialogs) = (steps, disabled, dialogs);
}
@@ -126,7 +126,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
}
// Steps that play another action find it in the set; the session's playback stack
// stops an action that calls itself.
h.session.actions.list = set.clone();
h.session.actions.list = ActionList::from_file(ActionsFile::new(set.clone(), Vec::new()));
h.open_with_approval(input, a.approve_high_memory)?;
for (id, p) in &actions {
if photocraft_engine::actions_cmds::shell_view_command(id)
+4 -3
View File
@@ -1410,13 +1410,14 @@ fn a_non_unicode_path_is_taken_and_non_unicode_text_is_a_usage_error() {
/// PhotoCraft can't play are warned about up front.
#[test]
fn batch_plays_a_photoshop_actions_file() {
use photocraft_engine::actions_cmds::Action;
use photocraft_engine::actions_cmds::{Action, ActionStep};
let d = tmp("atn");
let input = d.join("in");
std::fs::create_dir_all(&input).unwrap();
write_png(&input.join("a.png"), 8, 4, 3);
let invert = Action::new("Negative", vec![("image.adjustments.invert".into(), json!({})), ("select.all".into(), json!({}))]);
let odd = Action::new("Odd", vec![(photocraft_engine::atn_cmds::PHOTOSHOP_STEP.into(), json!({"event": "syntheticFill", "name": "Generative Fill"}))]);
let invert = Action::new("Negative", vec![ActionStep::new("image.adjustments.invert", json!({})), ActionStep::new("select.all", json!({}))]);
let odd =
Action::new("Odd", vec![ActionStep::new(photocraft_engine::atn_cmds::PHOTOSHOP_STEP, json!({"event": "syntheticFill", "name": "Generative Fill"}))]);
let (bytes, skipped) = photocraft_engine::atn_cmds::export("Set", &[&invert, &odd], &[], false).unwrap();
assert!(skipped.is_empty());
let atn = d.join("Set.atn");
+6 -5
View File
@@ -208,9 +208,10 @@ impl Bridge {
pub fn verify_action_definitions(&self, actions: &ActionState) {
let mut s = self.state();
s.actions_unsynced = match s.files.get(ACTIONS_FILE) {
Some(bytes) => !serde_json::from_slice::<ActionsFile>(bytes)
.is_ok_and(|file| file.version == 1 && file.actions == actions.list && file.sets == actions.sets && file.set_rows == actions.set_rows),
None => !(actions.list.is_empty() && actions.sets.is_empty() && actions.set_rows.is_empty()),
Some(bytes) => {
!std::str::from_utf8(bytes).ok().and_then(|text| ActionsFile::from_json(text).ok()).is_some_and(|file| file == actions.list.to_file())
}
None => !(actions.list.actions().is_empty() && actions.list.sets().is_empty()),
};
}
@@ -469,7 +470,7 @@ mod tests {
fn unmatched_definitions_cannot_commit_new_keys() {
let bridge = Bridge::default();
let mut actions = ActionState::default();
actions.list.push(photocraft_engine::actions_cmds::Action::new("New action", Vec::new()));
actions.list.push(photocraft_engine::actions_cmds::Action::new("New action", Vec::new())).unwrap();
bridge.verify_action_definitions(&actions);
bridge.stage_action_keys(ActionKeys::from_legacy(&json!({"shortcuts":{"actions.play:New action":"F6"}})));
bridge.write("index.json", b"unrelated").unwrap();
@@ -530,7 +531,7 @@ mod tests {
bridge.load_action_keys(2, keys.clone());
let (session, warnings) = session(bridge.clone());
assert!(!warnings.is_empty());
assert!(session.actions.list.is_empty());
assert!(session.actions.list.actions().is_empty());
assert!(session.tools.presets.iter().any(|preset| preset.name == "Browser seam brush"));
assert_eq!(bridge.committed_action_keys(), None);
assert_eq!(bridge.read(ACTIONS_FILE, 1024).unwrap(), malformed);
+11 -90
View File
@@ -6,11 +6,10 @@ use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image};
use photocraft_doc::Document;
use photocraft_ui_egui::i18n;
use photocraft_ui_egui::served_fonts;
use photocraft_ui_egui::theme::ThemeKind;
use photocraft_ui_egui::theme::AppTheme;
use photocraft_ui_egui::{FileDialogAnswer, FileDialogRequest, PhotocraftApp, Services};
use wasm_bindgen::JsCast as _;
@@ -95,25 +94,24 @@ pub fn start() {
canvas,
options,
Box::new(move |cc| {
PhotocraftApp::install_type_reset_hooks(&cc.egui_ctx);
PhotocraftApp::setup_context(&cc.egui_ctx, ThemeKind::Pro);
PhotocraftApp::setup_context(&cc.egui_ctx, AppTheme::pro());
let inbox: Inbox = Arc::default();
let place_inbox: PlaceInbox = Arc::default();
let served: Served = Arc::default();
load_font_manifest(served.clone(), cc.egui_ctx.clone());
let (session, warnings) = crate::preset_bridge::session(presets.clone());
let actions_revision = session.actions.rev;
let actions_revision = session.actions.list.revision();
preset_warnings.extend(warnings);
let drag = listen_drag(&pen_target);
let mut services = services(inbox.clone(), place_inbox.clone(), drag_pos_service(pen_target.clone(), drag));
let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions.list.is_empty()));
let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions.list.actions().is_empty()));
services.load_prefs = Some(Box::new(move || initial.take().unwrap_or_else(stored_preferences)));
let mut app = PhotocraftApp::new(session, services);
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, services);
if !preset_warnings.is_empty() {
photocraft_ui_egui::notices::post(&mut app, i18n::t("Some brush presets could not be loaded"), preset_warnings, true, None);
}
listen_pen(&pen_target, app.stylus.feed.clone());
app.set_theme(&cc.egui_ctx, ThemeKind::Pro);
app.set_theme(&cc.egui_ctx, AppTheme::pro());
if let Some(rs) = cc.wgpu_render_state.clone()
&& !force_cpu
{
@@ -377,11 +375,11 @@ struct WebShell {
impl WebShell {
fn save_presets(&mut self, ctx: &egui::Context) {
let session = &self.app.session;
if self.actions_revision != session.actions.rev {
if self.actions_revision != session.actions.list.revision() {
// The engine can reject an oversized definition before calling the backend.
// Never stage that edit's keys with the last successfully queued definitions.
self.presets.verify_action_definitions(&session.actions);
self.actions_revision = session.actions.rev;
self.actions_revision = session.actions.list.revision();
}
let prefs_revision = session.prefs.rev();
if self.prefs_revision != Some(prefs_revision) {
@@ -449,9 +447,8 @@ impl eframe::App for WebShell {
// A tap reaches eframe as Pointer Events and Touch Events: keep one press per tap, or the
// twin press closes the menu the first one opened (#2095).
photocraft_ui_egui::touch_twins::drop_twins(ctx, raw_input);
// The browser build has no TCP control server, so `inject_synthetic` finds an empty
// queue, but the clipboard key mapping (`Event::PasteImage`), legacy pinch, pen-hold and
// titlebar normalization live in the app hook and must run here too.
// The clipboard key mapping (`Event::PasteImage`), legacy pinch, pen-hold and titlebar
// normalization live in the app hook and must run here too.
eframe::App::raw_input_hook(&mut self.app, ctx, raw_input);
}
@@ -497,7 +494,6 @@ impl eframe::App for WebShell {
self.serve_fonts(ctx);
self.app.logic_frame(ctx, frame);
self.save_presets(ctx);
self.app.finish_type_reset_logic(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
@@ -508,7 +504,7 @@ impl eframe::App for WebShell {
&& let Some(warning) = self.presets.error()
{
egui::Panel::top("browser_preset_storage").show(ui, |ui| {
let tokens = photocraft_ui_egui::theme::Tokens::for_kind(self.app.ui.theme);
let tokens = self.app.ui.theme.tokens();
// Put retry first so floating brush windows cannot cover the control.
ui.horizontal_wrapped(|ui| {
if self.database.is_some() && ui.button(i18n::t("Retry saving presets")).clicked() {
@@ -545,13 +541,11 @@ impl eframe::App for WebShell {
}
self.app.ui_frame(ui, frame);
self.save_presets(ui.ctx());
self.app.finish_type_reset_pass(ui.ctx());
}
}
fn services(inbox: Inbox, place_inbox: PlaceInbox, cursor_pos: photocraft_ui_egui::CursorPosFn) -> Services {
Services {
screen_pick: screen_color_service(),
import: Some(Box::new(|name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions| {
photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
})),
@@ -597,10 +591,6 @@ fn services(inbox: Inbox, place_inbox: PlaceInbox, cursor_pos: photocraft_ui_egu
write: Some(Box::new(|path: &str, bytes: &[u8]| download(path, bytes))),
// A download may be cancelled and never reports back: it doesn't save the document.
write_unconfirmed: true,
encode_png: Some(Box::new(|w, h, rgba| {
let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?;
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())
})),
inbox: Some(inbox),
place_inbox: Some(place_inbox),
cursor_pos: Some(cursor_pos),
@@ -695,72 +685,3 @@ fn mime_for(name: &str) -> &'static str {
_ => "application/octet-stream",
}
}
/// Rust bindings to the browser's user-activated EyeDropper API; unsupported browsers keep
/// the document picker and its normal canvas zoom. The browser owns its screen magnifier.
fn screen_color_service() -> Option<photocraft_ui_egui::screen_picker::Service> {
use js_sys::{Function, Reflect};
use photocraft_ui_egui::screen_picker::{Capture, Pending};
use wasm_bindgen::{JsValue, closure::Closure};
let window = web_sys::window()?;
let constructor = Reflect::get(&window, &JsValue::from_str("EyeDropper")).ok()?.dyn_into::<Function>().ok()?;
Some(Box::new(move |ctx| {
let (tx, rx) = std::sync::mpsc::channel();
let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
let started = (|| -> Result<_, String> {
let eye = Reflect::construct(&constructor, &js_sys::Array::new()).map_err(|e| format!("Could not start browser eyedropper: {e:?}"))?;
let controller = web_sys::AbortController::new().map_err(|e| format!("Could not create eyedropper cancellation: {e:?}"))?;
let options = js_sys::Object::new();
Reflect::set(&options, &JsValue::from_str("signal"), &controller.signal()).map_err(|e| format!("Could not set eyedropper options: {e:?}"))?;
let open = Reflect::get(&eye, &JsValue::from_str("open"))
.map_err(|e| format!("Browser eyedropper has no open method: {e:?}"))?
.dyn_into::<Function>()
.map_err(|_| "Invalid browser eyedropper method")?;
let promise = open
.call1(&eye, &options)
.map_err(|e| format!("Could not open browser eyedropper: {e:?}"))?
.dyn_into::<js_sys::Promise>()
.map_err(|_| "Browser eyedropper returned no promise")?;
let stop = cancelled.clone();
let abort = controller.clone();
let timer = Closure::<dyn FnMut()>::new(move || {
if stop.load(std::sync::atomic::Ordering::Relaxed) {
abort.abort();
}
});
let interval = window.set_interval_with_callback_and_timeout_and_arguments_0(timer.as_ref().unchecked_ref(), 50).map_err(|e| {
controller.abort();
format!("Could not watch eyedropper cancellation: {e:?}")
})?;
Ok((promise, timer, interval))
})();
match started {
Err(e) => {
let _ = tx.send(Err(e));
}
Ok((promise, timer, interval)) => {
let wake = ctx.clone();
let window = window.clone();
wasm_bindgen_futures::spawn_local(async move {
let result = match wasm_bindgen_futures::JsFuture::from(promise).await {
Ok(value) => Reflect::get(&value, &JsValue::from_str("sRGBHex"))
.ok()
.and_then(|v| v.as_string())
.and_then(|h| photocraft_ui_egui::color_picker_ui::parse_hex(&h))
.map(|rgb| Capture::Color(Some(rgb)))
.ok_or_else(|| "Browser eyedropper returned an invalid color".into()),
Err(e) if Reflect::get(&e, &JsValue::from_str("name")).ok().and_then(|v| v.as_string()).as_deref() == Some("AbortError") => {
Ok(Capture::Color(None))
}
Err(e) => Err(format!("Browser screen color selection failed: {e:?}")),
};
window.clear_interval_with_handle(interval);
drop(timer);
let _ = tx.send(result);
wake.request_repaint();
});
}
}
Pending { receiver: rx, cancelled }
}))
}
+4 -15
View File
@@ -27,9 +27,11 @@ photocraft-io = { workspace = true }
photocraft-format = { workspace = true }
photocraft-automation = { workspace = true }
photocraft-ui-egui = { workspace = true }
craft-flags = { workspace = true }
# Pen tablet pressure/tilt on macOS and X11 (the workspace's one isolated unsafe helper crate).
photocraft-tablet = { workspace = true }
# The framework facade: `craft::host` (Wake, window services), `craft::menu` (the macOS menu bar)
# and `craft::automation` (the control server, the agent link and the launcher's agents switch).
craft = { workspace = true, features = ["ui", "menu", "automation-agents"] }
eframe = { workspace = true, features = ["wgpu", "accesskit", "wayland", "x11", "persistence", "clipboard"] }
egui = { workspace = true }
serde = { workspace = true }
@@ -66,12 +68,6 @@ fmv-macos-events = "=0.1.0"
objc2 = "=0.6.5"
objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSArray", "NSEnumerator", "NSGeometry"] }
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSApplicationScripting", "NSEvent", "NSGraphics", "NSResponder", "NSView", "NSWindow"] }
# The macOS menu bar (mac_menu.rs): a standalone native menu crate (from the tauri-apps org, but
# not Tauri: no webview, no JS), AppKit menus behind a safe API (no GTK with default features off). Pinned exactly: review the diff before bumping.
muda = { version = "=0.21.2", default-features = false }
# Quit with `terminate:` from the main queue, outside winit's event handler (mac_window.rs).
# Already in Cargo.lock (winit, objc2-app-kit); pinned exactly to the same version.
dispatch2 = { version = "=0.3.1", default-features = false, features = ["std"] }
[target.'cfg(unix)'.dependencies]
rustix = { version = "=1.1.5", features = ["fs"] }
@@ -117,14 +113,6 @@ winit = { version = "=0.30.13", default-features = false, features = ["wayland-c
xcap = "=0.9.8"
winsafe = { version = "=0.0.29", default-features = false, features = ["user"] }
# tests/mac_menu_appkit.rs: reads AppKit's menu bar back and sends it real key events.
[target.'cfg(target_os = "macos")'.dev-dependencies]
objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSString"] }
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSEvent", "NSGraphicsContext", "NSMenu", "NSMenuItem", "NSResponder"] }
[[test]]
name = "mac_menu_appkit"
harness = false
[build-dependencies]
# Icon + VERSIONINFO for photocraft.exe; build.rs only uses it when targeting Windows.
@@ -133,3 +121,4 @@ winresource = "0.1"
[dev-dependencies]
# Opt-in native save-back acceptance transports embedded sources through engine JSON.
base64 = "=0.22.1"
egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }
-281
View File
@@ -1,281 +0,0 @@
//! Agents in the open desktop app: while the person lets them in (ArtCraft Launcher › Settings ›
//! AI agents; without the `AI-MCP` flag, a Control Port saved before), the app serves the control
//! protocol by itself (no `--control`) and publishes the connection file `photocraft-cli mcp`
//! finds it by ([`photocraft_automation::agent_link`]). Turning it on or off, or changing the
//! port or folders in Preferences › AI Integrations, applies at once. The token stays in the settings
//! folder across launches (`agent-control.token`, as `--control-token-file` would keep it; delete
//! it for a new one). Agent requests get the policy and the folders chosen there, exactly as with
//! `--control` and the automation roots.
//!
//! Launch flags win: started with `--control`, the app doesn't install this service and the
//! dialog says the launch options manage the connection.
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use photocraft_automation::agent_link::{self, Connection};
use photocraft_automation::security;
use photocraft_engine::prefs::Integrations;
use photocraft_ui_egui::{AgentLink, AgentLinkFn, ControlRequest};
use crate::control_server;
/// The connection while it runs; dropping it stops the server and removes the connection file.
struct Running {
server: control_server::Listening,
dir: PathBuf,
/// The `controlPort` preference it was started for (0 = any).
port_pref: u32,
}
impl Drop for Running {
fn drop(&mut self) {
agent_link::remove_connection(&self.dir, std::process::id());
log::info!("agent connection on 127.0.0.1:{} stopped", self.server.port);
}
}
/// Start serving agents on `port` (0 = any free port): the token from the settings folder
/// (created `0600` when missing), then the connection file. Returns the connection and the
/// channel its requests arrive on. A token file that can't be written leaves the connection off
/// (no server, so no token to leak) and says why.
fn start(dir: &Path, port: u16, ctx: &egui::Context, port_pref: u32) -> Result<(Running, Receiver<ControlRequest>), String> {
let token_file = dir.join(agent_link::TOKEN_FILE);
let token = security::server_token(None, Some(&token_file)).map_err(|e| format!("Agents can't connect: the token file could not be written: {e}"))?;
let (requests, server) = control_server::listen(port, token, ctx.clone()).map_err(|e| format!("Couldn't listen on 127.0.0.1:{port}: {e}"))?;
let running = Running { server, dir: dir.to_path_buf(), port_pref };
agent_link::write_connection(dir, &Connection::new(running.server.port, token_file)).map_err(|e| format!("Couldn't publish the agent connection: {e}"))?;
log::info!("agents can connect on 127.0.0.1:{}", running.server.port);
Ok((running, requests))
}
/// The agent connection service (`settings_dir`: where the connection file and token go).
pub fn service(settings_dir: Option<PathBuf>) -> AgentLinkFn {
let mut running: Option<Running> = None;
Box::new(move |integrations: &Integrations, ctx: &egui::Context| apply(&mut running, settings_dir.as_deref(), integrations, ctx))
}
/// Bring the connection in line with `integrations`: start, restart on another port, stop, or only
/// change the folders agents may use.
fn apply(running: &mut Option<Running>, dir: Option<&Path>, integrations: &Integrations, ctx: &egui::Context) -> AgentLink {
let mut out = AgentLink::default();
if !integrations.connect_agents {
out.stopped = running.take().is_some();
return out;
}
// Allow Agent Control off refuses every control server, this one as `--control`.
if !integrations.allow_agent_control {
out.stopped = running.take().is_some();
out.status.error = Some("Agents can't connect: Allow Agent Control is off in the preferences file.".into());
return out;
}
let Some(dir) = dir else {
out.stopped = running.take().is_some();
out.status.error = Some("Agents can't connect: PhotoCraft has no settings folder (no home folder).".into());
return out;
};
if running.as_ref().is_none_or(|r| r.port_pref != integrations.control_port) {
out.stopped = running.take().is_some();
// The preference's range is 0..=65535; anything else picks a free port.
let port = u16::try_from(integrations.control_port).unwrap_or(0);
match start(dir, port, ctx, integrations.control_port) {
Ok((r, requests)) => {
out.requests = Some(requests);
*running = Some(r);
}
Err(e) => {
log::warn!("{e}");
out.status.error = Some(e);
return out;
}
}
}
out.status.port = running.as_ref().map(|r| r.server.port);
// Agent requests always go through the automation policy; without folders they get no file
// access at all (as `--control` without automation roots). A folder that can't be opened, or
// isn't an absolute path, is left out (that direction fails closed) and named, as at launch.
let no_flags = photocraft_automation::args::AutomationArgs { automation_read_root: Vec::new(), automation_write_root: None };
let workspace = match crate::automation_workspace(&no_flags, integrations) {
Ok((workspace, warning)) => {
if let Some(w) = warning {
out.status.error = Some(format!("Agents can connect, but without file access there: {w}"));
}
workspace
}
Err(e) => {
out.status.error = Some(format!("Agents can connect, but without file access: {e}"));
photocraft_automation::AuthorizedWorkspace::default()
}
};
out.automation = crate::services::automation(Some(workspace));
out
}
/// How often [`launcher_watch`] looks at the ArtCraft Launcher's files.
const LAUNCHER_POLL: std::time::Duration = std::time::Duration::from_secs(2);
/// Whether the ArtCraft Launcher turned agents on for every Craft app
/// ([`agent_link::launcher_allows_agents`]), watched on its own thread so the UI can ask every
/// frame without touching the disk. A change wakes the UI, which then starts or stops the
/// connection. Without a thread (one couldn't be started) the answer stays what it was at launch.
pub fn launcher_watch(ctx: &egui::Context) -> Box<dyn Fn() -> bool> {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let on = Arc::new(AtomicBool::new(agent_link::launcher_allows_agents()));
let (seen, ctx) = (on.clone(), ctx.clone());
let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || {
loop {
std::thread::sleep(LAUNCHER_POLL);
let now = agent_link::launcher_allows_agents();
if seen.swap(now, Ordering::Relaxed) != now {
log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" });
ctx.request_repaint();
}
}
});
if let Err(e) = started {
log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}");
}
Box::new(move || on.load(Ordering::Relaxed))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
fn temp() -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("photocraft-agent-service-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn on(port: u32) -> Integrations {
Integrations { connect_agents: true, control_port: port, ..Default::default() }
}
#[test]
fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() {
let dir = temp();
let ctx = egui::Context::default();
let mut link = service(Some(dir.clone()));
// Off (the default): nothing listens, nothing is published.
let off = link(&Integrations::default(), &ctx);
assert!(off.requests.is_none() && !off.stopped && off.status.port.is_none());
assert!(off.automation.command.is_none(), "no agent policy without a connection");
assert_eq!(agent_link::read_connection(&dir).unwrap(), None);
let started = link(&on(0), &ctx);
let port = started.status.port.unwrap();
assert!(started.requests.is_some());
assert!(started.automation.command.is_some() && started.automation.authorize.is_some(), "agent requests go through the policy");
assert!(started.automation.read.is_some(), "the workspace answers (and refuses: no folder chosen)");
let c = agent_link::read_connection(&dir).unwrap().unwrap();
assert_eq!((c.port, c.pid), (port, std::process::id()));
assert!(agent_link::probe(port, agent_link::PROBE_TIMEOUT));
let token = security::client_token(None, Some(&c.token_file)).unwrap();
// Folder changes keep the server and its token.
let folders = Integrations { read_root: dir.to_string_lossy().into_owned(), ..on(0) };
let changed = link(&folders, &ctx);
assert!(changed.requests.is_none() && !changed.stopped);
assert_eq!(changed.status.port, Some(port));
assert!(changed.status.error.is_none(), "{:?}", changed.status.error);
assert_eq!(security::client_token(None, Some(&c.token_file)).unwrap(), token);
// A missing folder still connects, without file access, and says why.
let missing = Integrations { write_root: dir.join("nope").to_string_lossy().into_owned(), ..on(0) };
let partial = link(&missing, &ctx);
assert_eq!(partial.status.port, Some(port));
assert!(partial.status.error.as_deref().is_some_and(|e| e.contains("without file access")), "{:?}", partial.status.error);
assert!(partial.automation.command.is_some());
let stopped = link(&Integrations::default(), &ctx);
assert!(stopped.stopped && stopped.status.port.is_none());
assert_eq!(agent_link::read_connection(&dir).unwrap(), None, "the connection file goes with the server");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while agent_link::probe(port, agent_link::PROBE_TIMEOUT) {
assert!(std::time::Instant::now() < deadline, "port {port} still open");
std::thread::sleep(std::time::Duration::from_millis(20));
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_new_port_restarts_with_the_same_token_and_a_taken_port_is_reported() {
let dir = temp();
let ctx = egui::Context::default();
let mut link = service(Some(dir.clone()));
let first = link(&on(0), &ctx);
let first_port = first.status.port.unwrap();
let token_file = dir.join(agent_link::TOKEN_FILE);
let first_token = std::fs::read_to_string(&token_file).unwrap();
// A taken port: the error names it and nothing is published for it.
let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let taken_port = taken.local_addr().unwrap().port();
let failed = link(&on(u32::from(taken_port)), &ctx);
assert!(failed.stopped && failed.requests.is_none() && failed.status.port.is_none());
assert!(failed.status.error.as_deref().is_some_and(|e| e.contains(&taken_port.to_string())), "{:?}", failed.status.error);
assert_eq!(agent_link::read_connection(&dir).unwrap(), None);
drop(taken);
// Back to any port: the token in the settings folder is kept, so a client holding it
// (a `--bridge` setup reading the token file) needn't be set up again.
let again = link(&on(0), &ctx);
assert!(again.requests.is_some());
assert!(again.status.port.is_some_and(|p| p != 0));
assert_eq!(std::fs::read_to_string(&token_file).unwrap(), first_token);
let _ = first_port;
drop(link);
assert_eq!(agent_link::read_connection(&dir).unwrap(), None, "quitting removes the connection file");
let _ = std::fs::remove_dir_all(&dir);
}
/// A token file that can't be written (here the "settings folder" is a file) leaves the
/// connection off with the reason shown, and its port free.
#[test]
fn a_token_file_that_cannot_be_written_leaves_agents_off() {
let dir = temp();
let settings = dir.join("not-a-folder");
std::fs::write(&settings, b"").unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let mut link = service(Some(settings));
let r = link(&on(u32::from(port)), &egui::Context::default());
assert!(r.requests.is_none() && r.status.port.is_none());
assert!(r.status.error.as_deref().is_some_and(|e| e.contains("token file")), "{:?}", r.status.error);
std::net::TcpListener::bind(("127.0.0.1", port)).expect("the port was let go");
let _ = std::fs::remove_dir_all(&dir);
}
/// A relative folder would depend on the folder the app was started from: left out and named.
#[test]
fn a_relative_folder_is_left_out_with_a_reason() {
let dir = temp();
let mut link = service(Some(dir.clone()));
let r = link(&Integrations { read_root: ".".into(), ..on(0) }, &egui::Context::default());
assert!(r.status.port.is_some());
assert!(r.status.error.as_deref().is_some_and(|e| e.contains("not an absolute path")), "{:?}", r.status.error);
drop(link);
let _ = std::fs::remove_dir_all(&dir);
}
/// Allow Agent Control off (in the file; the dialog doesn't show it) refuses this server too.
#[test]
fn allow_agent_control_off_keeps_agents_out() {
let dir = temp();
let mut link = service(Some(dir.clone()));
let r = link(&Integrations { allow_agent_control: false, ..on(0) }, &egui::Context::default());
assert!(r.requests.is_none() && r.status.port.is_none() && r.automation.command.is_none());
assert!(r.status.error.as_deref().is_some_and(|e| e.contains("Allow Agent Control")), "{:?}", r.status.error);
assert_eq!(agent_link::read_connection(&dir).unwrap(), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn no_settings_folder_is_an_error_not_a_panic() {
let mut link = service(None);
let r = link(&on(0), &egui::Context::default());
assert!(r.requests.is_none() && r.status.error.is_some());
}
}
-221
View File
@@ -1,221 +0,0 @@
//! Linux desktop colour scheme, including Wayland compositors that do not report a winit theme.
#[cfg(target_os = "linux")]
const PORTAL_NAMESPACE: &str = "org.freedesktop.appearance";
#[cfg(target_os = "linux")]
const PORTAL_KEY: &str = "color-scheme";
#[cfg(target_os = "linux")]
pub(crate) fn portal_proxy() -> Option<zbus::blocking::Proxy<'static>> {
let conn = zbus::blocking::connection::Builder::session().ok()?.method_timeout(std::time::Duration::from_secs(2)).build().ok()?;
zbus::blocking::Proxy::new(&conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Settings").ok()
}
#[cfg(target_os = "linux")]
fn portal_theme(proxy: &zbus::blocking::Proxy<'_>) -> Option<egui::Theme> {
let value: zbus::zvariant::OwnedValue = proxy.call("Read", &(PORTAL_NAMESPACE, PORTAL_KEY)).ok()?;
portal_code(value).and_then(decode).or_else(gtk_theme)
}
#[cfg(target_os = "linux")]
fn portal_code(value: zbus::zvariant::OwnedValue) -> Option<u32> {
let mut value: zbus::zvariant::Value<'_> = value.into();
// The Settings.Read result is a variant; some portals nest another variant inside it.
for _ in 0..4 {
match value {
zbus::zvariant::Value::Value(inner) => value = *inner,
other => return u32::try_from(other).ok(),
}
}
None
}
#[cfg(target_os = "linux")]
fn decode(code: u32) -> Option<egui::Theme> {
match code {
1 => Some(egui::Theme::Dark),
2 => Some(egui::Theme::Light),
_ => None,
}
}
/// GNOME fallback when the portal has no preference. Read only on the appearance worker,
/// using an absolute path rather than the shell's PATH.
#[cfg(target_os = "linux")]
fn gtk_theme() -> Option<egui::Theme> {
let exe = ["/usr/bin/gsettings", "/bin/gsettings", "/usr/local/bin/gsettings"].into_iter().find(|p| std::path::Path::new(p).is_file())?;
let output = std::process::Command::new(exe).args(["get", "org.gnome.desktop.interface", "color-scheme"]).output().ok()?;
if !output.status.success() {
return None;
}
parse_gtk_scheme(std::str::from_utf8(&output.stdout).ok()?)
}
#[cfg(target_os = "linux")]
fn parse_gtk_scheme(s: &str) -> Option<egui::Theme> {
match s.trim().trim_matches('\'') {
"prefer-dark" => Some(egui::Theme::Dark),
"prefer-light" | "default" => Some(egui::Theme::Light),
_ => None,
}
}
#[cfg(target_os = "linux")]
fn code_of(theme: Option<egui::Theme>) -> u8 {
match theme {
Some(egui::Theme::Dark) => 1,
Some(egui::Theme::Light) => 2,
None => 0,
}
}
#[cfg(target_os = "linux")]
fn portal_startup<T>(subscribe: impl FnOnce(), read: impl FnOnce() -> T) -> T {
subscribe();
read()
}
/// Reads the colour scheme once, then follows the portal's `SettingChanged` signal. There is no
/// polling: the worker sleeps in the signal iterator and wakes the UI only when the value changes.
pub fn service() -> Option<photocraft_ui_egui::SystemThemeFn> {
#[cfg(target_os = "linux")]
{
start(|publisher| {
let proxy = portal_proxy();
// Subscribe before the first read, so a change during start-up isn't lost.
let mut signals = None;
let initial = portal_startup(
|| signals = proxy.as_ref().and_then(|proxy| proxy.receive_signal("SettingChanged").ok()),
|| proxy.as_ref().and_then(portal_theme).or_else(gtk_theme),
);
publisher.publish(initial);
let Some(signals) = signals else { return };
for message in signals {
let Ok((namespace, key, changed)) = message.body().deserialize::<(String, String, zbus::zvariant::OwnedValue)>() else {
continue;
};
if namespace != PORTAL_NAMESPACE || key != PORTAL_KEY {
continue;
}
publisher.publish(portal_code(changed).and_then(decode).or_else(gtk_theme));
}
})
}
#[cfg(not(target_os = "linux"))]
{
None
}
}
/// The worker's handle on the shared value. Every change wakes the registered UI, including the
/// first read when it lands after the start-up wait below.
#[cfg(target_os = "linux")]
struct Publisher {
value: std::sync::Arc<std::sync::atomic::AtomicU8>,
wake: std::sync::Arc<std::sync::OnceLock<egui::Context>>,
ready: std::sync::mpsc::Sender<()>,
}
#[cfg(target_os = "linux")]
impl Publisher {
fn publish(&self, theme: Option<egui::Theme>) {
let code = code_of(theme);
if self.value.swap(code, std::sync::atomic::Ordering::Relaxed) != code
&& let Some(ctx) = self.wake.get()
{
ctx.request_repaint();
}
let _ = self.ready.send(());
}
}
/// Runs `worker` on its own thread and waits up to 250 ms for its first value, so a fast desktop
/// answers before the first frame.
#[cfg(target_os = "linux")]
fn start(worker: impl FnOnce(&Publisher) + Send + 'static) -> Option<photocraft_ui_egui::SystemThemeFn> {
use std::sync::{Arc, OnceLock, atomic::AtomicU8};
let value = Arc::new(AtomicU8::new(0));
let wake: Arc<OnceLock<egui::Context>> = Arc::new(OnceLock::new());
let (ready, wait) = std::sync::mpsc::channel();
let publisher = Publisher { value: Arc::clone(&value), wake: Arc::clone(&wake), ready };
std::thread::Builder::new().name("appearance-portal".into()).spawn(move || worker(&publisher)).ok()?;
let _ = wait.recv_timeout(std::time::Duration::from_millis(250));
Some(Box::new(move |ctx| {
let _ = wake.set(ctx.clone());
decode(u32::from(value.load(std::sync::atomic::Ordering::Relaxed)))
}))
}
#[cfg(test)]
mod tests {
#[cfg(target_os = "linux")]
#[test]
fn startup_keeps_changes_emitted_during_initial_read() {
use std::cell::Cell;
for (initial_value, changed_value) in [(2, 1), (1, 2), (2, 2)] {
let subscribed = Cell::new(false);
let mut portal_value = initial_value;
let mut pending_signal = None;
let initial = super::portal_startup(
|| subscribed.set(true),
|| {
let initial = portal_value;
portal_value = changed_value;
if subscribed.get() && portal_value != initial {
pending_signal = Some(portal_value);
}
initial
},
);
let cached = pending_signal.unwrap_or(initial);
assert_eq!(cached, changed_value, "portal changed during startup but cached {cached}");
}
}
#[cfg(target_os = "linux")]
#[test]
fn portal_scheme_values() {
assert_eq!(super::decode(0), None);
assert_eq!(super::decode(1), Some(egui::Theme::Dark));
assert_eq!(super::decode(2), Some(egui::Theme::Light));
assert_eq!(super::decode(9), None);
let nested = zbus::zvariant::Value::Value(Box::new(zbus::zvariant::Value::Value(Box::new(zbus::zvariant::Value::U32(2)))));
assert_eq!(super::portal_code(zbus::zvariant::OwnedValue::try_from(nested).unwrap()), Some(2));
assert_eq!(super::parse_gtk_scheme("'prefer-light'\n"), Some(egui::Theme::Light));
assert_eq!(super::parse_gtk_scheme("'prefer-dark'\n"), Some(egui::Theme::Dark));
// GNOME's "default" appearance is light, even though the portal reports no preference.
assert_eq!(super::parse_gtk_scheme("'default'\n"), Some(egui::Theme::Light));
assert_eq!(super::parse_gtk_scheme("default"), Some(egui::Theme::Light));
assert_eq!(super::parse_gtk_scheme("'not-a-scheme'"), None);
}
/// #2798: a first read that misses the start-up wait still wakes the idle UI.
#[cfg(target_os = "linux")]
#[test]
fn late_initial_read_requests_repaint() {
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
let (release, gate) = std::sync::mpsc::channel::<()>();
let (done, finished) = std::sync::mpsc::channel::<()>();
let reader = super::start(move |publisher| {
let _ = gate.recv();
publisher.publish(Some(egui::Theme::Light));
let _ = done.send(());
})
.expect("worker thread");
let ctx = egui::Context::default();
let repaints = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&repaints);
ctx.set_request_repaint_callback(move |_| {
counter.fetch_add(1, Ordering::Relaxed);
});
assert_eq!(reader(&ctx), None, "start-up wait elapsed without an answer");
release.send(()).unwrap();
finished.recv().unwrap();
assert_eq!(repaints.load(Ordering::Relaxed), 1);
assert_eq!(reader(&ctx), Some(egui::Theme::Light));
}
}
-399
View File
@@ -1,399 +0,0 @@
//! Linux: which desktop the custom title bar's caption buttons look like, and which buttons go on
//! which side (`photocraft_ui_egui::CaptionStyle`). GNOME gets libadwaita's buttons in the order of
//! its `button-layout` setting (read through the settings portal, and followed as it changes); KDE
//! gets Breeze's in KWin's order (`kwinrc`); other desktops get plain round buttons, or Adwaita's
//! or Breeze's when their GTK theme is one of those, in GTK's `gtk-decoration-layout` order.
//!
//! `PHOTOCRAFT_CAPTION_STYLE` (`windows`, `adwaita`, `breeze`, `generic`) and
//! `PHOTOCRAFT_CAPTION_LAYOUT` (a GTK layout such as `close,minimize:`) override what is found.
#[cfg(target_os = "linux")]
use photocraft_ui_egui::{CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle};
#[cfg(target_os = "linux")]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Desktop {
Gnome,
Kde,
Other,
}
/// The desktop, from the first of its variables that is set: `ubuntu:GNOME`, `Budgie:GNOME` and
/// the like count as GNOME.
#[cfg(target_os = "linux")]
fn desktop(var: &dyn Fn(&str) -> Option<String>) -> Desktop {
for key in ["XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "DESKTOP_SESSION"] {
let Some(v) = var(key).map(|v| v.to_ascii_lowercase()).filter(|v| !v.trim().is_empty()) else { continue };
return if v.contains("gnome") {
Desktop::Gnome
} else if v.contains("kde") || v.contains("plasma") {
Desktop::Kde
} else {
Desktop::Other
};
}
if var("KDE_FULL_SESSION").is_some() {
Desktop::Kde
} else if var("GNOME_DESKTOP_SESSION_ID").is_some() {
Desktop::Gnome
} else {
Desktop::Other
}
}
/// GNOME's apps are libadwaita's whatever the GTK theme, and KWin draws Breeze; elsewhere the GTK
/// theme says (Adwaita, adw-gtk3, Yaru, Breeze), and any other theme gets the plain buttons.
#[cfg(target_os = "linux")]
fn family(desktop: Desktop, gtk_theme: Option<&str>) -> CaptionFamily {
match desktop {
Desktop::Gnome => CaptionFamily::Adwaita,
Desktop::Kde => CaptionFamily::Breeze,
Desktop::Other => {
let theme = gtk_theme.unwrap_or_default().trim().to_ascii_lowercase();
if ["adwaita", "adw-gtk3", "yaru"].iter().any(|p| theme.starts_with(p)) {
CaptionFamily::Adwaita
} else if theme.starts_with("breeze") {
CaptionFamily::Breeze
} else {
CaptionFamily::Generic
}
}
}
}
/// The value of `key` in `[section]` of an INI-style file (GTK's `settings.ini`, KDE's `kwinrc`).
#[cfg(target_os = "linux")]
fn ini_value(text: &str, section: &str, key: &str) -> Option<String> {
let mut inside = false;
for line in text.lines().map(str::trim) {
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
inside = name == section;
} else if inside
&& let Some((k, v)) = line.split_once('=')
&& k.trim() == key
{
return Some(v.trim().to_string());
}
}
None
}
/// KWin's button order (`[org.kde.kdecoration2]` `ButtonsOnLeft` / `ButtonsOnRight`, one letter a
/// button: `I` minimize, `A` maximize, `X` close), as a GTK layout. Missing keys keep KWin's
/// defaults: the window menu on the left, minimize, maximize and close on the right.
#[cfg(target_os = "linux")]
fn kwin_layout(kwinrc: &str) -> String {
let side = |key: &str, default: &str| {
let letters = ini_value(kwinrc, "org.kde.kdecoration2", key).unwrap_or_else(|| default.to_string());
letters
.chars()
.filter_map(|c| match c {
'I' => Some("minimize"),
'A' => Some("maximize"),
'X' => Some("close"),
_ => None,
})
.collect::<Vec<_>>()
.join(",")
};
format!("{}:{}", side("ButtonsOnLeft", "MS"), side("ButtonsOnRight", "HIAX"))
}
/// What the style is worked out from.
#[cfg(target_os = "linux")]
#[derive(Clone, Default)]
struct Found {
gtk_theme: Option<String>,
/// A GTK decoration layout.
layout: Option<String>,
icon_theme: Option<String>,
}
/// The icon theme the glyphs come from: `PHOTOCRAFT_CAPTION_ICONS` (`none` draws PhotoCraft's own),
/// the desktop's setting, or its default theme.
#[cfg(target_os = "linux")]
fn icon_theme_name(desktop: Desktop, found: &Found, var: &dyn Fn(&str) -> Option<String>) -> Option<String> {
match var("PHOTOCRAFT_CAPTION_ICONS") {
Some(name) if name.trim().eq_ignore_ascii_case("none") => None,
Some(name) => Some(name.trim().to_string()),
None => Some(found.icon_theme.clone().unwrap_or_else(|| if desktop == Desktop::Kde { "breeze" } else { "Adwaita" }.into())),
}
}
/// The style from what was found; `icons` loads a theme's glyphs.
#[cfg(target_os = "linux")]
fn resolve(desktop: Desktop, found: &Found, var: &dyn Fn(&str) -> Option<String>, icons: &dyn Fn(&str) -> Option<CaptionIcons>) -> CaptionStyle {
let family = var("PHOTOCRAFT_CAPTION_STYLE").and_then(|s| CaptionFamily::parse(&s)).unwrap_or_else(|| family(desktop, found.gtk_theme.as_deref()));
// GNOME's own default shows Close only; GTK's shows all three.
let default = if desktop == Desktop::Gnome { "appmenu:close" } else { "menu:minimize,maximize,close" };
let layout = var("PHOTOCRAFT_CAPTION_LAYOUT").or_else(|| found.layout.clone()).unwrap_or_else(|| default.to_string());
let mut style = CaptionStyle::from_gtk_layout(family, &layout);
style.icons = icon_theme_name(desktop, found, var).and_then(|name| icons(&name));
style
}
#[cfg(target_os = "linux")]
fn read_text(path: &std::path::Path) -> Option<String> {
crate::icon_theme::read_small(path).map(|b| String::from_utf8_lossy(&b).into_owned())
}
/// The themes and layout from the desktop's files: `kwinrc` and `kdeglobals` on KDE, GTK 3's
/// `settings.ini` elsewhere (where GNOME's portal answers, read later, replace them).
#[cfg(target_os = "linux")]
fn from_files(desktop: Desktop, var: &dyn Fn(&str) -> Option<String>) -> Found {
let config = var("XDG_CONFIG_HOME")
.filter(|d| std::path::Path::new(d).is_absolute())
.map(std::path::PathBuf::from)
.or_else(|| var("HOME").map(|h| std::path::Path::new(&h).join(".config")));
let Some(config) = config else { return Found::default() };
let gtk = read_text(&config.join("gtk-3.0").join("settings.ini")).unwrap_or_default();
let gtk_theme = ini_value(&gtk, "Settings", "gtk-theme-name");
if desktop == Desktop::Kde {
let layout = Some(kwin_layout(&read_text(&config.join("kwinrc")).unwrap_or_default()));
let icon_theme = ini_value(&read_text(&config.join("kdeglobals")).unwrap_or_default(), "Icons", "Theme");
Found { gtk_theme, layout, icon_theme }
} else {
let layout = ini_value(&gtk, "Settings", "gtk-decoration-layout");
Found { gtk_theme, layout, icon_theme: ini_value(&gtk, "Settings", "gtk-icon-theme-name") }
}
}
/// The caption glyphs of icon theme `theme` (`window-*-symbolic.svg`), read now and rendered at
/// whatever size the bar asks for. `None` when the theme (with its parents) has none of them.
#[cfg(target_os = "linux")]
fn load_icons(theme: &str) -> Option<CaptionIcons> {
use crate::icon_theme::{IconTheme, base_dirs, rasterize_mask, read_small};
let found = IconTheme::load(theme, &base_dirs(&|k: &str| std::env::var(k).ok()))?;
let svg = |name: &str| found.find_svg(name).and_then(|p| read_small(&p)).map(std::sync::Arc::<[u8]>::from);
let files = [svg("window-minimize-symbolic"), svg("window-maximize-symbolic"), svg("window-restore-symbolic"), svg("window-close-symbolic")];
if files.iter().all(Option::is_none) {
return None;
}
let render = move |icon: CaptionIcon, px: u32| {
let i = match icon {
CaptionIcon::Minimize => 0,
CaptionIcon::Maximize => 1,
CaptionIcon::Restore => 2,
CaptionIcon::Close => 3,
};
files.get(i)?.as_deref().and_then(|svg| rasterize_mask(svg, px))
};
Some(CaptionIcons { theme: theme.to_string(), render: std::sync::Arc::new(render) })
}
/// [`load_icons`] for the last theme asked for, kept, so a layout change doesn't reread it.
#[cfg(target_os = "linux")]
#[derive(Default)]
struct IconCache(std::sync::Mutex<Option<(String, Option<CaptionIcons>)>>);
#[cfg(target_os = "linux")]
impl IconCache {
fn get(&self, theme: &str) -> Option<CaptionIcons> {
let mut last = self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some((name, icons)) = last.as_ref()
&& name == theme
{
return icons.clone();
}
let icons = load_icons(theme);
*last = Some((theme.to_string(), icons.clone()));
icons
}
}
#[cfg(target_os = "linux")]
const WM_NAMESPACE: &str = "org.gnome.desktop.wm.preferences";
#[cfg(target_os = "linux")]
const LAYOUT_KEY: &str = "button-layout";
#[cfg(target_os = "linux")]
const INTERFACE_NAMESPACE: &str = "org.gnome.desktop.interface";
#[cfg(target_os = "linux")]
const ICONS_KEY: &str = "icon-theme";
/// A string setting from the portal, unwrapping the variants some portals nest it in.
#[cfg(target_os = "linux")]
fn portal_string(value: zbus::zvariant::OwnedValue) -> Option<String> {
let mut value: zbus::zvariant::Value<'_> = value.into();
for _ in 0..4 {
match value {
zbus::zvariant::Value::Value(inner) => value = *inner,
zbus::zvariant::Value::Str(s) => return Some(s.to_string()),
_ => return None,
}
}
None
}
/// The caption style now, then with the icon theme's glyphs and (GNOME) the portal's settings,
/// following the button layout and icon theme as they change. A worker does the file and D-Bus
/// work and wakes the UI only when the style changes; the first answer usually lands before the
/// first frame.
pub fn service() -> Option<photocraft_ui_egui::CaptionStyleFn> {
#[cfg(target_os = "linux")]
{
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
let var = |k: &str| std::env::var(k).ok();
let desktop = desktop(&var);
let mut found = from_files(desktop, &var);
// Icons need the theme read, which takes tens of milliseconds: the worker brings them.
let current = Arc::new(Mutex::new(resolve(desktop, &found, &var, &|_: &str| None)));
let wake: Arc<OnceLock<egui::Context>> = Arc::new(OnceLock::new());
let (shared, waker) = (Arc::clone(&current), Arc::clone(&wake));
let cache = IconCache::default();
let publish = move |found: &Found| {
let style = resolve(desktop, found, &|k: &str| std::env::var(k).ok(), &|t: &str| cache.get(t));
let mut cur = shared.lock().unwrap_or_else(PoisonError::into_inner);
if *cur != style {
*cur = style;
if let Some(ctx) = waker.get() {
ctx.request_repaint();
}
}
};
let (ready, wait) = std::sync::mpsc::channel();
let spawned = std::thread::Builder::new().name("caption-style".into()).spawn(move || {
let proxy = if desktop == Desktop::Gnome { crate::appearance::portal_proxy() } else { None };
let Some(proxy) = proxy else {
publish(&found);
let _ = ready.send(());
return;
};
// Subscribe before the first read, so a change during start-up isn't lost.
let signals = proxy.receive_signal("SettingChanged").ok();
let read = |namespace: &str, key: &str| {
let value: Option<zbus::zvariant::OwnedValue> = proxy.call("Read", &(namespace, key)).ok();
value.and_then(portal_string)
};
found.layout = read(WM_NAMESPACE, LAYOUT_KEY).or(found.layout.take());
found.icon_theme = read(INTERFACE_NAMESPACE, ICONS_KEY).or(found.icon_theme.take());
publish(&found);
let _ = ready.send(());
for message in signals.into_iter().flatten() {
let Ok((namespace, key, value)) = message.body().deserialize::<(String, String, zbus::zvariant::OwnedValue)>() else { continue };
match (namespace.as_str(), key.as_str()) {
(WM_NAMESPACE, LAYOUT_KEY) => found.layout = portal_string(value),
(INTERFACE_NAMESPACE, ICONS_KEY) => found.icon_theme = portal_string(value),
_ => continue,
}
publish(&found);
}
});
// A fast desktop answers before the first frame; a slow one updates the bar later.
if spawned.is_ok() {
let _ = wait.recv_timeout(std::time::Duration::from_millis(150));
}
Some(Box::new(move |ctx| {
let _ = wake.set(ctx.clone());
current.lock().unwrap_or_else(PoisonError::into_inner).clone()
}))
}
#[cfg(not(target_os = "linux"))]
{
None
}
}
#[cfg(all(test, target_os = "linux"))]
mod tests {
use super::*;
use photocraft_ui_egui::Caption::{Close, Maximize, Minimize};
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> + use<> {
let pairs: Vec<(String, String)> = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
move |k| pairs.iter().find(|(key, _)| key == k).map(|(_, v)| v.clone())
}
#[test]
fn the_desktop_comes_from_the_first_variable_set() {
assert_eq!(desktop(&env(&[("XDG_CURRENT_DESKTOP", "ubuntu:GNOME")])), Desktop::Gnome);
assert_eq!(desktop(&env(&[("XDG_CURRENT_DESKTOP", "KDE")])), Desktop::Kde);
assert_eq!(desktop(&env(&[("XDG_CURRENT_DESKTOP", "X-Cinnamon"), ("KDE_FULL_SESSION", "true")])), Desktop::Other);
assert_eq!(desktop(&env(&[("XDG_CURRENT_DESKTOP", " "), ("DESKTOP_SESSION", "plasma")])), Desktop::Kde);
assert_eq!(desktop(&env(&[("KDE_FULL_SESSION", "true")])), Desktop::Kde);
assert_eq!(desktop(&env(&[("GNOME_DESKTOP_SESSION_ID", "this-is-deprecated")])), Desktop::Gnome);
assert_eq!(desktop(&env(&[])), Desktop::Other);
}
#[test]
fn the_family_follows_the_desktop_then_the_gtk_theme() {
assert_eq!(family(Desktop::Gnome, Some("Arc")), CaptionFamily::Adwaita);
assert_eq!(family(Desktop::Kde, None), CaptionFamily::Breeze);
assert_eq!(family(Desktop::Other, Some("adw-gtk3-dark")), CaptionFamily::Adwaita);
assert_eq!(family(Desktop::Other, Some("Yaru-blue")), CaptionFamily::Adwaita);
assert_eq!(family(Desktop::Other, Some("Breeze-Dark")), CaptionFamily::Breeze);
assert_eq!(family(Desktop::Other, Some("Mint-Y")), CaptionFamily::Generic);
assert_eq!(family(Desktop::Other, None), CaptionFamily::Generic);
}
#[test]
fn kwin_button_letters_become_a_gtk_layout() {
assert_eq!(kwin_layout(""), ":minimize,maximize,close", "KWin's defaults");
let rc = "[Desktops]\nButtonsOnLeft=X\n[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\nlibrary=org.kde.breeze\n";
assert_eq!(kwin_layout(rc), "close,minimize,maximize:");
assert_eq!(ini_value(rc, "org.kde.kdecoration2", "library").as_deref(), Some("org.kde.breeze"));
assert_eq!(ini_value(rc, "nope", "library"), None);
// Garbage is just no buttons on that side, never a panic.
assert_eq!(kwin_layout("[org.kde.kdecoration2]\nButtonsOnRight=ÿ€=X\n"), ":close");
}
fn no_icons(_: &str) -> Option<CaptionIcons> {
None
}
#[test]
fn the_icon_theme_comes_from_the_override_the_setting_or_the_desktop() {
let found = Found { icon_theme: Some("Papirus".into()), ..Found::default() };
assert_eq!(icon_theme_name(Desktop::Gnome, &found, &env(&[])).as_deref(), Some("Papirus"));
assert_eq!(icon_theme_name(Desktop::Gnome, &Found::default(), &env(&[])).as_deref(), Some("Adwaita"));
assert_eq!(icon_theme_name(Desktop::Kde, &Found::default(), &env(&[])).as_deref(), Some("breeze"));
assert_eq!(icon_theme_name(Desktop::Kde, &found, &env(&[("PHOTOCRAFT_CAPTION_ICONS", " None ")])), None);
assert_eq!(icon_theme_name(Desktop::Kde, &found, &env(&[("PHOTOCRAFT_CAPTION_ICONS", "Tela")])).as_deref(), Some("Tela"));
// The style carries what the loader returns for that name.
let s = resolve(Desktop::Gnome, &found, &env(&[]), &|t| {
(t == "Papirus").then(|| CaptionIcons { theme: t.into(), render: std::sync::Arc::new(|_, _| None) })
});
assert_eq!(s.icons.map(|i| i.theme).as_deref(), Some("Papirus"));
}
#[test]
fn layouts_and_overrides_resolve_to_a_style() {
let none = env(&[]);
let gnome = resolve(Desktop::Gnome, &Found::default(), &none, &no_icons);
assert_eq!((gnome.family, gnome.left, gnome.right), (CaptionFamily::Adwaita, vec![], vec![Close]), "GNOME's default layout");
let kde = resolve(Desktop::Kde, &Found { layout: Some(kwin_layout("")), ..Found::default() }, &none, &no_icons);
assert_eq!((kde.family, kde.right), (CaptionFamily::Breeze, vec![Minimize, Maximize, Close]));
let found = Found { gtk_theme: Some("Mint-Y".into()), layout: Some("close:".into()), icon_theme: None };
let other = resolve(Desktop::Other, &found, &none, &no_icons);
assert_eq!((other.family, other.left, other.right), (CaptionFamily::Generic, vec![Close], vec![]));
let forced = env(&[("PHOTOCRAFT_CAPTION_STYLE", "Breeze"), ("PHOTOCRAFT_CAPTION_LAYOUT", "minimize,close:maximize")]);
let s = resolve(Desktop::Gnome, &found, &forced, &no_icons);
assert_eq!((s.family, s.left, s.right), (CaptionFamily::Breeze, vec![Minimize, Close], vec![Maximize]));
// An unknown override name falls back to what was found.
assert_eq!(resolve(Desktop::Kde, &found, &env(&[("PHOTOCRAFT_CAPTION_STYLE", "aqua")]), &no_icons).family, CaptionFamily::Breeze);
}
#[test]
fn portal_strings_unwrap_nested_variants() {
use zbus::zvariant::{OwnedValue, Value};
let nested = Value::Value(Box::new(Value::Value(Box::new(Value::from("appmenu:close")))));
assert_eq!(portal_string(OwnedValue::try_from(nested).unwrap()).as_deref(), Some("appmenu:close"));
assert_eq!(portal_string(OwnedValue::try_from(Value::U32(7)).unwrap()), None);
}
#[test]
fn settings_files_are_read_from_the_config_dir() {
let dir = std::env::temp_dir().join(format!("photocraft-caption-{}", std::process::id()));
std::fs::create_dir_all(dir.join("gtk-3.0")).unwrap();
std::fs::write(dir.join("gtk-3.0/settings.ini"), "[Settings]\ngtk-theme-name=Yaru\ngtk-decoration-layout=close,maximize:\n").unwrap();
std::fs::write(dir.join("kwinrc"), "[org.kde.kdecoration2]\nButtonsOnRight=AX\n").unwrap();
std::fs::write(dir.join("kdeglobals"), "[Icons]\nTheme=breeze-dark\n").unwrap();
let var = env(&[("XDG_CONFIG_HOME", dir.to_str().unwrap())]);
let other = from_files(Desktop::Other, &var);
assert_eq!((other.gtk_theme.as_deref(), other.layout.as_deref()), (Some("Yaru"), Some("close,maximize:")));
let kde = from_files(Desktop::Kde, &var);
assert_eq!((kde.layout.as_deref(), kde.icon_theme.as_deref()), (Some(":maximize,close"), Some("breeze-dark")));
// A relative XDG_CONFIG_HOME is ignored, as the XDG spec says; no HOME: nothing found.
assert_eq!(from_files(Desktop::Other, &env(&[("XDG_CONFIG_HOME", "rel")])).layout, None);
let _ = std::fs::remove_dir_all(dir);
}
}
-449
View File
@@ -1,449 +0,0 @@
//! Localhost JSON-lines control server (one request per line, one reply per line).
//! Loopback only. This is the transport the MCP server will wrap.
//!
//! `--control` starts it for the whole run ([`start`]); Preferences › AI Integrations starts and
//! stops it while the app runs ([`listen`], see `agent_link`).
use std::io::{BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::{Duration, Instant};
use photocraft_automation::budgets::write_reply;
use photocraft_automation::security::{
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream,
read_bounded_line, repeat_auth_reply,
};
use photocraft_ui_egui::ControlRequest;
use photocraft_ui_egui::control::REPLY_DEADLINE;
use serde_json::{Value, json};
/// Start serving a listener already bound during startup, before a window is opened. It serves
/// for the whole run.
pub fn start(listener: TcpListener, token: String, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let port = listener.local_addr().map_or(0, |a| a.port());
eprintln!("photocraft: control server listening on {}", listening_addr(&listener, port));
std::thread::spawn(move || accept(listener, token, tx, ctx, None));
rx
}
/// A control server started by [`listen`]. Dropping it stops accepting connections; connections
/// already open end at their next request, once the app drops the request channel.
pub struct Listening {
/// The bound port (the one the system picked for port 0).
pub port: u16,
stop: Arc<AtomicBool>,
accept: Option<std::thread::JoinHandle<()>>,
}
impl Drop for Listening {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
// Wake the accept loop so it sees the flag and closes the listener, and wait for that, so
// the port is free when this returns (a restart on the same port binds it again at once).
// Without a wake-up the loop would block in `accept`: then don't wait.
let woke = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(500)).is_ok();
if woke && let Some(accept) = self.accept.take() {
let _ = accept.join();
}
}
}
/// Serve the control protocol on `127.0.0.1:port` (0 = any free port) until the returned
/// [`Listening`] is dropped.
pub fn listen(port: u16, token: String, ctx: egui::Context) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
let (tx, rx) = channel::<ControlRequest>();
let listener = TcpListener::bind(("127.0.0.1", port))?;
let port = listener.local_addr()?.port();
let stop = Arc::new(AtomicBool::new(false));
let stopped = stop.clone();
let accept = std::thread::Builder::new().name("control server".into()).spawn(move || accept(listener, token, tx, ctx, Some(stopped)))?;
Ok((rx, Listening { port, stop, accept: Some(accept) }))
}
/// Accept connections on `listener` and serve each on its own thread, until `stop` is set (never,
/// without one).
fn accept(listener: TcpListener, token: String, tx: Sender<ControlRequest>, ctx: egui::Context, stop: Option<Arc<AtomicBool>>) {
let limiter = ConnectionLimiter::new(MAX_CONNECTIONS);
let token = Arc::new(token);
for mut stream in listener.incoming().flatten() {
if stop.as_ref().is_some_and(|s| s.load(Ordering::Acquire)) {
break;
}
let Some(permit) = limiter.try_acquire() else {
let _ = configure_stream(&stream);
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"}));
continue;
};
let tx = tx.clone();
let ctx = ctx.clone();
let token = Arc::clone(&token);
std::thread::spawn(move || {
let _permit = permit;
serve(stream, &token, tx, ctx);
});
}
}
/// The address `listener` is bound to: with `--control 0` the OS picks the port, and a client
/// needs that one, not the requested 0 (#6427). Falls back to the requested port if the OS
/// can't report it.
fn listening_addr(listener: &TcpListener, requested_port: u16) -> String {
match listener.local_addr() {
Ok(addr) => addr.to_string(),
Err(_) => format!("127.0.0.1:{requested_port}"),
}
}
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context) {
serve_with_auth_deadline(stream, token, tx, ctx, AUTH_DEADLINE);
}
/// [`serve`] for a connection that must complete `auth` within `auth_deadline` of connecting,
/// however much it sends meanwhile (#4965); after that only the idle timeout applies.
fn serve_with_auth_deadline(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context, auth_deadline: Duration) {
if configure_stream(&stream).is_err() {
return;
}
let Ok(read) = stream.try_clone() else { return };
let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
let mut out = stream;
let mut line = String::new();
let mut handshake = ServerHandshake::new();
let mut authenticated = false;
loop {
match read_bounded_line(&mut reader, &mut line) {
Ok(LineRead::Eof) | Err(_) => break,
Ok(LineRead::TooLong) => {
let reply = json!({
"id": null,
"ok": false,
"error": format!("request exceeds {MAX_REQUEST_BYTES} bytes"),
});
let _ = write_reply(&mut out, &reply);
let _ = out.flush();
break;
}
Ok(LineRead::Line) if line.trim().is_empty() => continue,
Ok(LineRead::Line) => {}
}
if !authenticated {
let (reply, step) = handshake.reply(&line, token);
authenticated = step == AuthStep::Authenticated;
if authenticated && reader.get_mut().authenticated().is_err() {
break;
}
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() || step == AuthStep::Rejected {
break;
}
continue;
}
if let Some(reply) = repeat_auth_reply(&line) {
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() {
break;
}
continue;
}
let reply = match serde_json::from_str::<Value>(&line) {
Ok(msg) => {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let deadline = Instant::now() + REPLY_DEADLINE;
let (mut req, rrx) = ControlRequest::new(method, params);
req.deadline = Some(deadline);
let dispatch = req.dispatch.clone();
if tx.send(req).is_err() {
break;
}
ctx.request_repaint();
let mut r =
rrx.recv_timeout(deadline.saturating_duration_since(Instant::now())).unwrap_or_else(|_| json!({"ok": false, "error": dispatch.give_up()}));
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
r
}
Err(e) => json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}),
};
if write_reply(&mut out, &reply).is_err() {
break;
}
if out.flush().is_err() {
break;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::BufRead;
/// #6427: with port 0 the log names the port the OS bound, which a client can connect to.
#[test]
fn a_listening_server_picks_a_port_and_stops_when_dropped() {
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let (rx, server) = listen(0, TOKEN.into(), egui::Context::default()).unwrap();
let port = server.port;
assert_ne!(port, 0);
let handler = std::thread::spawn(move || {
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(req.method, "test.ping");
req.reply.send(json!({"ok": true, "result": "pong"})).unwrap();
});
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["ok"], true);
writeln!(stream, "{}", json!({"id": 2, "method": "test.ping"})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"], "pong");
handler.join().unwrap();
drop(server);
// The listener is closed when the drop returns: the same port binds again at once.
TcpListener::bind(("127.0.0.1", port)).expect("the port is free after the drop");
}
#[test]
fn port_zero_logs_the_bound_port() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let bound = listener.local_addr().unwrap();
assert_ne!(bound.port(), 0);
let logged = listening_addr(&listener, 0);
assert_eq!(logged, format!("127.0.0.1:{}", bound.port()));
TcpStream::connect(&logged).unwrap();
}
#[test]
fn a_prebound_listener_authenticates_and_dispatches_requests() {
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let requests = start(listener, TOKEN.into(), egui::Context::default());
let mut stream = TcpStream::connect(address).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut replies = BufReader::new(stream.try_clone().unwrap());
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap();
let mut line = String::new();
replies.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"]["authenticated"], true);
writeln!(stream, "{}", json!({"id": 2, "method": "test.bound"})).unwrap();
let request = requests.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(request.method, "test.bound");
request.reply.send(json!({"ok": true, "result": "served"})).unwrap();
line.clear();
replies.read_line(&mut line).unwrap();
let reply: Value = serde_json::from_str(&line).unwrap();
assert_eq!(reply["id"], 2);
assert_eq!(reply["result"], "served");
}
/// #4965: a connection that keeps sending without authenticating is closed at the deadline
/// (releasing its connection permit), and nothing it sent is dispatched.
#[test]
fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let started = Instant::now();
serve_with_auth_deadline(stream, "unused", tx, egui::Context::default(), Duration::from_millis(300));
started.elapsed()
});
// Blank lines and partial frames, one byte every 20 ms: each read succeeds long before
// the idle timeout.
let mut stream = TcpStream::connect(addr).unwrap();
for i in 0..150 {
let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " };
if stream.write_all(byte).is_err() {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
let served = server.join().unwrap();
assert!(served < Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}");
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
#[test]
fn oversized_reply_preserves_framing_id_and_the_next_control_request() {
use photocraft_automation::budgets::MAX_RESPONSE_BYTES;
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
serve(stream, TOKEN, tx, egui::Context::default());
});
let handler = std::thread::spawn(move || {
let first = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(first.method, "test.large");
assert!(first.deadline.is_some_and(|deadline| deadline > std::time::Instant::now()), "native requests carry their reply deadline");
first.reply.send(json!({"ok": true, "result": "x".repeat(MAX_RESPONSE_BYTES)})).unwrap();
let second = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(second.method, "test.small");
second.reply.send(json!({"ok": true, "result": "still serving"})).unwrap();
});
let mut stream = TcpStream::connect(addr).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["ok"], true);
writeln!(stream, "{}", json!({"id": 2, "method": "test.large"})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
let rejected: Value = serde_json::from_str(&line).unwrap();
assert_eq!(rejected["id"], 2);
assert_eq!(rejected["ok"], false);
assert!(rejected["error"].as_str().unwrap().contains("operation may have completed"));
writeln!(stream, "{}", json!({"id": 3, "method": "test.small"})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
let accepted: Value = serde_json::from_str(&line).unwrap();
assert_eq!(accepted["id"], 3);
assert_eq!(accepted["result"], "still serving");
drop(reader);
drop(stream);
handler.join().unwrap();
server.join().unwrap();
}
#[test]
fn bad_json_reply_carries_a_null_id_and_the_connection_keeps_serving() {
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
serve(stream, TOKEN, tx, egui::Context::default());
});
let handler = std::thread::spawn(move || {
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(req.method, "test.after");
req.reply.send(json!({"ok": true, "result": "still serving"})).unwrap();
});
let mut stream = TcpStream::connect(addr).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
writeln!(stream, "{}", json!({"id": "auth", "method": "auth", "params": {"token": TOKEN}})).unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["ok"], true);
writeln!(stream, "{{not json}}").unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
let bad: Value = serde_json::from_str(&line).unwrap();
let bad = bad.as_object().unwrap();
assert_eq!(bad.get("id"), Some(&Value::Null), "bad JSON reply must carry `id: null`: {line}");
assert_eq!(bad.get("ok"), Some(&Value::Bool(false)));
assert!(bad.get("error").and_then(Value::as_str).unwrap().starts_with("bad JSON: "));
writeln!(stream, "{}", json!({"id": 7, "method": "test.after"})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
let after: Value = serde_json::from_str(&line).unwrap();
assert_eq!(after["id"], 7);
assert_eq!(after["result"], "still serving");
drop(reader);
drop(stream);
handler.join().unwrap();
server.join().unwrap();
}
#[test]
fn repeat_auth_reports_already_authenticated_without_dispatching() {
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
serve(stream, TOKEN, tx, egui::Context::default());
});
let handler = std::thread::spawn(move || {
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(req.method, "test.after", "a repeat auth must not reach the UI dispatcher");
req.reply.send(json!({"ok": true, "result": "still serving"})).unwrap();
});
let mut stream = TcpStream::connect(addr).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
for id in ["auth", "again"] {
writeln!(stream, "{}", json!({"id": id, "method": "auth", "params": {"token": TOKEN}})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
}
let again: Value = serde_json::from_str(&line).unwrap();
assert_eq!(again["id"], "again");
assert_eq!(again["ok"], false);
assert_eq!(again["error"], "already authenticated");
writeln!(stream, "{}", json!({"id": 9, "method": "test.after"})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
let after: Value = serde_json::from_str(&line).unwrap();
assert_eq!(after["id"], 9);
assert_eq!(after["result"], "still serving");
drop(reader);
drop(stream);
handler.join().unwrap();
server.join().unwrap();
}
/// NV-6: the desktop server answers challenge authentication, proving it holds the token
/// before the client sends its proof, and dispatches only after that proof.
#[test]
fn challenge_authentication_proves_the_server_then_serves() {
use photocraft_automation::security::{CHALLENGE_METHOD, ProofRole, generate_nonce, handshake_proof, proof_matches};
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
serve(stream, TOKEN, tx, egui::Context::default());
});
let handler = std::thread::spawn(move || {
let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(req.method, "test.after", "only the request after the proof is dispatched");
req.reply.send(json!({"ok": true, "result": "served"})).unwrap();
});
let mut stream = TcpStream::connect(addr).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
let client_nonce = generate_nonce().unwrap();
writeln!(stream, "{}", json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}})).unwrap();
reader.read_line(&mut line).unwrap();
let challenge: Value = serde_json::from_str(&line).unwrap();
assert!(!line.contains(TOKEN), "{line}");
let server_nonce = challenge["result"]["serverNonce"].as_str().unwrap().to_owned();
let server_proof = challenge["result"]["serverProof"].as_str().unwrap();
assert!(proof_matches(TOKEN, ProofRole::Server, &client_nonce, &server_nonce, server_proof), "{line}");
let proof = handshake_proof(TOKEN, ProofRole::Client, &client_nonce, &server_nonce).unwrap();
writeln!(stream, "{}", json!({"id": 2, "method": "auth", "params": {"proof": proof}})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"]["authenticated"], true, "{line}");
writeln!(stream, "{}", json!({"id": 3, "method": "test.after"})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"], "served");
drop(reader);
drop(stream);
handler.join().unwrap();
server.join().unwrap();
}
}
+1 -1
View File
@@ -1159,7 +1159,7 @@ mod native {
#[test]
fn missing_editor_errors_name_the_dialog_option() {
let dialog = include_str!("../../../crates/ui-egui/src/smart_svg_ui.rs");
assert!(dialog.contains(&format!("(Editor::Program, \"{OTHER_APPLICATION}\")")), "the dialog label changed");
assert!(dialog.contains(&format!("(Editor::Program, \"program\", \"{OTHER_APPLICATION}\")")), "the dialog label changed");
let source = include_str!("external_svg.rs");
assert!(!source.contains(concat!("Other ", "editor")), "errors must name the dialog's option");
#[cfg(target_os = "linux")]
-230
View File
@@ -1,230 +0,0 @@
//! Why a File › Open / Save dialog may never appear on Linux (#3354).
//!
//! `rfd` talks to the XDG file-chooser portal through `libdbus-1`, which it loads at runtime, and
//! falls back to `zenity`. When neither works (a minimal window-manager session without a portal
//! backend) it logs the failure and answers "nothing picked", which the app took for Cancel: the
//! menu item did nothing and said nothing. [`start`] looks for the pieces once, in the background,
//! and [`known_problem`] returns what to install when a dialog came back empty and none of them
//! is there.
//!
//! The probe only ever explains an empty answer; it never stops a dialog from opening. Anything
//! it can't tell counts as present, so a working system never sees the message.
use std::sync::OnceLock;
/// What the probe found. `None` means it couldn't tell, which counts as present.
// Only Linux probes; the types and helpers stay testable on every platform.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Findings {
/// `libdbus-1.so.3` is in the linker cache (`rfd` loads it for the portal).
pub libdbus: Option<bool>,
/// The session bus has the portal's `FileChooser` interface (a portal and a backend for it).
pub file_chooser_portal: Option<bool>,
/// `zenity` is on `PATH` (`rfd`'s fallback).
pub zenity: bool,
}
/// The message for `findings`, or `None` when some file dialog should work.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub fn problem(findings: Findings) -> Option<String> {
let portal = findings.libdbus != Some(false) && findings.file_chooser_portal != Some(false);
if portal || findings.zenity {
return None;
}
let cause = if findings.libdbus == Some(false) { "libdbus is missing" } else { "no desktop portal offers a file chooser" };
Some(format!(
"No file dialog can open: {cause}. Install xdg-desktop-portal with a backend (xdg-desktop-portal-gtk, -kde or -gnome) and libdbus, or zenity. Meanwhile, drop a file onto the window or paste a copied image."
))
}
static RESULT: OnceLock<Option<String>> = OnceLock::new();
/// The problem found by [`start`], once it has finished.
pub fn known_problem() -> Option<String> {
RESULT.get().cloned().flatten()
}
/// Whether `program` is an executable file in one of the `path` directories.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn on_path(program: &str, path: &std::ffi::OsStr) -> bool {
std::env::split_paths(path).any(|dir| dir.join(program).is_file())
}
/// Look for the file dialog backends on a helper thread (the portal call can take a moment).
#[cfg(target_os = "linux")]
pub fn start() {
let spawned = std::thread::Builder::new().name("file dialog probe".into()).spawn(|| {
let findings = Findings {
libdbus: crate::linux_libs::cached("libdbus-1.so.3"),
file_chooser_portal: file_chooser_portal(),
zenity: std::env::var_os("PATH").is_some_and(|path| on_path("zenity", &path)),
};
log::info!("file dialog backends: {findings:?}");
let _ = RESULT.set(problem(findings));
});
if let Err(e) = spawned {
log::warn!("couldn't start the file dialog probe: {e}");
}
}
/// Whether the portal's `FileChooser` interface is on the session bus: `Some(false)` only when the
/// bus or the interface is definitely absent, `None` for anything inconclusive (a slow reply).
///
/// Asks the portal object to introspect itself rather than reading the interface's `version`
/// property: xdg-desktop-portal exports `FileChooser` only when a backend offers it, and without
/// one a property read fails with `InvalidArgs` ("No such interface"), an error the old check
/// didn't count as absent (#5739). The interface list answers the question directly.
#[cfg(target_os = "linux")]
fn file_chooser_portal() -> Option<bool> {
let Ok(conn) = zbus::blocking::connection::Builder::session().and_then(|b| b.method_timeout(std::time::Duration::from_secs(5)).build()) else {
return Some(false);
};
let reply = conn.call_method(
Some("org.freedesktop.portal.Desktop"),
"/org/freedesktop/portal/desktop",
Some("org.freedesktop.DBus.Introspectable"),
"Introspect",
&(),
);
match reply {
Ok(message) => match message.body().deserialize::<String>() {
Ok(xml) => Some(interface_listed(&xml)),
Err(_) => None,
},
Err(e) => classify_error(&e),
}
}
/// Whether introspection XML lists the portal's `FileChooser` interface (not a longer name such as
/// `FileChooser2`).
#[cfg(target_os = "linux")]
fn interface_listed(xml: &str) -> bool {
["\"", "'"].iter().any(|quote| xml.contains(&format!("<interface name={quote}org.freedesktop.portal.FileChooser{quote}")))
}
/// What a failed call says about the interface: `Some(false)` when the D-Bus error means the
/// service, object or interface isn't there, `None` for anything else (a timeout, a dropped
/// connection, an unknown error), which counts as present.
#[cfg(target_os = "linux")]
fn classify_error(e: &zbus::Error) -> Option<bool> {
use zbus::fdo::Error as Fdo;
// Names a bus daemon or portal answers with when the thing asked about is absent.
const ABSENT: [&str; 7] = ["ServiceUnknown", "NameHasNoOwner", "UnknownObject", "UnknownInterface", "UnknownMethod", "UnknownProperty", "InvalidArgs"];
match e {
zbus::Error::FDO(fdo) => matches!(
**fdo,
Fdo::ServiceUnknown(_)
| Fdo::NameHasNoOwner(_)
| Fdo::UnknownObject(_)
| Fdo::UnknownInterface(_)
| Fdo::UnknownMethod(_)
| Fdo::UnknownProperty(_)
| Fdo::InvalidArgs(_)
)
.then_some(false),
zbus::Error::MethodError(name, _, _) => ABSENT.iter().any(|n| name.as_str().ends_with(n)).then_some(false),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn found(libdbus: Option<bool>, file_chooser_portal: Option<bool>, zenity: bool) -> Findings {
Findings { libdbus, file_chooser_portal, zenity }
}
#[test]
fn a_working_backend_is_not_reported() {
assert_eq!(problem(found(Some(true), Some(true), false)), None, "portal");
assert_eq!(problem(found(Some(false), Some(false), true)), None, "zenity alone");
assert_eq!(problem(found(None, None, false)), None, "unknown counts as present");
assert_eq!(problem(found(Some(true), None, false)), None, "slow portal reply");
}
#[test]
fn nothing_to_show_a_dialog_with_is_explained() {
let no_portal = problem(found(Some(true), Some(false), false)).unwrap();
assert!(no_portal.contains("no desktop portal offers a file chooser") && no_portal.contains("xdg-desktop-portal"), "{no_portal}");
let no_dbus = problem(found(Some(false), Some(true), false)).unwrap();
assert!(no_dbus.contains("libdbus is missing"), "{no_dbus}");
}
#[test]
fn programs_are_found_on_the_given_path() {
let dir = std::env::temp_dir().join(format!("photocraft-probe-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("zenity"), b"").unwrap();
let path = std::env::join_paths([std::path::Path::new("/nonexistent"), dir.as_path()]).unwrap();
assert!(on_path("zenity", &path));
assert!(!on_path("kdialog", &path));
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(target_os = "linux")]
mod portal {
use super::super::*;
const WITH_FILE_CHOOSER: &str = r#"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/introspect.dtd">
<node>
<interface name="org.freedesktop.DBus.Peer"/>
<interface name="org.freedesktop.portal.Settings"><property name="version" type="u" access="read"/></interface>
<interface name="org.freedesktop.portal.FileChooser">
<method name="OpenFile"/>
</interface>
</node>"#;
const WITHOUT_FILE_CHOOSER: &str = r#"<node>
<interface name="org.freedesktop.DBus.Peer"/>
<interface name="org.freedesktop.portal.Settings"/>
</node>"#;
fn method_error(name: &'static str) -> zbus::Error {
let call = zbus::message::Message::method_call("/a", "M").unwrap().build(&()).unwrap();
let reply = zbus::message::Message::error(&call.header(), name).unwrap().build(&"detail").unwrap();
zbus::Error::MethodError(name.try_into().unwrap(), Some("detail".into()), reply)
}
#[test]
fn the_interface_list_says_whether_a_file_chooser_is_offered() {
assert!(interface_listed(WITH_FILE_CHOOSER));
assert!(interface_listed("<interface name='org.freedesktop.portal.FileChooser'>"), "single quotes");
assert!(!interface_listed(WITHOUT_FILE_CHOOSER), "portal without a backend");
assert!(!interface_listed(r#"<interface name="org.freedesktop.portal.FileChooser2">"#), "longer name");
assert!(!interface_listed(""));
}
#[test]
fn dbus_errors_for_a_missing_interface_mean_absent() {
// zbus's fdo proxies hand D-Bus errors back as `Error::FDO`, a plain method call as
// `MethodError`; both forms count. The portal answers `InvalidArgs` ("No such interface")
// when no backend offers the interface (#5739).
for e in [
zbus::fdo::Error::InvalidArgs("No such interface".into()),
zbus::fdo::Error::UnknownInterface("x".into()),
zbus::fdo::Error::ServiceUnknown("x".into()),
zbus::fdo::Error::NameHasNoOwner("x".into()),
zbus::fdo::Error::UnknownObject("x".into()),
] {
let desc = format!("{e:?}");
assert_eq!(classify_error(&zbus::Error::FDO(Box::new(e))), Some(false), "{desc}");
}
}
#[test]
fn method_error_names_still_count_as_absent() {
for name in ["org.freedesktop.DBus.Error.ServiceUnknown", "org.freedesktop.DBus.Error.InvalidArgs", "org.freedesktop.DBus.Error.UnknownMethod"] {
assert_eq!(classify_error(&method_error(name)), Some(false), "{name}");
}
assert_eq!(classify_error(&method_error("org.freedesktop.DBus.Error.AccessDenied")), None);
}
#[test]
fn inconclusive_errors_are_not_absent() {
assert_eq!(classify_error(&zbus::Error::FDO(Box::new(zbus::fdo::Error::NoReply("slow".into())))), None);
assert_eq!(classify_error(&zbus::Error::FDO(Box::new(zbus::fdo::Error::Failed("x".into())))), None);
assert_eq!(classify_error(&zbus::Error::InputOutput(std::sync::Arc::new(std::io::Error::other("gone")))), None);
}
}
}
+8 -35
View File
@@ -531,43 +531,16 @@ impl Sentinel {
}
}
/// The Linux display-server preference (`performance.linuxDisplayServer`) from the preferences
/// file, read before the window opens; `Auto` when the file or value is missing or unknown.
#[cfg(any(target_os = "linux", test))]
pub fn read_display_server(path: Option<&Path>) -> photocraft_engine::prefs::LinuxDisplayServer {
read_performance(path).map(|performance| performance.linux_display_server).unwrap_or_default()
/// The backend and rendering mode Preferences › Performance asks for, read before the window
/// opens: an explicit Rendering Mode, else the one older settings imply (`useGpu`, `gpuBackend`).
pub fn rendering_prefs(performance: &photocraft_engine::prefs::Performance) -> (GpuBackend, RenderingMode) {
(performance.gpu_backend, performance.effective_rendering_mode())
}
/// The preferences file's Performance section, read as the app reads it: a value of the wrong
/// type keeps its default without resetting the others. `None` without a file or section.
fn read_performance(path: Option<&Path>) -> Option<photocraft_engine::prefs::Performance> {
let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
v.get("performance").cloned().map(photocraft_engine::prefs::read_section)
}
/// Preferences › Performance › Graphics Adapter (`performance.gpuAdapter`), read before the window
/// opens; empty (automatic) when the file or value is missing or not text.
pub fn read_gpu_adapter(path: Option<&Path>) -> String {
read_performance(path).map(|performance| performance.gpu_adapter.chars().take(256).collect()).unwrap_or_default()
}
/// Preferences › Performance › Low-Latency Drawing (`performance.lowLatencyDrawing`, off unless
/// turned on), read before the window opens: it picks the surface's present mode.
pub fn read_low_latency(path: Option<&Path>) -> bool {
let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
let default = photocraft_engine::prefs::Preferences::default().performance.low_latency_drawing;
v.get("performance").and_then(|p| p.get("lowLatencyDrawing")).and_then(Value::as_bool).unwrap_or(default)
}
/// Read the policy leniently at startup, including old settings without renderingMode.
pub fn read_rendering_prefs(path: Option<&Path>) -> (GpuBackend, RenderingMode) {
let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
let perf = v.get("performance");
let backend = perf.and_then(|p| p.get("gpuBackend")).and_then(Value::as_str).and_then(GpuBackend::parse).unwrap_or_default();
let use_gpu = perf.and_then(|p| p.get("useGpu")).and_then(Value::as_bool).unwrap_or(true);
let explicit = perf.and_then(|p| p.get("renderingMode")).and_then(Value::as_str).and_then(RenderingMode::parse);
let mode = explicit.unwrap_or(if !use_gpu || backend == GpuBackend::Cpu { RenderingMode::Cpu } else { RenderingMode::Auto });
(backend, mode)
/// Preferences › Performance › Graphics Adapter, read before the window opens; empty (automatic)
/// when none is chosen.
pub fn gpu_adapter(performance: &photocraft_engine::prefs::Performance) -> String {
performance.gpu_adapter.chars().take(256).collect()
}
#[cfg(test)]
+29 -38
View File
@@ -5,43 +5,45 @@ fn crashed(backend: &str, adapter_backend: &str) -> Marker {
Marker { backend: backend.into(), adapter: "Intel(R) UHD Graphics".into(), adapter_backend: adapter_backend.into(), ..Default::default() }
}
/// Writes `json` as the settings folder `dir`'s older preferences file (no `config.toml`), and
/// returns Performance as the launch reads it (`services::saved_prefs`).
fn launch_performance(dir: &Path, json: &str) -> photocraft_engine::prefs::Performance {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join(photocraft_engine::prefs::LEGACY_PREFS_FILE), json).unwrap();
photocraft_engine::prefs::read_saved(Some(dir)).prefs.performance
}
/// Performance without a settings folder.
fn default_performance() -> photocraft_engine::prefs::Performance {
photocraft_engine::prefs::read_saved(None).prefs.performance
}
#[test]
fn low_latency_drawing_is_read_before_the_window_opens_and_defaults_off() {
let dir = std::env::temp_dir().join(format!("photocraft-low-latency-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("preferences.json");
let read = |json: &str| {
std::fs::write(&file, json).unwrap();
read_low_latency(Some(&file))
};
let dir = temp_dir("low-latency");
let read = |json: &str| launch_performance(&dir, json).low_latency_drawing;
assert!(read(r#"{"performance":{"lowLatencyDrawing":true}}"#));
assert!(!read(r#"{"performance":{"lowLatencyDrawing":false}}"#));
assert!(!read(r#"{"performance":{"lowLatencyDrawing":"nope"}}"#), "garbage keeps the default (off)");
assert!(!read("not json"));
assert!(!read_low_latency(None), "no settings file: the default (off)");
assert!(!default_performance().low_latency_drawing, "no settings folder: the default (off)");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn display_server_preference_is_read_before_the_window_opens() {
use photocraft_engine::prefs::LinuxDisplayServer;
let dir = std::env::temp_dir().join(format!("photocraft-display-server-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("preferences.json");
let read = |json: &str| {
std::fs::write(&file, json).unwrap();
read_display_server(Some(&file))
};
let dir = temp_dir("display-server");
let read = |json: &str| launch_performance(&dir, json).linux_display_server;
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11"}}"#), LinuxDisplayServer::X11);
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"auto","gpuBackend":"vulkan"}}"#), LinuxDisplayServer::Auto);
// Unknown values, other types, broken JSON and a missing file all start as Auto.
// Unknown values, other types, broken JSON and no settings folder all start as Auto.
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto);
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto);
// A bad value beside it resets only itself, as when the app loads the file (#6611).
assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11","cacheLevels":"four"}}"#), LinuxDisplayServer::X11);
assert_eq!(read("{not json"), LinuxDisplayServer::Auto);
assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto);
assert_eq!(read_display_server(None), LinuxDisplayServer::Auto);
assert_eq!(default_performance().linux_display_server, LinuxDisplayServer::Auto);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -203,20 +205,15 @@ fn adapter_names_match_loosely_and_the_environment_wins() {
#[test]
fn gpu_adapter_is_read_before_the_window_opens() {
let dir = std::env::temp_dir().join(format!("photocraft-gpu-adapter-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("preferences.json");
let read = |json: &str| {
std::fs::write(&file, json).unwrap();
read_gpu_adapter(Some(&file))
};
let dir = temp_dir("gpu-adapter");
let read = |json: &str| gpu_adapter(&launch_performance(&dir, json));
assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia"}}"#), "nvidia");
assert_eq!(read(r#"{"performance":{"gpuAdapter":7}}"#), "");
// A bad value beside it resets only itself, as when the app loads the file (#6611).
assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia","cacheLevels":"four"}}"#), "nvidia");
assert_eq!(read(r#"{"performance":{}}"#), "");
assert_eq!(read("not json"), "");
assert_eq!(read_gpu_adapter(None), "");
assert_eq!(gpu_adapter(&default_performance()), "");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -527,18 +524,12 @@ fn unwritable_config_dir_is_not_fatal() {
#[test]
fn prefs_are_read_leniently() {
let dir = temp_dir("prefs");
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join("preferences.json");
assert_eq!(read_rendering_prefs(None), (Auto, RenderingMode::Auto));
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
std::fs::write(&p, r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#).unwrap();
assert_eq!(read_rendering_prefs(Some(&p)), (Dx12, RenderingMode::Cpu));
std::fs::write(&p, r#"{"performance": {"gpuBackend": "quantum"}}"#).unwrap();
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
std::fs::write(&p, r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#).unwrap();
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Gpu));
std::fs::write(&p, "{not json").unwrap();
assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto));
let read = |json: &str| rendering_prefs(&launch_performance(&dir, json));
assert_eq!(rendering_prefs(&default_performance()), (Auto, RenderingMode::Auto));
assert_eq!(read(r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#), (Dx12, RenderingMode::Cpu));
assert_eq!(read(r#"{"performance": {"gpuBackend": "quantum"}}"#), (Auto, RenderingMode::Auto));
assert_eq!(read(r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#), (Auto, RenderingMode::Gpu));
assert_eq!(read("{not json"), (Auto, RenderingMode::Auto));
let _ = std::fs::remove_dir_all(&dir);
}
-364
View File
@@ -1,364 +0,0 @@
//! Linux: icons from the desktop's freedesktop icon theme (the Icon Theme Specification), for the
//! caption buttons' glyphs (`caption_style.rs`). A theme is searched, then the themes it inherits,
//! then `hicolor`; within each, its directories from the best fit for a 16 px icon down. Only SVG
//! files are used: symbolic icons are drawn as a coverage mask in the button's ink colour.
use std::path::{Path, PathBuf};
/// Bounds on what a theme's files can make us do: themes in an inheritance chain, directories a
/// theme lists, and the bytes read from one file.
const MAX_THEMES: usize = 32;
const MAX_DIRS: usize = 4096;
/// How deep an index's unlisted directories are looked for (`symbolic/ui`, `16x16@2/actions`).
const SCAN_DEPTH: usize = 3;
const MAX_FILE: u64 = 1 << 20;
/// The size the caption glyphs are drawn at, in the spec's units.
const ICON_SIZE: i64 = 16;
/// A theme or icon name that stays inside its directory.
pub fn valid_name(name: &str) -> bool {
!name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\', '\0'])
}
/// At most [`MAX_FILE`] bytes of a file (settings, theme indexes and icons are small).
pub fn read_small(path: &Path) -> Option<Vec<u8>> {
use std::io::Read;
let mut bytes = vec![];
std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_end(&mut bytes).ok()?;
Some(bytes)
}
/// Where themes live, in the spec's order: `~/.icons`, `$XDG_DATA_HOME/icons`, then each
/// `$XDG_DATA_DIRS/icons`. Relative paths in the variables are ignored, as the XDG spec says.
pub fn base_dirs(var: &dyn Fn(&str) -> Option<String>) -> Vec<PathBuf> {
let absolute = |p: &String| Path::new(p).is_absolute();
let home = var("HOME").filter(absolute).map(PathBuf::from);
let mut dirs = vec![];
if let Some(home) = &home {
dirs.push(home.join(".icons"));
}
if let Some(data) = var("XDG_DATA_HOME").filter(absolute).map(PathBuf::from).or_else(|| home.map(|h| h.join(".local").join("share"))) {
dirs.push(data.join("icons"));
}
let data_dirs = var("XDG_DATA_DIRS").filter(|d| !d.trim().is_empty()).unwrap_or_else(|| "/usr/local/share:/usr/share".into());
dirs.extend(data_dirs.split(':').filter(|d| Path::new(d).is_absolute()).map(|d| Path::new(d).join("icons")));
dirs
}
/// Every `[section]` of an `index.theme` as (key, value) pairs, in one pass; the first section
/// of a name wins. (Looking each directory's section up by rescanning the file multiplied its
/// size by the number of directories.)
fn sections(index: &str) -> std::collections::HashMap<&str, Vec<(&str, &str)>> {
let mut all = std::collections::HashMap::new();
let mut current: Option<Vec<(&str, &str)>> = None;
let mut name = "";
for line in index.lines().map(str::trim) {
if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
if let Some(done) = current.take() {
all.entry(name).or_insert(done);
}
name = s;
current = Some(vec![]);
} else if let (Some(pairs), Some((k, v))) = (current.as_mut(), line.split_once('=')) {
pairs.push((k.trim(), v.trim()));
}
}
if let Some(done) = current {
all.entry(name).or_insert(done);
}
all
}
fn list(value: Option<&str>) -> impl Iterator<Item = &str> {
value.unwrap_or_default().split(',').map(str::trim).filter(|s| !s.is_empty())
}
/// How far a theme directory is from a 16 px icon at scale 1 (the spec's
/// `DirectorySizeDistance`), then its scale: 0 is an exact fit.
fn distance(keys: &[(&str, &str)]) -> (i64, i64) {
let get = |k: &str| keys.iter().find(|(key, _)| *key == k).map(|(_, v)| *v);
let num = |k: &str, default: i64| get(k).and_then(|v| v.parse::<i64>().ok()).unwrap_or(default).clamp(0, 1 << 16);
let size = num("Size", 0);
let scale = num("Scale", 1).max(1);
let d = match get("Type").unwrap_or("Threshold") {
"Fixed" => (size * scale - ICON_SIZE).abs(),
"Scalable" => {
let (min, max) = (num("MinSize", size) * scale, num("MaxSize", size) * scale);
(min - ICON_SIZE).max(ICON_SIZE - max).max(0)
}
_ => ((size * scale - ICON_SIZE).abs() - num("Threshold", 2) * scale).max(0),
};
(d, scale)
}
/// Every directory under `root`, at most [`SCAN_DEPTH`] levels down and [`MAX_DIRS`] in all, in
/// path order: scalable and symbolic ones first, as icons there fit any size.
fn subdirectories(root: &Path) -> Vec<PathBuf> {
let mut found = vec![];
let mut level = vec![root.to_path_buf()];
for _ in 0..SCAN_DEPTH {
let mut next = vec![];
for dir in &level {
let Ok(entries) = std::fs::read_dir(dir) else { continue };
for entry in entries.flatten().take(MAX_DIRS) {
let path = entry.path();
if found.len() + next.len() < MAX_DIRS && path.is_dir() {
next.push(path);
}
}
}
found.extend(next.iter().cloned());
level = next;
}
let vector = |p: &PathBuf| !p.components().any(|c| matches!(c.as_os_str().to_str(), Some("scalable" | "symbolic")));
found.sort_by_key(|p| (vector(p), p.clone()));
found
}
/// One theme of a chain: its listed directories, best fit first, in every base directory that has
/// the theme, and (looked for only when an icon isn't in those) the directories its index forgot.
struct Theme {
roots: Vec<PathBuf>,
listed: Vec<PathBuf>,
unlisted: std::cell::OnceCell<Vec<PathBuf>>,
}
impl Theme {
/// The directories the index forgot to list: GTK still finds icons there, and custom themes
/// often add `symbolic/ui` without listing it.
fn unlisted(&self) -> &[PathBuf] {
self.unlisted.get_or_init(|| {
let listed: std::collections::HashSet<&PathBuf> = self.listed.iter().collect();
self.roots.iter().flat_map(|r| subdirectories(r)).filter(|d| !listed.contains(d)).collect()
})
}
}
/// A theme and the themes it inherits, in search order.
pub struct IconTheme {
themes: Vec<Theme>,
}
impl IconTheme {
/// `name` and the themes it inherits, then `hicolor`. `None` when no theme in the chain has an
/// `index.theme`.
pub fn load(name: &str, bases: &[PathBuf]) -> Option<Self> {
let mut chain: Vec<String> = vec![name.to_string()];
let mut themes = vec![];
let mut i = 0;
loop {
let Some(theme) = chain.get(i).cloned() else {
// Every chain ends in hicolor, whether or not the themes before it exist.
if chain.iter().any(|t| t == "hicolor") {
break;
}
chain.push("hicolor".into());
continue;
};
i += 1;
if !valid_name(&theme) {
continue;
}
let roots: Vec<PathBuf> = bases.iter().map(|b| b.join(&theme)).filter(|r| r.is_dir()).collect();
// The first index wins; a theme can still be spread over several base directories.
let Some(index) = roots.iter().find_map(|r| read_small(&r.join("index.theme"))) else { continue };
let index = String::from_utf8_lossy(&index);
let all = sections(&index);
let head = all.get("Icon Theme").map_or(&[][..], Vec::as_slice);
let get = |k: &str| head.iter().find(|(key, _)| *key == k).map(|(_, v)| *v);
let mut subdirs: Vec<((i64, i64), &str)> = list(get("Directories"))
.chain(list(get("ScaledDirectories")))
.filter(|d| !d.split('/').any(|part| part == ".." || part.is_empty()))
.take(MAX_DIRS)
.map(|d| (distance(all.get(d).map_or(&[][..], Vec::as_slice)), d))
.collect();
subdirs.sort_by_key(|(key, _)| *key);
// Not checked for existence: a theme lists hundreds, and the search stops at a hit.
let listed = subdirs.iter().flat_map(|(_, sub)| roots.iter().map(move |r| r.join(sub))).collect();
for parent in list(get("Inherits")) {
if chain.len() < MAX_THEMES && !chain.iter().any(|t| t == parent) {
chain.push(parent.to_string());
}
}
themes.push(Theme { roots, listed, unlisted: std::cell::OnceCell::new() });
}
(!themes.is_empty()).then_some(Self { themes })
}
/// The first `<icon>.svg` in search order: each theme's listed directories, then its unlisted
/// ones, before its parent.
pub fn find_svg(&self, icon: &str) -> Option<PathBuf> {
if !valid_name(icon) {
return None;
}
let file = format!("{icon}.svg");
let hit = |dirs: &[PathBuf]| dirs.iter().map(|d| d.join(&file)).find(|p| p.is_file());
self.themes.iter().find_map(|t| hit(&t.listed).or_else(|| hit(t.unlisted())))
}
}
/// An SVG's coverage (alpha) as a `px` × `px` mask, the drawing fitted and centred. `None` for an
/// unreadable SVG or an absurd size.
pub fn rasterize_mask(svg: &[u8], px: u32) -> Option<Vec<u8>> {
use craft_svg::tree::{draw, draw::tiny_skia, usvg};
// usvg inflates gzip (`.svgz`) input without a decoded-size limit, and icons are plain `.svg`.
if !(1..=256).contains(&px) || svg.starts_with(&[0x1f, 0x8b]) {
return None;
}
// Glyphs are paths: no `<image>` is loaded, so an icon can't make us read another file
// (`/dev/zero`, a huge picture) or nest an SVG.
let opts = usvg::Options {
image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) },
..usvg::Options::default()
};
// usvg and resvg panic on some malformed drawings: such an icon is unreadable, not a crash.
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let tree = usvg::Tree::from_data(svg, &opts).ok()?;
let size = tree.size();
let side = size.width().max(size.height());
if !side.is_finite() || side <= 0.0 {
return None;
}
let s = px as f32 / side;
let (dx, dy) = ((px as f32 - size.width() * s) / 2.0, (px as f32 - size.height() * s) / 2.0);
let pixmap = draw::render(&tree, tiny_skia::Transform::from_scale(s, s).post_translate(dx, dy), px, px, 0, 64 * 1024 * 1024).ok()?;
Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect())
}))
.ok()
.flatten()
}
#[cfg(test)]
mod tests {
use super::*;
/// A throwaway icon tree: `files` are (path under the base, contents).
fn tree(tag: &str, files: &[(&str, &str)]) -> PathBuf {
let base = std::env::temp_dir().join(format!("photocraft-icons-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
for (path, text) in files {
let p = base.join(path);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
base
}
const SQUARE: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M4 4h8v8H4z" fill="#2e3436"/></svg>"##;
#[test]
fn icons_come_from_the_theme_then_its_parents_then_hicolor_best_size_first() {
let base = tree(
"chain",
&[
("Child/index.theme", "[Icon Theme]\nInherits=Parent, Child\nDirectories=48,16\n[48]\nSize=48\nType=Fixed\n[16]\nSize=16\nType=Fixed\n"),
("Child/48/a-symbolic.svg", "big"),
// Not in the index: still found, and before the parent's copy.
("Child/symbolic/ui/d-symbolic.svg", SQUARE),
("Parent/ui/d-symbolic.svg", SQUARE),
("Child/16/a-symbolic.svg", SQUARE),
("Parent/index.theme", "[Icon Theme]\nDirectories=ui\n[ui]\nSize=16\nMinSize=8\nMaxSize=512\nType=Scalable\n"),
("Parent/ui/b-symbolic.svg", SQUARE),
("hicolor/index.theme", "[Icon Theme]\nDirectories=s\n[s]\nSize=16\nType=Scalable\n"),
("hicolor/s/c-symbolic.svg", SQUARE),
],
);
let theme = IconTheme::load("Child", std::slice::from_ref(&base)).expect("the theme loads");
assert_eq!(theme.find_svg("a-symbolic"), Some(base.join("Child/16/a-symbolic.svg")), "16 px before 48 px");
assert_eq!(theme.find_svg("b-symbolic"), Some(base.join("Parent/ui/b-symbolic.svg")));
assert_eq!(theme.find_svg("c-symbolic"), Some(base.join("hicolor/s/c-symbolic.svg")));
assert_eq!(theme.find_svg("d-symbolic"), Some(base.join("Child/symbolic/ui/d-symbolic.svg")), "unlisted, but the theme's own");
assert_eq!(theme.find_svg("missing"), None);
assert_eq!(theme.find_svg("../Parent/ui/b-symbolic"), None);
assert!(IconTheme::load("Nowhere", std::slice::from_ref(&base)).is_some(), "hicolor still answers");
assert!(IconTheme::load("Nowhere", &[base.join("empty")]).is_none());
let _ = std::fs::remove_dir_all(base);
}
/// Hostile theme files: cycles, escapes and junk sizes end the search, never hang or panic.
#[test]
fn cyclic_or_hostile_indexes_are_harmless() {
let base = tree(
"hostile",
&[
(
"A/index.theme",
"[Icon Theme]\nInherits=B,../etc,\nDirectories=../../x,,/abs,ok\n[ok]\nSize=99999999999999999999\nScale=-3\nType=Threshold\n",
),
("A/ok/x.svg", SQUARE),
("B/index.theme", "[Icon Theme]\nInherits=A\n"),
],
);
let theme = IconTheme::load("A", std::slice::from_ref(&base)).expect("loads");
assert_eq!(theme.find_svg("x"), Some(base.join("A/ok/x.svg")));
assert!(IconTheme::load("..", std::slice::from_ref(&base)).is_none());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn sections_are_read_once_and_the_first_of_a_name_wins() {
let all = sections("stray=1\n[A]\nSize=16\n[B]\nSize=22\n[A]\nSize=48\n");
assert_eq!(all["A"], vec![("Size", "16")]);
assert_eq!(all["B"], vec![("Size", "22")]);
assert!(!all.contains_key(""));
}
#[test]
fn a_gzip_icon_is_refused() {
assert_eq!(rasterize_mask(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0], 16), None);
}
#[test]
fn distance_follows_the_spec() {
assert_eq!(distance(&[("Size", "16"), ("Type", "Fixed")]), (0, 1));
assert_eq!(distance(&[("Size", "22"), ("Type", "Fixed")]), (6, 1));
assert_eq!(distance(&[("Size", "16"), ("Scale", "2"), ("Type", "Fixed")]), (16, 2));
assert_eq!(distance(&[("Size", "32"), ("MinSize", "8"), ("MaxSize", "512"), ("Type", "Scalable")]), (0, 1));
assert_eq!(distance(&[("Size", "48"), ("Type", "Scalable")]), (32, 1));
assert_eq!(distance(&[("Size", "18")]), (0, 1), "Threshold 2 by default");
}
#[test]
fn masks_are_square_coverage() {
let mask = rasterize_mask(SQUARE.as_bytes(), 32).expect("renders");
assert_eq!(mask.len(), 32 * 32);
assert_eq!(mask[16 * 32 + 16], 255, "inside the square");
assert_eq!(mask[0], 0, "outside it");
assert!(rasterize_mask(b"not svg", 16).is_none());
assert!(rasterize_mask(SQUARE.as_bytes(), 0).is_none());
assert!(rasterize_mask(SQUARE.as_bytes(), 100_000).is_none());
}
/// resvg panics rendering an offset past the pixmap's size: the icon is unreadable instead.
#[test]
fn a_mask_the_renderer_panics_on_is_none() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">
<filter id="f"><feOffset dx="3e9" dy="-3e9"/></filter><rect width="16" height="16" filter="url(#f)"/>
</svg>"##;
assert!(rasterize_mask(svg.as_bytes(), 16).is_none());
}
/// An icon's `<image>` is never loaded: not a device file, not an embedded picture.
#[test]
fn masks_load_no_images() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16">
<image href="/dev/zero" width="16" height="16"/>
<image xlink:href="data:image/svg+xml;utf8,&lt;svg xmlns='http://www.w3.org/2000/svg' width='16' height='16'&gt;&lt;rect width='16' height='16'/&gt;&lt;/svg&gt;" width="16" height="16"/>
</svg>"##;
let mask = rasterize_mask(svg.as_bytes(), 16).expect("renders");
assert!(mask.iter().all(|a| *a == 0), "nothing drawn");
}
#[test]
fn base_dirs_follow_xdg() {
let var = |k: &str| match k {
"HOME" => Some("/home/u".to_string()),
"XDG_DATA_DIRS" => Some("/a:rel:/b".to_string()),
_ => None,
};
let dirs = base_dirs(&var);
let want: Vec<PathBuf> = ["/home/u/.icons", "/home/u/.local/share/icons", "/a/icons", "/b/icons"].iter().map(PathBuf::from).collect();
assert_eq!(dirs, want);
assert_eq!(base_dirs(&|_| None), vec![PathBuf::from("/usr/local/share/icons"), PathBuf::from("/usr/share/icons")]);
}
}
-6
View File
@@ -265,12 +265,6 @@ fn system_probe() -> Probe {
Probe { ldconfig: read_ldconfig(), dirs: search_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref()) }
}
/// Whether the linker cache lists `soname`; `None` when the cache can't be read, which proves
/// nothing (musl, NixOS, some containers).
pub fn cached(soname: &str) -> Option<bool> {
read_ldconfig().map(|text| ldconfig_has(&text, soname, ldconfig_arch_tag()))
}
/// Are all the libraries `session` needs found on this system? (For choosing a display server:
/// libraries the check can't find count as missing.)
pub fn available(session: DisplaySession) -> bool {
-396
View File
@@ -1,396 +0,0 @@
//! The macOS menu bar, through muda (a standalone native menu crate, not Tauri: no webview, just
//! AppKit menus behind a safe API, no GTK on macOS). The menus themselves, their Mac layout and how their keys reach PhotoCraft are in
//! `photocraft_ui_egui::native_menu`; this file only builds and updates the `NSMenu`s.
//!
//! - Item ids are command ids; a command in two menus (Keyboard Shortcuts is in Edit and Window)
//! gets `id#2` for its second copy, as muda ids must be unique.
//! - A structure change (a new Open Recent file, a language switch) rebuilds the menu; anything
//! else (labels, enabled, checked) is updated in place. Opening or closing a document rebuilds
//! only the Window menu, whose list of documents changed: AppKit adds its own items to that
//! menu (window tiling, the window list), so muda can't insert rows there by position.
//! - A chosen item is a click or a key equivalent: AppKit's current event says which. Key
//! equivalents go back to egui as the key press that was made (the event's modifiers, not the
//! item's: AppKit may match ⌘R to a ⇧⌘R item), so PhotoCraft's key rules still apply.
//! - Hide is a custom item calling `NSApplication hide:`, as the predefined one always takes ⌘H.
use std::collections::{HashMap, HashSet};
use std::sync::mpsc::{Receiver, channel};
use muda::accelerator::{Accelerator, Code, Modifiers};
use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use objc2::MainThreadMarker;
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType};
use photocraft_ui_egui::native_menu::{self, Backend, Chord, Event, MenuBar, MenuRole, Node, Standard};
enum Handle {
Plain(MenuItem),
Check(CheckMenuItem),
}
/// One native item.
struct Entry {
handle: Handle,
/// The command id (several entries can share one).
command: String,
chord: Option<Chord>,
label: String,
enabled: bool,
}
/// How an item was chosen, read from AppKit's current event while it calls the handler.
struct Chosen {
id: String,
/// A key press (not a mouse click), and the modifiers held: ⌘, ⌃, ⌥, ⇧.
key: bool,
mods: [bool; 4],
}
pub struct MacMenu {
menu: Option<Menu>,
/// By muda id.
entries: HashMap<String, Entry>,
rx: Receiver<Chosen>,
structure: u64,
/// The Window menu, the muda ids of its items, and its [`native_menu::window_key`].
window: Option<(Submenu, Vec<String>, u64)>,
}
impl MacMenu {
pub fn new(ctx: &egui::Context) -> MacMenu {
let (tx, rx) = channel();
let repaint = ctx.clone();
MenuEvent::set_event_handler(Some(move |e: MenuEvent| {
// AppKit calls this on the main thread, from the event that chose the item: a key
// equivalent is a key-down, a click a mouse-up (or ↩ inside the open menu).
let event = MainThreadMarker::new().and_then(|mtm| NSApplication::sharedApplication(mtm).currentEvent());
let key = event.as_ref().is_some_and(|ev| ev.r#type() == NSEventType::KeyDown);
let flags = event.as_ref().map(|ev| ev.modifierFlags()).unwrap_or(NSEventModifierFlags::empty());
let mods = [NSEventModifierFlags::Command, NSEventModifierFlags::Control, NSEventModifierFlags::Option, NSEventModifierFlags::Shift]
.map(|m| flags.contains(m));
let _ = tx.send(Chosen { id: e.id.0, key, mods });
// Wake egui, so the item runs now rather than on the next mouse move.
repaint.request_repaint();
}));
MacMenu { menu: None, entries: HashMap::new(), rx, structure: 0, window: None }
}
fn build(&mut self, bar: &MenuBar) {
if let Some(old) = self.menu.take() {
old.remove_for_nsapp();
}
self.entries.clear();
self.window = None;
let menu = Menu::new();
let mut special = Vec::new();
for m in &bar.menus {
let (sub, ids) = self.submenu(m);
let _ = menu.append(&sub);
if m.role == MenuRole::Window {
self.window = Some((sub.clone(), ids, native_menu::window_key(bar)));
}
if matches!(m.role, MenuRole::Window | MenuRole::Help) {
special.push((m.role, sub));
}
}
menu.init_for_nsapp();
// Only once the menu is NSApp's: muda looks the submenus up in the installed main menu.
for (role, sub) in special {
match role {
MenuRole::Window => sub.set_as_windows_menu_for_nsapp(),
_ => sub.set_as_help_menu_for_nsapp(),
}
}
self.menu = Some(menu);
self.structure = native_menu::structure_key(bar);
}
/// A top-level menu, and the muda ids of the items it added.
fn submenu(&mut self, m: &native_menu::Menu) -> (Submenu, Vec<String>) {
let before: HashSet<String> = self.entries.keys().cloned().collect();
let sub = Submenu::new(escape(&m.title), true);
self.append(&sub, &m.children);
let ids = self.entries.keys().filter(|id| !before.contains(*id)).cloned().collect();
(sub, ids)
}
/// Replace the Window menu (a document opened or closed), leaving the other menus as they are.
fn rebuild_window(&mut self, bar: &MenuBar) {
let (Some(menu), Some((old, ids, _))) = (self.menu.clone(), self.window.take()) else { return self.build(bar) };
let Some((at, spec)) = bar.menus.iter().enumerate().find(|(_, m)| m.role == MenuRole::Window) else { return self.build(bar) };
if menu.remove(&old).is_err() {
return self.build(bar);
}
for id in ids {
self.entries.remove(&id);
}
let (sub, ids) = self.submenu(spec);
if menu.insert(&sub, at).is_err() {
return self.build(bar);
}
sub.set_as_windows_menu_for_nsapp();
self.window = Some((sub, ids, native_menu::window_key(bar)));
}
fn append(&mut self, sub: &Submenu, nodes: &[Node]) {
for n in nodes {
match n {
Node::Separator => {
let _ = sub.append(&PredefinedMenuItem::separator());
}
Node::Submenu { label, children, .. } => {
let s = Submenu::new(escape(label), !children.is_empty());
self.append(&s, children);
let _ = sub.append(&s);
}
Node::Standard(item) => {
let p = match item {
Standard::Services => PredefinedMenuItem::services(Some(photocraft_ui_egui::i18n::t("Services"))),
Standard::HideOthers => PredefinedMenuItem::hide_others(Some(photocraft_ui_egui::i18n::t("Hide Others"))),
Standard::ShowAll => PredefinedMenuItem::show_all(Some(photocraft_ui_egui::i18n::t("Show All"))),
Standard::Minimize => PredefinedMenuItem::minimize(None),
Standard::Zoom => PredefinedMenuItem::maximize(Some(photocraft_ui_egui::i18n::t("Zoom"))),
Standard::BringAllToFront => PredefinedMenuItem::bring_all_to_front(None),
Standard::CloseWindow => PredefinedMenuItem::close_window(None),
};
let _ = sub.append(&p);
}
Node::Item(it) => {
let id = self.unique_id(&it.id);
let chord = it.shortcut.as_deref().and_then(Chord::parse);
let accel = chord.as_ref().filter(|c| c.native_ok()).and_then(accelerator);
let handle = match it.checked {
Some(c) => {
let h = CheckMenuItem::with_id(id.clone(), escape(&it.label), it.enabled, c, accel);
let _ = sub.append(&h);
Handle::Check(h)
}
None => {
let h = MenuItem::with_id(id.clone(), escape(&it.label), it.enabled, accel);
let _ = sub.append(&h);
Handle::Plain(h)
}
};
self.entries.insert(id, Entry { handle, command: it.id.clone(), chord, label: it.label.clone(), enabled: it.enabled });
}
}
}
}
/// muda ids must be unique: the second `edit.keyboardShortcuts` becomes `…#2`.
fn unique_id(&self, id: &str) -> String {
let mut unique = id.to_string();
let mut n = 2;
while self.entries.contains_key(&unique) {
unique = format!("{id}#{n}");
n += 1;
}
unique
}
}
impl Backend for MacMenu {
fn sync(&mut self, bar: &MenuBar) {
if self.menu.is_none() || native_menu::structure_key(bar) != self.structure {
self.build(bar);
return;
}
if self.window.as_ref().map(|w| w.2) != Some(native_menu::window_key(bar)) {
self.rebuild_window(bar);
}
let items: HashMap<&str, &native_menu::Item> = bar.items().into_iter().map(|it| (it.id.as_str(), it)).collect();
for e in self.entries.values_mut() {
let Some(it) = items.get(e.command.as_str()) else { continue };
if e.label != it.label {
let text = escape(&it.label);
match &e.handle {
Handle::Plain(h) => h.set_text(text),
Handle::Check(h) => h.set_text(text),
}
e.label = it.label.clone();
}
if e.enabled != it.enabled {
match &e.handle {
Handle::Plain(h) => h.set_enabled(it.enabled),
Handle::Check(h) => h.set_enabled(it.enabled),
}
e.enabled = it.enabled;
}
// Compare with AppKit's own state: muda toggles a check item when it's clicked.
if let (Handle::Check(h), Some(c)) = (&e.handle, it.checked)
&& h.is_checked() != c
{
h.set_checked(c);
}
}
}
fn drain(&mut self) -> Vec<Event> {
let mut out = Vec::new();
while let Ok(chosen) = self.rx.try_recv() {
// Ids that aren't ours are AppKit's own items (Services, Zoom, …), already handled.
let Some(e) = self.entries.get(&chosen.id) else { continue };
if e.command == native_menu::HIDE {
if let Some(mtm) = MainThreadMarker::new() {
NSApplication::sharedApplication(mtm).hide(None);
}
continue;
}
// A key-down chose it: its key equivalent, unless it was ↩ or Space inside the open
// menu (no ⌘ or ⌃, and the item's shortcut needs one). The key is the item's (AppKit
// matched on it); the modifiers are the ones held.
let [cmd, ctrl, alt, shift] = chosen.mods;
let key =
e.chord.as_ref().filter(|c| chosen.key && (cmd || ctrl || !(c.cmd || c.ctrl))).map(|c| Chord { cmd, ctrl, alt, shift, key: c.key.clone() });
out.push(match key {
Some(chord) if e.command != native_menu::MINIMIZE => Event::Key(chord),
_ => Event::Click(e.command.clone()),
});
}
out
}
}
/// Install the menu bar now (in eframe's creator closure, so winit's default menu doesn't stay).
pub fn install(ctx: &egui::Context, app: &photocraft_ui_egui::PhotocraftApp) -> Option<native_menu::NativeMenu> {
let language = &app.session.prefs().interface.language;
let lang = photocraft_ui_egui::i18n::Lang::from_pref(language);
let bar = native_menu::app_layout(app, &photocraft_ui_egui::menus::menu_items(app), lang, language).bar;
// Never crash for a menu: if AppKit refuses, keep the in-window menus.
let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut menu = MacMenu::new(ctx);
menu.sync(&bar);
menu
}));
match built {
Ok(menu) => Some(native_menu::NativeMenu::new(Box::new(menu))),
Err(_) => {
log::warn!("couldn't install the macOS menu bar; using the in-window menus");
None
}
}
}
/// `&` marks a mnemonic in muda labels.
fn escape(s: &str) -> String {
s.replace('&', "&&")
}
/// A key equivalent for AppKit. `Cmd` is ⌘ (`META`) and `Ctrl` is ⌃: never folded together.
fn accelerator(c: &Chord) -> Option<Accelerator> {
let mut mods = Modifiers::empty();
for (on, m) in [(c.cmd, Modifiers::META), (c.ctrl, Modifiers::CONTROL), (c.alt, Modifiers::ALT), (c.shift, Modifiers::SHIFT)] {
if on {
mods |= m;
}
}
const LETTERS: [Code; 26] = [
Code::KeyA,
Code::KeyB,
Code::KeyC,
Code::KeyD,
Code::KeyE,
Code::KeyF,
Code::KeyG,
Code::KeyH,
Code::KeyI,
Code::KeyJ,
Code::KeyK,
Code::KeyL,
Code::KeyM,
Code::KeyN,
Code::KeyO,
Code::KeyP,
Code::KeyQ,
Code::KeyR,
Code::KeyS,
Code::KeyT,
Code::KeyU,
Code::KeyV,
Code::KeyW,
Code::KeyX,
Code::KeyY,
Code::KeyZ,
];
const DIGITS: [Code; 10] =
[Code::Digit0, Code::Digit1, Code::Digit2, Code::Digit3, Code::Digit4, Code::Digit5, Code::Digit6, Code::Digit7, Code::Digit8, Code::Digit9];
const F: [Code; 24] = [
Code::F1,
Code::F2,
Code::F3,
Code::F4,
Code::F5,
Code::F6,
Code::F7,
Code::F8,
Code::F9,
Code::F10,
Code::F11,
Code::F12,
Code::F13,
Code::F14,
Code::F15,
Code::F16,
Code::F17,
Code::F18,
Code::F19,
Code::F20,
Code::F21,
Code::F22,
Code::F23,
Code::F24,
];
let k = c.key.as_str();
let mut chars = k.chars();
let code = match (chars.next(), chars.next()) {
(Some(ch), None) if ch.is_ascii_alphabetic() => *LETTERS.get((ch.to_ascii_uppercase() as usize).checked_sub('A' as usize)?)?,
(Some(ch), None) if ch.is_ascii_digit() => *DIGITS.get((ch as usize).checked_sub('0' as usize)?)?,
_ if c.is_function_key() => *F.get(k.get(1..)?.parse::<usize>().ok()?.checked_sub(1)?)?,
_ => match k {
"[" => Code::BracketLeft,
"]" => Code::BracketRight,
"\\" => Code::Backslash,
"/" => Code::Slash,
"=" => Code::Equal,
"-" => Code::Minus,
"'" => Code::Quote,
";" => Code::Semicolon,
"," => Code::Comma,
"." => Code::Period,
"`" => Code::Backquote,
"Delete" | "Backspace" => Code::Backspace,
"Enter" if !mods.is_empty() => Code::Enter,
"Tab" if !mods.is_empty() => Code::Tab,
"Space" if !mods.is_empty() => Code::Space,
_ => return None,
},
};
Some(Accelerator::new(mods, code))
}
#[cfg(test)]
mod tests {
use super::*;
/// Every shortcut the Mac menu shows becomes a key equivalent (or stays egui's, for bare keys).
#[test]
fn every_menu_shortcut_maps_to_a_key_equivalent() {
let app = photocraft_ui_egui::PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default());
let bar = native_menu::photocraft_layout(&photocraft_ui_egui::menus::menu_items(&app), photocraft_ui_egui::i18n::Lang::EN, "auto").bar;
let mut native = 0;
for it in bar.items() {
let Some(c) = it.shortcut.as_deref().and_then(Chord::parse) else { continue };
if c.native_ok() {
assert!(accelerator(&c).is_some(), "{} ({}) has no key equivalent", c.portable(), it.id);
native += 1;
}
}
assert!(native > 70, "{native} key equivalents");
}
#[test]
fn control_and_command_stay_distinct() {
let a = accelerator(&Chord::parse("Cmd+M").unwrap()).unwrap();
let b = accelerator(&Chord::parse("Ctrl+Cmd+M").unwrap()).unwrap();
assert_ne!(a, b);
}
}
+2 -19
View File
@@ -1,4 +1,4 @@
//! macOS window lifecycle: title bar dragging and quitting.
//! macOS window lifecycle: title bar dragging.
//!
//! Dragging: the window draws under a transparent title bar (`main.rs`), so AppKit would
//! otherwise drag the window from anywhere in that strip, menus included: pressing a menu title
@@ -7,7 +7,7 @@
//! `panels::title_bar`), which starts a drag explicitly (`ViewportCommand::StartDrag`, AppKit's
//! `performWindowDragWithEvent:`, which works on an unmovable window).
//!
//! Quitting: see [`terminate_later`]. All safe objc2 calls.
//! All safe objc2 calls. Quitting goes through the craft runtime's close path (`craft-quit`).
use objc2::MainThreadMarker;
use objc2_app_kit::NSApplication;
@@ -22,20 +22,3 @@ pub fn disable_native_title_drag() {
window.setMovable(false);
}
}
/// Quit the way a Mac app does, with `-[NSApplication terminate:]` (`Services::quit`), instead of
/// letting eframe close the window. eframe drops the window while AppKit's run loop is still
/// running, and on Macs with a Touch Bar AppKit's next display cycle then tries to stop observing
/// a view that is gone: an uncaught exception that crashes (macOS 27) or leaves a windowless app
/// that only Force Quit ends (macOS 26) (#1458, #1575). `terminate:` ends the process before
/// another display cycle runs; winit's `applicationWillTerminate:` closes the windows and has
/// eframe save the window layout first, as the old ⌘Q (winit's default menu) did.
///
/// Scheduled on the main queue: winit has to be out of its event handler, or eframe's exit
/// handling (and the save) is dropped.
pub fn terminate_later() {
dispatch2::DispatchQueue::main().exec_async(|| match MainThreadMarker::new() {
Some(mtm) => NSApplication::sharedApplication(mtm).terminate(None),
None => log::warn!("quit: the main queue ran off the main thread; not terminating"),
});
}
+150 -282
View File
@@ -17,7 +17,7 @@
//! crashes inside the driver also falls back by itself next time (see `gpu_startup`).
//!
//! `--in-window-menus` (or `PHOTOCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on
//! macOS instead of the macOS menu bar (`mac_menu`).
//! macOS instead of the macOS menu bar (`photocraft_ui_egui::native_menu`).
//!
//! `--control <port>` (or `PHOTOCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server.
//! The first line must authenticate; subsequent request lines get reply lines.
@@ -29,25 +29,16 @@
#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod agent_link;
mod app_dirs;
mod app_icon;
mod appearance;
#[cfg(target_os = "macos")]
mod apple_events;
mod caps_lock;
mod caption_style;
mod control_server;
mod crash_guard;
mod cursor;
mod file_dialog_probe;
mod gpu_startup;
#[cfg(target_os = "linux")]
mod icon_theme;
mod launch_args;
#[cfg(target_os = "macos")]
mod mac_menu;
#[cfg(target_os = "macos")]
mod mac_window;
// Pure logic is tested on every platform; only Linux runs the check.
#[cfg(not(target_arch = "wasm32"))]
@@ -57,14 +48,10 @@ mod linux_libs;
mod logging;
mod monitor_profile;
mod photoshop_settings;
// Save As through the desktop portal, which reports the file type picked (#6121).
#[cfg(target_os = "linux")]
mod portal_save;
mod presentation;
// The print portal needs the session bus (zbus, Linux only); its pure helpers are tested everywhere.
#[cfg(any(target_os = "linux", test))]
mod print_portal;
mod screen_color;
mod services;
// macOS gets one instance from LaunchServices (open-documents Apple events).
#[cfg(any(not(target_os = "macos"), test))]
@@ -73,44 +60,23 @@ mod startup_report;
// Tablet support (macOS AppKit monitor, Linux X11/Wayland, Windows barrel button).
mod tablet;
mod ui_state;
mod updates;
mod window_frame;
use photocraft_engine::Session;
use photocraft_ui_egui::PhotocraftApp;
use photocraft_ui_egui::Prefix;
use photocraft_ui_egui::window_policy::{self, Backend, Frame, TitleBarPref};
use photocraft_ui_egui::os_window::APP_ID;
/// Windows and Linux can use the app's title bar, with its own caption buttons and edge resizing
/// (`photocraft_ui_egui::titlebar`); the preference below selects the mode. macOS always keeps its
/// system traffic lights over the integrated title strip.
const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
/// The smallest the main window may be, in points.
const MIN_WINDOW_SIZE: [f32; 2] = [760.0, 480.0];
/// Whether this start draws its own title bar: Windows and Linux do, unless Preferences ›
/// Interface › System Title Bar asks for the system's (#1271, #1316). Read from the saved
/// preferences before the window opens; a missing or unreadable file keeps the default.
fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool {
let prefs: photocraft_engine::prefs::Preferences =
prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
CUSTOM_TITLEBAR && !prefs.interface.system_title_bar
}
/// Preferences › AI Integrations, read before the window opens the way [`custom_titlebar`] is:
/// whether agents may drive this launch at all, the port to listen on when no `--control`
/// was given (0 = only with `--control`) and the automation folders used when no
/// `--automation-read-root` / `--automation-write-root` was given. A missing or unreadable file
/// keeps the defaults.
///
/// The section is read on its own, and when it doesn't read as a whole each value on its own,
/// as the app's lenient load reads them (#6611): a wrong-typed value elsewhere in the file, or
/// in the other field, must not turn Allow Agent Control back on while the dialog shows it off.
fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::prefs::Integrations {
let file: Option<serde_json::Value> = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok());
file.as_ref()
.and_then(|v| v.get("integrations"))
.cloned()
.map(photocraft_engine::prefs::read_integrations_section)
.unwrap_or_else(|| photocraft_engine::prefs::Preferences::default().integrations)
/// Which title bar Preferences › Interface › System Title Bar asks for (#1271, #1316), from the
/// preferences read before the window opens (`services::saved_prefs`). The frame decision
/// (`window_policy::decide_for`) turns it into the frame the platform allows.
fn title_bar_pref(prefs: &photocraft_engine::prefs::Preferences) -> TitleBarPref {
if prefs.interface.system_title_bar { TitleBarPref::System } else { TitleBarPref::Integrated }
}
/// The automation roots: `--automation-read-root` / `--automation-write-root` (or their
@@ -123,14 +89,13 @@ fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::pref
/// and writing shares one capability, as it does when given by flags.
fn automation_workspace(
flags: &photocraft_automation::args::AutomationArgs,
prefs: &photocraft_engine::prefs::Integrations,
prefs: &craft::automation::agents::AgentSettings,
) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option<String>), photocraft_automation::AutomationError> {
use photocraft_automation::agent_link::folder;
let mut workspace = flags.workspace()?;
let mut warnings = Vec::new();
for read in [true, false] {
let given = if read { !flags.automation_read_root.is_empty() } else { flags.automation_write_root.is_some() };
let Some(root) = folder(if read { &prefs.read_root } else { &prefs.write_root }).filter(|_| !given) else {
let Some(root) = (if read { prefs.read_folder() } else { prefs.write_folder() }).filter(|_| !given) else {
continue;
};
let opened = if !root.is_absolute() {
@@ -152,11 +117,11 @@ fn automation_workspace(
}
/// The control port this launch listens on, and the warning to print when a request was refused.
/// Only `--control` (or `PHOTOCRAFT_CONTROL_PORT`) opens one at launch: Preferences › AI
/// Integrations' connection starts and stops while the app runs (`agent_link`). Allow Agent
/// Control off refuses the flag too, and says so rather than ignoring it silently.
/// Only `--control` (or `PHOTOCRAFT_CONTROL_PORT`) opens one at launch: the agent link starts and
/// stops its own while the app runs (`craft::automation::agents::AgentLink`). Allow Agent Control
/// off refuses the flag too, and says so rather than ignoring it silently.
fn control_port_for(cli: Option<u16>, prefs: &photocraft_engine::prefs::Integrations) -> (Option<u16>, Option<String>) {
if !prefs.allow_agent_control {
if !prefs.agents.allow_agent_control {
let warning = cli.map(|p| {
format!(
"photocraft: Preferences › AI Integrations › Allow Agent Control is off: not listening on port {p}
@@ -173,19 +138,12 @@ fn control_port_for(cli: Option<u16>, prefs: &photocraft_engine::prefs::Integrat
/// `centered`, Windows cascades each new window from the top-left corner, so it opened at a
/// different offset every launch (#419). A later launch restores the saved position instead
/// (`main` turns `centered` off, #4826). Wayland compositors place windows themselves.
fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
fn native_options(frame: &Frame) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default().with_icon(app_icon::viewport_icon(std::env::current_exe().ok().as_deref()));
let viewport =
viewport.with_app_id(APP_ID).with_title("PhotoCraft").with_inner_size([1440.0, 900.0]).with_min_inner_size(MIN_WINDOW_SIZE).with_drag_and_drop(true);
eframe::NativeOptions {
viewport: viewport
.with_app_id(APP_ID)
.with_title("PhotoCraft")
.with_inner_size([1440.0, 900.0])
.with_min_inner_size(photocraft_ui_egui::MIN_WINDOW_SIZE)
.with_drag_and_drop(true)
.with_decorations(!custom_titlebar)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false),
viewport: window_policy::apply(viewport, frame),
centered: true,
// PhotoCraft owns its fallback fonts (`cjk_fonts`, craft-fonts): eframe's system-font
// provider would compete with it and make glyph choice machine-dependent (#8512).
@@ -201,8 +159,8 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
/// The window eframe restores from `ui.ron`, corrected before it is created: at least the
/// minimum size, and never full screen. PhotoCraft always starts in Standard Screen Mode, but
/// eframe also saves and restores full screen, and a window closed in a full-screen mode is
/// saved full screen and maximized at once: the overlap `view_cmds::screen_mode_commands` keeps
/// apart at run time. [OBSERVED 2026-10-12, Windows 11] Restored that way, View › Screen Mode ›
/// saved full screen and maximized at once: the overlap the window's screen-mode sequence
/// (`AppShell`'s `ScreenModeFollow`) keeps apart at run time. [OBSERVED 2026-10-12, Windows 11] Restored that way, View › Screen Mode ›
/// Full Screen did nothing until `F` had cycled through Standard.
fn restored_window(builder: egui::ViewportBuilder) -> egui::ViewportBuilder {
at_least_min_size(builder).with_fullscreen(false)
@@ -285,13 +243,13 @@ fn claim_single_instance(
/// The display server to open the window on: Xwayland for a pen on Wayland, which gives this app
/// no pen input (#639). Exits with the package to install when its libraries are missing.
#[cfg(target_os = "linux")]
fn linux_display_session() -> linux_libs::DisplaySession {
fn linux_display_session(display_server: photocraft_engine::prefs::LinuxDisplayServer) -> linux_libs::DisplaySession {
let session = tablet::display_session();
// Preferences › Performance › Linux display server = X11: Xwayland on a Wayland session too,
// where native file drops work (winit 0.30 has none on Wayland, #386). Only when Xwayland can
// run the window ($DISPLAY set, X11 libraries installed); otherwise the session's own.
let session = if session == linux_libs::DisplaySession::Wayland
&& gpu_startup::read_display_server(services::prefs_file().as_deref()) == photocraft_engine::prefs::LinuxDisplayServer::X11
&& display_server == photocraft_engine::prefs::LinuxDisplayServer::X11
&& std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty())
&& linux_libs::available(linux_libs::DisplaySession::X11)
{
@@ -326,14 +284,16 @@ struct ControlNotice {
}
/// The `--control` server's port, token and workspace, when it is on (exits 2 on a bad
/// configuration). Preferences › AI Integrations' folders stand in for automation roots no flag
/// names. The server the agents switch starts is `agent_link`'s, not this.
/// configuration). Preferences › AI Integrations (`prefs`, read before the window opens) decide
/// whether agents may drive this launch, and its folders stand in for automation roots no flag
/// names. The server the agents switch starts is the agent link's, not this.
fn control_setup(
prefs: &photocraft_engine::prefs::Integrations,
cli_port: Option<u16>,
auth: photocraft_automation::args::ControlArgs,
automation: &photocraft_automation::args::AutomationArgs,
) -> ControlSetup {
control_setup_in(services::config_dir(), &integrations(services::prefs_file().as_deref()), cli_port, auth, automation)
control_setup_in(services::config_dir(), prefs, cli_port, auth, automation)
}
/// [`control_setup`] with the settings folder and Preferences › AI Integrations given.
@@ -344,7 +304,6 @@ fn control_setup_in(
auth: photocraft_automation::args::ControlArgs,
automation: &photocraft_automation::args::AutomationArgs,
) -> ControlSetup {
use photocraft_automation::agent_link;
let (port, warning) = control_port_for(cli_port, prefs);
if let Some(warning) = &warning {
eprint!("{warning}");
@@ -352,7 +311,7 @@ fn control_setup_in(
// A file a crashed (or, on macOS, quit) launch left behind names a port nothing serves. Before
// binding, so this launch's own listener doesn't keep it.
if let Some(dir) = &settings {
agent_link::remove_stale_connection(dir);
craft::automation::agents::remove_stale_connection(dir);
}
let Some(port) = port else {
return ControlSetup { control: None, warning: None };
@@ -379,7 +338,7 @@ fn control_setup_in(
} else {
eprintln!("photocraft: using supplied control token");
}
let (workspace, warning) = match automation_workspace(automation, prefs) {
let (workspace, warning) = match automation_workspace(automation, &prefs.agents) {
Ok(workspace) => workspace,
Err(error) => {
eprintln!("photocraft: cannot configure automation workspace: {error}");
@@ -448,8 +407,12 @@ fn main() -> eframe::Result {
attach_log_file(logger);
// The saved preferences the launch needs before the window opens, read once without opening
// the settings store (the app opens it later).
let saved = services::saved_prefs();
let prefs = &saved.prefs;
// An adapter named in the environment is chosen at startup, which a forwarded launch never reaches.
let rendering_mode = gpu_startup::read_rendering_prefs(services::prefs_file().as_deref()).1;
let rendering_mode = gpu_startup::rendering_prefs(&prefs.performance).1;
if gpu_startup::adapter_override_is_process_specific(std::env::var("PHOTOCRAFT_GPU_ADAPTER").ok().as_deref(), rendering_mode, gpu_startup::ADAPTER_CHOICE) {
launch_options.push(launch_args::PerProcess::GpuAdapterEnv);
}
@@ -467,12 +430,12 @@ fn main() -> eframe::Result {
let _ = (new_instance, &launch_options);
// Bind and authenticate the authorized control listener before display/GPU initialization.
let ControlSetup { control, warning: control_warning } = control_setup(control_port, auth, &automation);
let ControlSetup { control, warning: control_warning } = control_setup(&prefs.integrations, control_port, auth, &automation);
#[cfg(target_os = "linux")]
let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok());
#[cfg(target_os = "linux")]
let session = linux_display_session();
let session = linux_display_session(prefs.performance.linux_display_server);
// Finder / Dock / Open With deliver files as Apple events, not arguments; catch the one that
// launched us as well as later ones. Lives until the event loop returns.
@@ -501,8 +464,11 @@ fn main() -> eframe::Result {
let monitor = monitor_profile::detect_async();
// Brush presets load in the background; the app attaches them when they arrive.
let presets = services::presets_dir().map(photocraft_engine::preset_store::open_dir_async);
let custom_titlebar = custom_titlebar(services::prefs_file().as_deref());
let mut options = native_options(custom_titlebar);
// Who draws the window frame, decided once: the viewport below and the runtime's root frame both follow it.
// `PHOTOCRAFT_TITLEBAR`, `PHOTOCRAFT_CAPTION_STYLE` and `PHOTOCRAFT_CAPTION_LAYOUT` are read by the decision.
let decision = window_policy::decide_for(Prefix::new("PHOTOCRAFT"), Backend::from_env(), title_bar_pref(prefs));
let integrated_frame = matches!(decision.frame, Frame::Integrated(_));
let mut options = native_options(&decision.frame);
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; open on X11 when that was chosen.
#[cfg(target_os = "linux")]
if session == linux_libs::DisplaySession::X11 {
@@ -520,7 +486,7 @@ fn main() -> eframe::Result {
// driver moves to a safer one), and lock this start's marker until the first frames render.
let t_sentinel = std::time::Instant::now();
let os = gpu_startup::Os::current();
let (pref, mode) = gpu_startup::read_rendering_prefs(services::prefs_file().as_deref());
let (pref, mode) = gpu_startup::rendering_prefs(&prefs.performance);
let (previous, sentinel) = match services::config_dir() {
Some(dir) => gpu_startup::Sentinel::begin(&dir),
None => (gpu_startup::Previous::Clean, None),
@@ -534,12 +500,11 @@ fn main() -> eframe::Result {
write_start_marker(&sentinel, &plan);
let gpu_note: std::sync::Arc<std::sync::Mutex<Option<String>>> = Default::default();
// The adapter's real texture limits (egui asks for 8192 px), so big documents stay on the GPU.
let wanted_adapter =
gpu_startup::wanted_adapter(std::env::var("PHOTOCRAFT_GPU_ADAPTER").ok().as_deref(), &gpu_startup::read_gpu_adapter(services::prefs_file().as_deref()));
let wanted_adapter = gpu_startup::wanted_adapter(std::env::var("PHOTOCRAFT_GPU_ADAPTER").ok().as_deref(), &gpu_startup::gpu_adapter(&prefs.performance));
gpu_startup::configure(&mut options.wgpu_options.wgpu_setup, &plan, os, wanted_adapter, sentinel.clone(), gpu_note.clone());
// Preferences › Performance › Low-Latency Drawing (#1343): without vsync a stroke shows about
// 50 ms sooner; wgpu picks Immediate, else Mailbox, else Fifo by what the driver offers.
if gpu_startup::read_low_latency(services::prefs_file().as_deref()) {
if prefs.performance.low_latency_drawing {
options.wgpu_options.surface.present_mode = eframe::wgpu::PresentMode::AutoNoVsync;
}
// Testers' present mode and frame latency overrides (#1343), after the preference.
@@ -569,14 +534,17 @@ fn main() -> eframe::Result {
Box::new(move |cc| {
created_in_callback.store(true, std::sync::atomic::Ordering::Relaxed);
let automation = control.as_ref().map(|(_, _, workspace)| workspace.clone());
let mut services = services::native(automation);
let wake = {
let ctx = cc.egui_ctx.clone();
craft::host::Wake::new(move || ctx.request_repaint())
};
let mut services = services::native(automation, wake);
services.preset_store = presets;
#[cfg(target_os = "linux")]
let display = tablet::DisplayKind::of(cc);
#[cfg(target_os = "linux")]
{
services.is_wayland = display == Some(tablet::DisplayKind::Wayland);
file_dialog_probe::start();
if services.is_wayland {
let var = |name| std::env::var(name).ok();
services.xwayland_command =
@@ -591,11 +559,12 @@ fn main() -> eframe::Result {
};
#[cfg(not(target_os = "linux"))]
let session = Session::new();
PhotocraftApp::install_type_reset_hooks(&cc.egui_ctx);
let mut app = PhotocraftApp::new(session, services);
// Before the first pass: the one install of the craft runtime must see every pass from
// the first (R71); the app then runs on that context.
PhotocraftApp::setup_window(&cc.egui_ctx, Default::default(), decision);
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, services);
app.open_suite(&cc.egui_ctx);
app.min_frame_ms = uncapped.then_some(1000.0 / 240.0);
app.integrated_titlebar = cfg!(target_os = "macos");
app.custom_titlebar = custom_titlebar;
// Only the title bar's free gap drags the window, never the menus (mac_window.rs).
#[cfg(target_os = "macos")]
mac_window::disable_native_title_drag();
@@ -687,33 +656,31 @@ fn main() -> eframe::Result {
log::warn!("couldn't remember GPU backend {}: {e}", b.name());
}
});
// Agents in the open window, unless the launch flags (`--control`) manage the
// connection. Behind the suite's AI-MCP feature flag, the ArtCraft Launcher's switch
// (Settings › AI agents) is the one consent; without it, as before, a Control Port.
let flags = craft_flags::load();
for problem in &flags.problems {
log::warn!("feature flags: {problem}");
}
app.agent_link.mcp_flag = flags.enabled(&craft_flags::AI_MCP);
if app.agent_link.mcp_flag {
app.services.launcher_agents = Some(agent_link::launcher_watch(&cc.egui_ctx));
}
if let Some((listener, token, _)) = control {
app.agent_link.launch_flags = true;
app.agent_link.port = listener.local_addr().ok().map(|a| a.port());
let rx = control_server::start(listener, token, cc.egui_ctx.clone());
app = app.with_control(rx);
// Agents in the open window. Behind the suite's AI-MCP flag the ArtCraft Launcher's
// switch (Settings › AI agents) is the one consent; without it, as before, a Control
// Port saved in the preferences. The launch flags (`--control`) manage the connection
// for the whole run instead.
app.services.agent_switch = Some(craft::automation::agents::AgentSwitch::watch(photocraft_automation::agent_link::LAUNCHER_APP_ID, {
let ctx = cc.egui_ctx.clone();
craft::host::Wake::new(move || ctx.request_repaint())
}));
let link = if let Some((listener, token, _)) = control {
let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx);
let (requests, server) = craft::automation::server::serve(listener, token, host)?;
eprintln!("photocraft: control server listening on {}", server.addr);
app = app.with_control(requests);
craft::automation::agents::AgentLink::from_launch(server)
} else {
app.services.agent_link = Some(agent_link::service(services::config_dir()));
}
app.services.agent_automation = Some(Box::new(services::agent_automation));
craft::automation::agents::AgentLink::new(services::config_dir(), photocraft_engine::build_info::long_version())
};
app.services.agent_link = Some(link);
#[cfg(target_os = "macos")]
{
app.services.os_events = Some(apple_events.connect(&cc.egui_ctx));
// Quit through AppKit, not by closing the window (Touch Bar Macs, #1575, #1458).
app.services.quit = Some(Box::new(mac_window::terminate_later));
// The macOS menu bar, installed now so winit's default menu doesn't stay up.
if !in_window_menus {
app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app);
app.services.native_menu = photocraft_ui_egui::native_menu::install(&cc.egui_ctx, &mut app);
}
}
#[cfg(not(target_os = "macos"))]
@@ -727,22 +694,10 @@ fn main() -> eframe::Result {
app.services.cursor_pos = cursor::service(cc);
// The custom title bar's undecorated window must stay borderless, or its caption and
// border offset the content and the pointer on some Windows systems (#2246).
app.services.window_frame = window_frame::service(cc, custom_titlebar);
// Linux: the desktop's caption buttons (GNOME's, KDE's) on the sides its layout puts them.
if custom_titlebar {
app.services.caption_style = caption_style::service();
}
app.services.window_frame = window_frame::service(cc, integrated_frame);
// Caps Lock state (X11/Windows/macOS; `None` on native Wayland): the canvas shows the
// precise crosshair for painting tools while it is toggled on (#1758).
app.services.caps_lock = caps_lock::service(cc);
// Pick through the portal on a Wayland desktop even when the window went through
// Xwayland (a pen, or the X11 display-server preference): Xwayland's root window has
// no desktop pixels to read (#8977).
#[cfg(target_os = "linux")]
let portal = screen_color::uses_portal(native_session);
#[cfg(not(target_os = "linux"))]
let portal = false;
app.services.screen_pick = screen_color::service(cc, portal);
// Tablet pressure/tilt/eraser (winit drops them): the macOS monitor and the X11 reader
// write into the stylus feed. The monitor goes in here, not before the event loop:
// AppKit's shared application only exists once winit created it (#759).
@@ -766,23 +721,22 @@ fn main() -> eframe::Result {
tablet::spawn_x11(&app.stylus.feed, display);
app.services.right_button_down = tablet::right_button_service();
app.services.pen_end = tablet::pen_end_service();
app.services.pen_screen_px = tablet::pen_screen_service();
// Paths on the command line (Linux/Windows file associations, `photocraft a.psd`).
app.open_paths(&files);
if !unreadable_paths.is_empty() {
use photocraft_ui_egui::i18n;
let line = i18n::t("{path}: the path is not valid Unicode; rename the file and open it again.");
let lines = unreadable_paths.iter().map(|p| i18n::fmt(line, &[("path", p.as_str())])).collect();
photocraft_ui_egui::notices::post(&mut app, i18n::t("Could not open"), lines, true, None);
photocraft_ui_egui::notices::post(&mut app, i18n::t("Could not open"), lines, craft::theme::variant::Tone::Bad, None);
}
// Portable marker found but its data folder isn't writable (#228): say where settings went.
if let Some(w) = &app_dirs::current().warning {
photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], false, None);
photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], craft::theme::variant::Tone::Neutral, None);
}
// A preference's automation folder that couldn't be opened, or a token file it couldn't
// write: a Dock launch has no console.
if let Some(ControlNotice { title, lines }) = control_warning {
photocraft_ui_egui::notices::post(&mut app, title, lines, false, None);
photocraft_ui_egui::notices::post(&mut app, title, lines, craft::theme::variant::Tone::Neutral, None);
}
Ok(Box::new(app))
}),
@@ -863,107 +817,6 @@ pub(crate) fn no_child_spawns() -> std::sync::RwLockWriteGuard<'static, ()> {
#[cfg(test)]
mod tests {
#[test]
fn window_and_panel_geometry_survive_a_restart() {
let options = super::native_options(super::CUSTOM_TITLEBAR);
assert!(options.persist_window);
assert_eq!(options.persistence_path, super::services::config_dir().map(|dir| dir.join("ui.ron")));
#[derive(Default)]
struct Storage(std::collections::BTreeMap<String, String>);
impl eframe::Storage for Storage {
fn get_string(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
fn set_string(&mut self, key: &str, value: String) {
self.0.insert(key.into(), value);
}
fn remove_string(&mut self, key: &str) {
self.0.remove(key);
}
fn flush(&mut self) {}
}
let ctx = egui::Context::default();
let input = || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() };
let mut output = ctx.run_ui(input(), |ui| {
egui::Panel::right("dock").exact_size(410.0).show(ui, |ui| ui.set_min_width(ui.available_width()));
});
output.textures_delta.clear();
let mut storage = Storage::default();
ctx.memory(|memory| eframe::set_value(&mut storage, "egui", memory));
let restored = egui::Context::default();
restored.memory_mut(|memory| *memory = eframe::get_value(&storage, "egui").unwrap());
let mut output = restored.run_ui(input(), |ui| {
egui::Panel::right("dock").default_size(290.0).show(ui, |ui| ui.set_min_width(ui.available_width()));
});
output.textures_delta.clear();
let panel = egui::containers::panel::PanelState::load(&restored, photocraft_ui_egui::panels::panel_state_id(&restored, "dock")).unwrap();
assert_eq!(panel.size().x, 410.0);
}
/// A 0.36 `ui.ron` saved panel widths under `Id::new("dock")`; the first 0.37 launch copies
/// them to the parent-scoped key, leaves the old one for a rollback, and a later resize
/// survives two more restarts.
#[test]
fn saved_036_panel_widths_migrate_and_survive_two_restarts() {
#[derive(Default)]
struct Storage(std::collections::BTreeMap<String, String>);
impl eframe::Storage for Storage {
fn get_string(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
fn set_string(&mut self, key: &str, value: String) {
self.0.insert(key.into(), value);
}
fn remove_string(&mut self, key: &str) {
self.0.remove(key);
}
fn flush(&mut self) {}
}
let state = |width: f32| egui::containers::panel::PanelState { outer_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 600.0)) };
let input = || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() };
let draw = |ctx: &egui::Context| {
let mut output = ctx.run_ui(input(), |ui| {
egui::Panel::right("dock").default_size(290.0).show(ui, |ui| ui.set_min_width(ui.available_width()));
});
output.textures_delta.clear();
};
let save = |ctx: &egui::Context| {
let mut storage = Storage::default();
ctx.memory(|memory| eframe::set_value(&mut storage, "egui", memory));
storage
};
let restore = |storage: &Storage| {
let ctx = egui::Context::default();
ctx.memory_mut(|memory| *memory = eframe::get_value(storage, "egui").expect("the saved memory"));
ctx
};
// The real 0.14/0.15 shape: the panel state under the old key inside the egui memory.
let ctx = egui::Context::default();
ctx.data_mut(|d| d.insert_persisted(egui::Id::unique("dock"), state(410.0)));
let storage = save(&ctx);
let first = restore(&storage);
photocraft_ui_egui::panels::migrate_panel_state(&first);
draw(&first);
let key = photocraft_ui_egui::panels::panel_state_id(&first, "dock");
assert_eq!(egui::containers::panel::PanelState::load(&first, key).map(|p| p.size().x), Some(410.0));
assert!(egui::containers::panel::PanelState::load(&first, egui::Id::unique("dock")).is_some(), "the 0.36 key is kept");
// Resize in 0.37: the new key wins from now on.
first.data_mut(|d| d.insert_persisted(key, state(500.0)));
let storage = save(&first);
for restart in 0..2 {
let next = restore(&storage);
photocraft_ui_egui::panels::migrate_panel_state(&next);
draw(&next);
let key = photocraft_ui_egui::panels::panel_state_id(&next, "dock");
let width = egui::containers::panel::PanelState::load(&next, key).map(|p| p.size().x).unwrap_or_default();
assert!((width - 500.0).abs() < 0.5, "restart {restart}: the old 410 key must not win (got {width})");
}
}
/// Schema-probe `ui.ron` shapes *reconstructed* from the documented 0.14/0.15/0.37 layouts,
/// not recorded machine saves: 0.14 and 0.15 both store the flat window entry, which the
/// first 0.37 launch rewrites; a 0.37 file is left alone. Keeping all three probes makes a
@@ -994,7 +847,7 @@ mod tests {
#[test]
fn the_window_opens_centred_at_its_default_size() {
let o = super::native_options(super::CUSTOM_TITLEBAR);
let o = super::native_options(&super::Frame::Native);
assert!(o.centered, "#419: centred, not cascaded from the top-left corner");
assert_eq!(o.viewport.inner_size, Some(egui::vec2(1440.0, 900.0)));
// eframe shrinks the start size to the monitor, so the centred position is on-screen.
@@ -1003,31 +856,31 @@ mod tests {
#[test]
fn a_window_saved_while_minimized_reopens_at_the_minimum_size() {
let hook = super::native_options(super::CUSTOM_TITLEBAR).window_builder.expect("a window builder hook");
let hook = super::native_options(&super::Frame::Native).window_builder.expect("a window builder hook");
// Saved minimized on Windows, then centred on a 1920 × 1080 monitor by eframe.
let saved = super::native_options(super::CUSTOM_TITLEBAR).viewport.with_inner_size([160.0, 64.0]).with_position([880.0, 508.0]);
let saved = super::native_options(&super::Frame::Native).viewport.with_inner_size([160.0, 64.0]).with_position([880.0, 508.0]);
let opened = hook(saved);
assert_eq!(opened.inner_size, Some(egui::vec2(760.0, 480.0)));
assert_eq!(opened.position, Some(egui::pos2(580.0, 300.0)), "still centred");
// Too narrow only: only the width grows.
let opened = super::at_least_min_size(super::native_options(false).viewport.with_inner_size([500.0, 900.0]));
let opened = super::at_least_min_size(super::native_options(&super::Frame::Native).viewport.with_inner_size([500.0, 900.0]));
assert_eq!(opened.inner_size, Some(egui::vec2(760.0, 900.0)));
// A window at or above the minimum, or with no size, is left alone.
for size in [[760.0, 480.0], [1100.0, 760.0]] {
let builder = super::native_options(false).viewport.with_inner_size(size).with_position([10.0, 20.0]);
let builder = super::native_options(&super::Frame::Native).viewport.with_inner_size(size).with_position([10.0, 20.0]);
let opened = super::at_least_min_size(builder);
assert_eq!((opened.inner_size, opened.position), (Some(egui::Vec2::from(size)), Some(egui::pos2(10.0, 20.0))));
}
let mut builder = super::native_options(false).viewport;
let mut builder = super::native_options(&super::Frame::Native).viewport;
builder.inner_size = None;
assert_eq!(super::at_least_min_size(builder).inner_size, None);
}
#[test]
fn a_window_saved_in_full_screen_reopens_maximized_not_full_screen() {
let hook = super::native_options(super::CUSTOM_TITLEBAR).window_builder.expect("a window builder hook");
let hook = super::native_options(&super::Frame::Native).window_builder.expect("a window builder hook");
// What eframe restores from a ui.ron saved in a full-screen mode on Windows.
let saved = super::native_options(super::CUSTOM_TITLEBAR)
let saved = super::native_options(&super::Frame::Native)
.viewport
.with_inner_size([2560.0, 1392.0])
.with_position([0.0, 0.0])
@@ -1039,43 +892,50 @@ mod tests {
assert_eq!(opened.inner_size, Some(egui::vec2(2560.0, 1392.0)));
}
/// The preferences the launch reads from the settings folder `dir` (`services::saved_prefs`).
fn launch_prefs(dir: Option<&std::path::Path>) -> photocraft_engine::prefs::Preferences {
photocraft_engine::prefs::read_saved(dir).prefs
}
#[test]
fn the_system_title_bar_preference_keeps_the_window_decorations() {
// #1271, #1316: Preferences › Interface › System Title Bar gives the window back its
// system decorations on Windows and Linux; macOS always has them.
fn the_system_title_bar_preference_is_read_from_the_saved_preferences() {
// #1271, #1316: Preferences › Interface › System Title Bar asks for the system's bar; the frame
// decision (craft-window) turns the preference into the frame the platform allows.
use super::TitleBarPref;
let dir = std::env::temp_dir().join(format!("pc-titlebar-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("prefs.json");
let default_custom = super::CUSTOM_TITLEBAR;
assert_eq!(super::custom_titlebar(None), default_custom, "no preferences file: the platform default");
let file = dir.join(photocraft_engine::prefs::LEGACY_PREFS_FILE);
let read = || super::title_bar_pref(&launch_prefs(Some(&dir)));
assert_eq!(super::title_bar_pref(&launch_prefs(None)), TitleBarPref::default(), "no settings folder: the default");
assert_eq!(read(), TitleBarPref::default(), "nothing saved: the default");
std::fs::write(&file, "not json").unwrap();
assert_eq!(super::custom_titlebar(Some(&file)), default_custom, "an unreadable file: the platform default");
assert_eq!(read(), TitleBarPref::default(), "an unreadable file: the default");
std::fs::write(&file, r#"{"interface":{}}"#).unwrap();
assert_eq!(super::custom_titlebar(Some(&file)), default_custom, "an older preference file: the platform default");
assert_eq!(read(), TitleBarPref::default(), "an older preference file: the default");
std::fs::write(&file, r#"{"interface":{"systemTitleBar":true}}"#).unwrap();
assert!(!super::custom_titlebar(Some(&file)));
assert_eq!(super::native_options(false).viewport.decorations, Some(true));
assert_eq!(read(), TitleBarPref::System);
std::fs::write(&file, r#"{"interface":{"systemTitleBar":false}}"#).unwrap();
assert_eq!(super::custom_titlebar(Some(&file)), super::CUSTOM_TITLEBAR);
if super::CUSTOM_TITLEBAR {
assert_eq!(super::native_options(true).viewport.decorations, Some(false));
}
assert_eq!(read(), TitleBarPref::Integrated);
// Once the app's settings store has saved config.toml, the launch reads that, not the older file.
let (mut store, _) = craft::settings::SettingsStore::open_with(photocraft_engine::prefs::store_options(Some(&dir)));
store.update(|saved| saved.prefs.interface.system_title_bar = true);
store.flush().unwrap();
assert_eq!(read(), TitleBarPref::System, "config.toml wins over preferences.json");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn integrations_preferences_decide_the_control_port() {
use photocraft_engine::prefs::Integrations;
let off = Integrations { allow_agent_control: false, control_port: 0, ..Default::default() };
let on = Integrations { allow_agent_control: true, control_port: 0, ..Default::default() };
let preferred = Integrations { allow_agent_control: true, control_port: 7878, ..Default::default() };
let (off, on, preferred) = (agent_prefs(false, 0), agent_prefs(true, 0), agent_prefs(true, 7878));
// Nothing asked for, nothing listening.
assert_eq!(super::control_port_for(None, &on), (None, None));
// --control wins over the preference.
assert_eq!(super::control_port_for(Some(9000), &preferred), (Some(9000), None));
// The preference alone opens nothing at launch: the agent connection starts it while
// the app runs (`agent_link`).
// The preference alone opens nothing at launch: the agent link starts it while the app
// runs.
assert_eq!(super::control_port_for(None, &preferred), (None, None));
// Allow Agent Control off refuses both, and says so when --control asked for one
@@ -1084,24 +944,32 @@ mod tests {
let (port, warning) = super::control_port_for(Some(9000), &off);
assert_eq!(port, None);
assert!(warning.is_some_and(|w| w.contains("Allow Agent Control") && w.contains("9000")), "the refusal names the port");
let off_with_port = Integrations { allow_agent_control: false, control_port: 7878, ..Default::default() };
assert_eq!(super::control_port_for(None, &off_with_port), (None, None), "off beats a preferred port");
assert_eq!(super::control_port_for(None, &agent_prefs(false, 7878)), (None, None), "off beats a preferred port");
}
fn agent_prefs(allow: bool, port: u32) -> photocraft_engine::prefs::Integrations {
let mut prefs = photocraft_engine::prefs::Integrations::default();
prefs.agents.allow_agent_control = allow;
prefs.agents.control_port = port;
prefs
}
#[test]
fn integrations_fall_back_to_the_defaults_without_a_readable_file() {
let dir = std::env::temp_dir().join(format!("pc-integrations-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("prefs.json");
let file = dir.join(photocraft_engine::prefs::LEGACY_PREFS_FILE);
let default = photocraft_engine::prefs::Integrations::default();
assert_eq!(super::integrations(None), default, "no preferences file");
assert_eq!(launch_prefs(None).integrations, default, "no settings folder");
assert_eq!(launch_prefs(Some(&dir)).integrations, default, "nothing saved");
std::fs::write(&file, "not json").unwrap();
assert_eq!(super::integrations(Some(&file)), default, "an unreadable file");
assert_eq!(launch_prefs(Some(&dir)).integrations, default, "an unreadable file");
std::fs::write(&file, r#"{"integrations":{"allowAgentControl":false,"controlPort":7878}}"#).unwrap();
let read = super::integrations(Some(&file));
assert!(!read.allow_agent_control);
assert_eq!(read.control_port, 7878);
let read = launch_prefs(Some(&dir)).integrations;
assert!(!read.agents.allow_agent_control);
assert_eq!(read.agents.control_port, 7878);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1110,8 +978,9 @@ mod tests {
#[test]
fn a_bad_value_elsewhere_keeps_agent_control_off() {
let dir = std::env::temp_dir().join(format!("pc-integrations-lenient-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("prefs.json");
let file = dir.join(photocraft_engine::prefs::LEGACY_PREFS_FILE);
// What the Preferences dialog shows for the same file.
let shown = |text: &str| {
let mut session = photocraft_engine::Session::new();
@@ -1120,31 +989,30 @@ mod tests {
};
let read = |text: &str| {
std::fs::write(&file, text).unwrap();
let read = super::integrations(Some(&file));
let read = launch_prefs(Some(&dir)).integrations;
assert_eq!(read, shown(text), "{text}");
read
};
let r = read(r#"{"interface":{"showTooltips":"nope"},"integrations":{"allowAgentControl":false,"controlPort":7878}}"#);
assert!(!r.allow_agent_control, "a bad value in another section");
assert_eq!(r.control_port, 7878);
assert!(!r.agents.allow_agent_control, "a bad value in another section");
assert_eq!(r.agents.control_port, 7878);
let r = read(r#"{"integrations":{"allowAgentControl":false,"controlPort":"x"}}"#);
assert!(!r.allow_agent_control, "a bad port");
assert_eq!(r.control_port, 0, "the bad port alone takes its default");
assert!(!r.agents.allow_agent_control, "a bad port");
assert_eq!(r.agents.control_port, 0, "the bad port alone takes its default");
// A bad Allow Agent Control alone takes its default.
let r = read(r#"{"integrations":{"allowAgentControl":"no","controlPort":7878}}"#);
// (A saved port from before the agents switch turns it on, in both reads.)
assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878, connect_agents: true, ..Default::default() });
assert_eq!(r, photocraft_engine::prefs::Integrations { connect_agents: true, ..agent_prefs(true, 7878) });
read(r#"{"integrations":{"allowAgentControl":false,"controlPort":-1}}"#);
read(r#"{"integrations":{"allowAgentControl":false,"controlPort":4294967296}}"#);
read(r#"{"integrations":"off"}"#);
// serde reads a struct from a list too; the app does.
assert!(!read(r#"{"integrations":[false]}"#).allow_agent_control, "a list");
assert_eq!(read(r#"{"integrations":[false,7878]}"#).control_port, 7878);
// A section that isn't an object keeps the defaults, in both reads.
read(r#"{"integrations":[false,7878]}"#);
// The automation folders: a bad one takes its default alone, too.
let r = read(r#"{"integrations":{"allowAgentControl":false,"readRoot":5,"writeRoot":"/w"}}"#);
assert!(!r.allow_agent_control, "a bad folder");
assert_eq!((r.read_root.as_str(), r.write_root.as_str()), ("", "/w"));
assert!(!r.agents.allow_agent_control, "a bad folder");
assert_eq!((r.agents.read_root.as_str(), r.agents.write_root.as_str()), ("", "/w"));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1162,12 +1030,11 @@ mod tests {
}
}
fn roots(read: &std::path::Path, write: &std::path::Path) -> photocraft_engine::prefs::Integrations {
photocraft_engine::prefs::Integrations {
read_root: read.to_string_lossy().into_owned(),
write_root: write.to_string_lossy().into_owned(),
..Default::default()
}
fn roots(read: &std::path::Path, write: &std::path::Path) -> craft::automation::agents::AgentSettings {
let mut prefs = craft::automation::agents::AgentSettings::default();
prefs.read_root = read.to_string_lossy().into_owned();
prefs.write_root = write.to_string_lossy().into_owned();
prefs
}
/// Preferences › AI Integrations' folders are the automation roots when no flag names one, and
@@ -1200,7 +1067,7 @@ mod tests {
assert_eq!(ws.read_with_save_path("b.txt").unwrap().1.as_deref(), Some("b.txt"));
// Empty preferences grant nothing, as no flags do.
let (ws, warning) = super::automation_workspace(&flags(None, None), &photocraft_engine::prefs::Integrations::default()).unwrap();
let (ws, warning) = super::automation_workspace(&flags(None, None), &craft::automation::agents::AgentSettings::default()).unwrap();
assert_eq!(warning, None);
assert!(ws.read("a.txt").is_err() && ws.write("c.txt", b"x").is_err());
let _ = std::fs::remove_dir_all(&dir);
@@ -1228,7 +1095,8 @@ mod tests {
#[test]
fn a_relative_preference_folder_is_left_out() {
let dir = temp_dir("automation-roots-relative");
let relative = photocraft_engine::prefs::Integrations { read_root: ".".into(), ..roots(&dir, &dir) };
let mut relative = roots(&dir, &dir);
relative.read_root = ".".into();
let (ws, warning) = super::automation_workspace(&flags(None, None), &relative).unwrap();
let warning = warning.expect("the relative read folder is named");
assert!(warning.contains("Automation Read Folder") && warning.contains("not an absolute path"), "{warning}");
+1 -1
View File
@@ -1,5 +1,5 @@
//! Photoshop's live keyboard shortcut set on this machine, for the one-time offer to import it
//! at first launch (`photocraft_ui_egui::kys_import::offer_import`).
//! at first launch (`photocraft_ui_egui::kys_import::offer`).
//!
//! Photoshop keeps the set in use as `Keyboard Shortcuts.psp` in its per-version settings
//! folder; it is the same XML a saved `.kys` holds, named after the set the user chose.
-195
View File
@@ -1,195 +0,0 @@
//! File › Save As through the XDG desktop portal on Linux (#6121, #4328, #4394).
//!
//! The GTK file chooser behind the portal keeps the typed name when the user picks another file
//! type, and rfd 0.17 reads only the file name from the portal's answer, so `image.psd` with PNG
//! picked came back as `image.psd` and was written as a PSD. The answer does say which type was
//! picked (`current_filter`), so Save As asks the portal itself and gives a name the dialog left
//! alone that type's extension ([`crate::services::with_chosen_type`]). rfd stays the fallback
//! (zenity, or no portal), and this can go once an rfd release reads the picked type
//! (PolyMeilex/rfd#341).
//!
//! The dialog is attached to the window on X11. On Wayland it has no parent: naming the window to
//! the portal needs an xdg-foreign handle, which takes `unsafe` code the workspace forbids.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
/// One file type in the dialog: its label and extensions (`("PNG", ["png"])`).
pub type Filter = (String, Vec<String>);
/// A Save dialog to show.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SaveRequest {
/// The portal's parent window identifier (`x11:<xid>`), or empty.
pub parent: String,
/// The name the dialog shows: the stem of the suggested file (`test`), see
/// `services::dialog_file_name`.
pub name: Option<String>,
/// The suggested file's name (`test.psd`): a name that comes back with its extension still
/// takes the extension of the type picked ([`crate::services::with_chosen_type`]).
pub suggested: Option<String>,
pub folder: Option<PathBuf>,
pub filters: Vec<Filter>,
/// The filter the dialog starts on.
pub current: Option<usize>,
}
/// What the user chose: the path, as typed, and the label of the file type picked.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Saved {
pub path: PathBuf,
pub filter: Option<String>,
}
/// The portal's parent window identifier for `window`: `x11:<xid>` on X11, empty elsewhere.
pub fn parent_id(window: Option<eframe::wgpu::rwh::RawWindowHandle>) -> String {
use eframe::wgpu::rwh::RawWindowHandle;
match window {
Some(RawWindowHandle::Xlib(h)) => format!("x11:{:x}", h.window),
Some(RawWindowHandle::Xcb(h)) => format!("x11:{:x}", h.window.get()),
_ => String::new(),
}
}
/// Shows the portal's Save dialog and waits for it. `Ok(None)` is Cancel; `Err` means the portal
/// couldn't show it (no portal, no FileChooser), so the caller falls back to rfd.
pub fn save_file(conn: &zbus::blocking::Connection, req: &SaveRequest) -> Result<Option<Saved>, String> {
use futures_lite::StreamExt;
use zbus::blocking::Proxy;
let unique = conn.unique_name().ok_or("Portal connection has no unique name")?.as_str().trim_start_matches(':').replace('.', "_");
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let token = format!("photocraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let path = format!("/org/freedesktop/portal/desktop/request/{unique}/{token}");
// Listen before asking, so a quick answer isn't missed.
let request = Proxy::new(conn, "org.freedesktop.portal.Desktop", path.as_str(), "org.freedesktop.portal.Request").map_err(|e| e.to_string())?;
let mut replies = futures_lite::future::block_on(request.inner().receive_signal("Response")).map_err(|e| e.to_string())?;
let chooser = Proxy::new(conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser")
.map_err(|e| e.to_string())?;
let handle: OwnedObjectPath = chooser.call("SaveFile", &(req.parent.as_str(), "Save As", options(req, &token))).map_err(|e| e.to_string())?;
// A portal older than 0.9 ignores `handle_token` and answers on a request path of its own,
// which it returns: listen there instead, as the Request documentation asks.
let reply = if handle.as_str() == path {
futures_lite::future::block_on(replies.next())
} else {
let request = Proxy::new(conn, "org.freedesktop.portal.Desktop", handle.as_str(), "org.freedesktop.portal.Request").map_err(|e| e.to_string())?;
let mut replies = futures_lite::future::block_on(request.inner().receive_signal("Response")).map_err(|e| e.to_string())?;
futures_lite::future::block_on(replies.next())
}
.ok_or("The save dialog closed without an answer")?;
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
answer(code, &results)
}
/// The `SaveFile` options for `req`.
fn options<'a>(req: &'a SaveRequest, token: &'a str) -> HashMap<&'static str, Value<'a>> {
let mut o: HashMap<&'static str, Value<'a>> = HashMap::from([("handle_token", Value::from(token)), ("modal", Value::from(true))]);
if let Some(name) = &req.name {
o.insert("current_name", Value::from(name.as_str()));
}
if let Some(folder) = &req.folder {
// A byte string with its terminating NUL, as the portal specifies.
use std::os::unix::ffi::OsStrExt;
let mut bytes = folder.as_os_str().as_bytes().to_vec();
bytes.push(0);
o.insert("current_folder", Value::from(bytes));
}
let wire = |(label, exts): &Filter| (label.clone(), exts.iter().map(|e| (0u32, format!("*.{e}"))).collect::<Vec<_>>());
if !req.filters.is_empty() {
o.insert("filters", Value::from(req.filters.iter().map(wire).collect::<Vec<_>>()));
}
if let Some(f) = req.current.and_then(|i| req.filters.get(i)) {
o.insert("current_filter", Value::from(wire(f)));
}
o
}
/// Reads the portal's `Response`: code 0 with the first `uris` entry. 1 is Cancel, and 2 a dialog
/// closed some other way, such as with Esc in GNOME's: no file either, and not a reason to show
/// rfd's dialog instead (it did, so Esc opened a second Save As).
fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Saved>, String> {
match code {
0 => {}
1 | 2 => return Ok(None),
_ => return Err(format!("the save dialog failed (portal response {code})")),
}
let uris: Vec<String> = results
.get("uris")
.ok_or("no file in the portal's answer")?
.try_clone()
.map_err(|e| e.to_string())?
.try_into()
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
let uri = uris.first().ok_or("no file in the portal's answer")?;
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
let filter = results.get("current_filter").and_then(|v| {
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
Some(label)
});
Ok(Some(Saved { path, filter }))
}
/// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes.
fn file_uri_path(uri: &str) -> Option<PathBuf> {
let rest = uri.strip_prefix("file://")?;
// Only local files: `file:///…` or `file://localhost/…`.
let rest = rest.strip_prefix("localhost").unwrap_or(rest);
if !rest.starts_with('/') {
return None;
}
let bytes = rest.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = bytes.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
use std::os::unix::ffi::OsStringExt;
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
}
/// Which file type's extensions belong on the name the dialog returned: the one it reported, or,
/// when the dialog offered only one type, that one. It reports no pick then, and the name it was
/// given is the stem (`services::dialog_file_name`), so a bare `Swatches` has to come back as
/// `Swatches.aco`. `None` when the answer names no type this dialog offered.
fn chosen_type(filters: &[Filter], picked: Option<usize>) -> Option<usize> {
match picked {
Some(i) if i < filters.len() => Some(i),
None if filters.len() == 1 => Some(0),
_ => None,
}
}
/// Save As on Linux: the portal's dialog, with the name given the extension of the file type
/// picked. When that changes the name to one that already exists, the dialog opens again under
/// the new name, so the portal asks before replacing it (it asked only about the typed name).
pub fn save_as(conn: &zbus::blocking::Connection, mut req: SaveRequest) -> Result<Option<PathBuf>, String> {
loop {
let Some(saved) = save_file(conn, &req)? else { return Ok(None) };
let picked = saved.filter.as_deref().and_then(|label| req.filters.iter().position(|(l, _)| l == label));
// A typed extension is the user's own: `with_chosen_type` keeps one it recognises.
let exts: &[String] = match chosen_type(&req.filters, picked) {
Some(i) => &req.filters[i].1,
None => &[],
};
let path = crate::services::with_chosen_type(&saved.path, req.suggested.as_deref(), exts);
if path == saved.path || !path.exists() {
return Ok(Some(path));
}
req.name = path.file_name().map(|n| n.to_string_lossy().into_owned());
req.suggested = req.name.clone();
req.folder = path.parent().map(Path::to_path_buf);
req.current = picked;
}
}
#[cfg(test)]
mod tests;
-267
View File
@@ -1,267 +0,0 @@
use super::*;
use std::sync::{Arc, Mutex};
#[test]
fn file_uris_become_local_paths() {
assert_eq!(file_uri_path("file:///home/me/Untitled-1.psd"), Some(PathBuf::from("/home/me/Untitled-1.psd")));
assert_eq!(file_uri_path("file:///home/me/A%20b%C3%A9.png"), Some(PathBuf::from("/home/me/A bé.png")));
assert_eq!(file_uri_path("file://localhost/tmp/x.png"), Some(PathBuf::from("/tmp/x.png")));
assert_eq!(file_uri_path("sftp://host/x.png"), None);
assert_eq!(file_uri_path("file://host/x.png"), None);
}
#[test]
fn x11_windows_are_named_to_the_portal() {
use eframe::wgpu::rwh::{RawWindowHandle, XlibWindowHandle};
assert_eq!(parent_id(Some(RawWindowHandle::Xlib(XlibWindowHandle::new(0x3a0000f)))), "x11:3a0000f");
assert_eq!(parent_id(None), "");
}
/// What the mock portal answers to one `SaveFile` call: the response code, and the file and
/// filter label the user "picked".
type Script = Vec<(u32, Option<(&'static str, &'static str)>)>;
/// The options of each `SaveFile` call the mock portal received: current_name and the label of
/// current_filter.
type Seen = Arc<Mutex<Vec<(Option<String>, Option<String>)>>>;
/// A private session bus (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser` that
/// answers `SaveFile` from `script`. `None` when there is no `dbus-daemon` to run.
fn mock_portal(script: Script) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
mock_portal_with(script, false)
}
/// [`mock_portal`]; with `own_paths` it is a portal older than 0.9, which ignores `handle_token`,
/// answers on a request path of its own and returns that from `SaveFile`, as a real dialog does
/// once the user is done with it (here after 300 ms).
fn mock_portal_with(script: Script, own_paths: bool) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
use std::io::BufRead;
let spawns = crate::CHILD_SPAWNS.read().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut daemon =
std::process::Command::new("dbus-daemon").args(["--session", "--nofork", "--print-address=1"]).stdout(std::process::Stdio::piped()).spawn().ok()?;
drop(spawns);
let mut address = String::new();
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
let address = address.trim().to_string();
let server = zbus::blocking::connection::Builder::address(address.as_str()).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap();
let seen: Seen = Arc::default();
let log = seen.clone();
// A stream only gets the messages that arrive after it exists: made in the thread, it could
// miss a `SaveFile` sent before the thread got going, and the call would wait forever.
let messages = zbus::blocking::MessageIterator::from(&server);
std::thread::spawn(move || {
let mut script = script.into_iter();
for msg in messages {
let Ok(msg) = msg else { break };
let header = msg.header();
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("SaveFile") {
continue;
}
let (_parent, _title, options): (String, String, HashMap<String, OwnedValue>) = msg.body().deserialize().unwrap();
let text = |key: &str| options.get(key).and_then(|v| String::try_from(v.try_clone().ok()?).ok());
let filter = options.get("current_filter").and_then(|v| {
let (label, _): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
Some(label)
});
log.lock().unwrap().push((text("current_name"), filter));
let sender = header.sender().unwrap().as_str().trim_start_matches(':').replace('.', "_");
let token = if own_paths { format!("old{}", log.lock().unwrap().len()) } else { text("handle_token").unwrap() };
let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}");
server.reply(&header, &OwnedObjectPath::try_from(path.as_str()).unwrap()).unwrap();
if own_paths {
std::thread::sleep(std::time::Duration::from_millis(300));
}
let (code, pick) = script.next().unwrap_or((2, None));
let mut results: HashMap<&str, Value<'_>> = HashMap::new();
if let Some((uri, label)) = pick {
results.insert("uris", Value::from(vec![uri.to_string()]));
results.insert("current_filter", Value::from((label.to_string(), vec![(0u32, "*.x".to_string())])));
}
server
.emit_signal(
header.sender().cloned().map(zbus::names::BusName::from),
path.as_str(),
"org.freedesktop.portal.Request",
"Response",
&(code, results),
)
.unwrap();
}
});
let client = zbus::blocking::connection::Builder::address(address.as_str()).unwrap().build().unwrap();
Some((client, seen, daemon))
}
fn request(name: &str) -> SaveRequest {
let filters = [("PSD Document", &["psd", "psb"][..]), ("PNG", &["png"]), ("JPEG", &["jpg"])];
SaveRequest {
parent: String::new(),
name: Some(name.into()),
suggested: Some(name.into()),
folder: Some(PathBuf::from("/tmp")),
filters: filters.iter().map(|(l, e)| (l.to_string(), e.iter().map(|s| s.to_string()).collect())).collect(),
current: Some(0),
}
}
/// #6121 end to end through a real D-Bus: the name comes back as typed with the type picked,
/// and Save As writes it with that type's extension.
#[test]
fn save_as_follows_the_file_type_picked_in_the_portal_dialog() {
let dir = std::env::temp_dir().join(format!("photocraft-portal-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let typed = format!("file://{}/Untitled-1.psd", dir.display());
let typed: &'static str = Box::leak(typed.into_boxed_str());
let Some((conn, seen, mut daemon)) = mock_portal(vec![(0, Some((typed, "PNG"))), (1, None), (0, Some((typed, "PSD Document")))]) else {
eprintln!("no dbus-daemon: skipped");
return;
};
// PNG picked with `Untitled-1.psd` still in the name: written as Untitled-1.png.
assert_eq!(save_as(&conn, request("Untitled-1.psd")).unwrap(), Some(dir.join("Untitled-1.png")));
assert_eq!(seen.lock().unwrap()[0], (Some("Untitled-1.psd".into()), Some("PSD Document".into())), "the request carried the name and type");
// Cancel.
assert_eq!(save_as(&conn, request("Untitled-1.psd")).unwrap(), None);
// The type the name already has: unchanged.
assert_eq!(save_as(&conn, request("Untitled-1.psd")).unwrap(), Some(dir.join("Untitled-1.psd")));
daemon.kill().ok();
std::fs::remove_dir_all(&dir).ok();
}
/// The dialog opens on the bare name (`test`, see `services::dialog_file_name`), so GTK doesn't
/// ask to replace test.psd when PNG is picked: the type picked gives the extension, and a name
/// that then exists is asked about under that name.
#[test]
fn a_bare_name_takes_the_picked_type_and_an_existing_target_is_asked_about() {
let dir = std::env::temp_dir().join(format!("photocraft-portal-bare-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("test.psd"), b"open document").unwrap();
let uri = |name: &str| -> &'static str { Box::leak(format!("file://{}/{name}", dir.display()).into_boxed_str()) };
let Some((conn, seen, mut daemon)) = mock_portal(vec![
(0, Some((uri("test"), "PNG"))),
(0, Some((uri("test.psd"), "PNG"))),
(0, Some((uri("test"), "PSD Document"))),
(0, Some((uri("test.psd"), "PSD Document"))),
]) else {
eprintln!("no dbus-daemon: skipped");
return;
};
// As File › Save As opens it: `test` shown, `test.psd` suggested.
let opened = || SaveRequest { suggested: Some("test.psd".into()), ..request("test") };
// PNG picked: test.png, and nothing was asked about test.psd.
assert_eq!(save_as(&conn, opened()).unwrap(), Some(dir.join("test.png")));
// The suggested extension back in the name (typed again, or GTK's completion) with PNG
// picked: test.png too, not a PSD written over test.psd.
assert_eq!(save_as(&conn, opened()).unwrap(), Some(dir.join("test.png")));
// The type untouched: test.psd, which exists, so the dialog asks again as test.psd (the
// portal's replace prompt is then about the file that is written).
assert_eq!(save_as(&conn, opened()).unwrap(), Some(dir.join("test.psd")));
let seen = seen.lock().unwrap().clone();
let names: Vec<_> = seen.iter().map(|(name, _)| name.as_deref()).collect();
assert_eq!(names, [Some("test"), Some("test"), Some("test"), Some("test.psd")], "{seen:?}");
assert_eq!(seen[3].1.as_deref(), Some("PSD Document"));
daemon.kill().ok();
std::fs::remove_dir_all(&dir).ok();
}
/// GNOME's dialog closed with Esc answers 2 ("ended some other way"): no file, like Cancel, and
/// no fallback to rfd, which opened a second Save As.
#[test]
fn a_dialog_closed_some_other_way_is_a_cancel() {
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(2, None)]) else {
eprintln!("no dbus-daemon: skipped");
return;
};
assert_eq!(save_as(&conn, request("test")), Ok(None));
daemon.kill().ok();
}
/// An extension the user typed is theirs: `art.png` with the PSD type left as the dialog opened
/// saves a PNG, as it did before the type was read.
#[test]
fn a_typed_extension_wins_over_an_untouched_file_type() {
let typed: &'static str = "file:///tmp/photocraft-none/art.png";
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some((typed, "PSD Document")))]) else {
eprintln!("no dbus-daemon: skipped");
return;
};
assert_eq!(save_as(&conn, request("Untitled-1.psd")).unwrap(), Some(PathBuf::from("/tmp/photocraft-none/art.png")));
daemon.kill().ok();
}
/// A portal older than 0.9 answers on a request path of its own: the wait follows the handle
/// `SaveFile` returns, as the Request documentation asks, instead of the predicted path.
#[test]
fn the_answer_is_awaited_on_the_handle_the_portal_returns() {
let typed: &'static str = "file:///tmp/photocraft-none/Untitled-1.psd";
let Some((conn, _seen, mut daemon)) = mock_portal_with(vec![(0, Some((typed, "PNG")))], true) else {
eprintln!("no dbus-daemon: skipped");
return;
};
assert_eq!(save_as(&conn, request("Untitled-1.psd")).unwrap(), Some(PathBuf::from("/tmp/photocraft-none/Untitled-1.png")));
daemon.kill().ok();
}
/// When the extension the type gives names a file that exists, the dialog opens again under that
/// name (so the portal asks before replacing it) instead of overwriting it unasked.
#[test]
fn a_renamed_file_that_exists_is_confirmed_in_the_dialog() {
let dir = std::env::temp_dir().join(format!("photocraft-portal-exists-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("art.png"), b"old").unwrap();
let typed: &'static str = Box::leak(format!("file://{}/art.psd", dir.display()).into_boxed_str());
let confirmed: &'static str = Box::leak(format!("file://{}/art.png", dir.display()).into_boxed_str());
let Some((conn, seen, mut daemon)) = mock_portal(vec![(0, Some((typed, "PNG"))), (0, Some((confirmed, "PNG")))]) else {
eprintln!("no dbus-daemon: skipped");
return;
};
assert_eq!(save_as(&conn, request("art.psd")).unwrap(), Some(dir.join("art.png")));
let seen = seen.lock().unwrap().clone();
assert_eq!(seen.len(), 2, "asked again: {seen:?}");
assert_eq!(seen[1], (Some("art.png".into()), Some("PNG".into())), "under the new name, on the picked type");
assert_eq!(std::fs::read(dir.join("art.png")).unwrap(), b"old", "nothing written by the dialog");
daemon.kill().ok();
std::fs::remove_dir_all(&dir).ok();
}
/// With only one type offered (the Swatches panel's .aco) a typed extension is kept.
#[test]
fn a_single_file_type_keeps_the_typed_extension() {
let typed: &'static str = "file:///tmp/photocraft-none/Swatches.ase";
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some((typed, "Color Swatches")))]) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let req = SaveRequest { filters: vec![("Color Swatches".into(), vec!["aco".into()])], ..request("Swatches.aco") };
assert_eq!(save_as(&conn, req).unwrap(), Some(PathBuf::from("/tmp/photocraft-none/Swatches.ase")));
daemon.kill().ok();
}
/// The same single type, with the name left as the dialog shows it: the bare stem comes back, and
/// that one type gives it its extension instead of a file named `Swatches` being written.
#[test]
fn a_single_file_type_gives_the_bare_name_its_extension() {
let typed: &'static str = "file:///tmp/photocraft-none/Swatches";
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some((typed, "Color Swatches")))]) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let req = SaveRequest { filters: vec![("Color Swatches".into(), vec!["aco".into()])], ..request("Swatches.aco") };
assert_eq!(save_as(&conn, req).unwrap(), Some(PathBuf::from("/tmp/photocraft-none/Swatches.aco")));
daemon.kill().ok();
}
/// Which type's extensions the returned name gets. The portal cases above need a `dbus-daemon`,
/// so the rule itself is checked here too, which needs none.
#[test]
fn the_type_that_gives_the_extension_is_the_one_picked() {
let one: Vec<Filter> = vec![("Color Swatches".into(), vec!["aco".into()])];
// One type offered: the dialog reports no pick, and it was given the stem.
assert_eq!(chosen_type(&one, None), Some(0));
assert_eq!(chosen_type(&one, Some(0)), Some(0));
let many: Vec<Filter> = request("test").filters;
assert_eq!(chosen_type(&many, Some(1)), Some(1));
// Several types and no pick: nothing to add, as before.
assert_eq!(chosen_type(&many, None), None);
// An answer naming a type this dialog never offered is not a pick either.
assert_eq!(chosen_type(&many, Some(99)), None);
}
-508
View File
@@ -1,508 +0,0 @@
//! Desktop colour capture starts only on an explicit UI request. No snapshots are written to
//! disk, transmitted or retained after a pick. Wayland delegates to its permission portal.
use photocraft_ui_egui::screen_picker::{Capture, Pending, Service};
// Only the platform capture backends (and the tests) build images and check sizes.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows", test))]
use photocraft_ui_egui::screen_picker::MAX_PIXELS;
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
use photocraft_ui_egui::screen_picker::ScreenImage;
pub fn service(cc: &eframe::CreationContext<'_>, wayland: bool) -> Option<Service> {
if !cfg!(any(target_os = "linux", target_os = "macos", target_os = "windows")) {
return None;
}
let window = cc.winit_window()?.clone();
Some(Box::new(move |ctx| {
let (tx, rx) = std::sync::mpsc::channel();
let fallback = tx.clone();
let placements: Vec<Placement> = window
.available_monitors()
.enumerate()
.map(|(index, m)| {
let p = m.position();
let size = m.size();
Placement { index, x: p.x, y: p.y, width: size.width, height: size.height }
})
.collect();
let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let stop = cancelled.clone();
let scale = ctx.native_pixels_per_point().unwrap_or(1.0);
let wake = ctx.clone();
if let Err(e) = std::thread::Builder::new().name("screen-color-picker".into()).spawn(move || {
let result = capture(wayland, scale, &stop, &placements);
let _ = tx.send(result);
wake.request_repaint();
}) {
let _ = fallback.send(Err(format!("Could not start screen color picker: {e}")));
}
Pending { receiver: rx, cancelled }
}))
}
/// Whether to pick through the desktop portal: on a Wayland desktop, whichever display server the
/// window opened on. Xwayland serves only its own windows, so reading its root window fails (#8977).
#[cfg(target_os = "linux")]
pub fn uses_portal(desktop: crate::linux_libs::DisplaySession) -> bool {
desktop == crate::linux_libs::DisplaySession::Wayland
}
#[derive(Clone, Copy)]
#[cfg_attr(not(any(target_os = "linux", target_os = "macos", target_os = "windows", test)), allow(dead_code))]
struct Placement {
index: usize,
x: i32,
y: i32,
width: u32,
height: u32,
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows", test))]
fn find_monitor(placements: &[Placement], x: i32, y: i32, w: u32, h: u32) -> Option<usize> {
placements.iter().find(|p| p.x == x && p.y == y && p.width == w && p.height == h).map(|p| p.index)
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows", test))]
fn count(width: usize, height: usize) -> Result<usize, String> {
width.checked_mul(height).filter(|&n| n > 0 && n <= MAX_PIXELS).ok_or_else(|| "Screen capture exceeds the 64 MP memory budget".into())
}
#[cfg(target_os = "linux")]
const MAX_ICC_PROFILE_BYTES: usize = 1024 * 1024;
#[cfg(target_os = "linux")]
const ICC_PROFILE_PROPERTY_LONG_LENGTH: u32 = 256 * 1024;
#[cfg(target_os = "linux")]
fn icc_profile(bytes: Vec<u8>) -> Option<Vec<u8>> {
if bytes.is_empty() || bytes.len() > MAX_ICC_PROFILE_BYTES {
return None;
}
let profile = match craft_cms::Profile::parse(&bytes) {
Ok(profile) => profile,
Err(_) => return None,
};
(profile.color_space == craft_cms::ColorSpace::Rgb).then_some(bytes)
}
#[cfg(target_os = "linux")]
fn icc_profile_atom<C: x11rb::connection::RequestConnection>(conn: &C, name: &str) -> Option<u32> {
use x11rb::protocol::xproto::ConnectionExt as _;
let cookie = match conn.intern_atom(true, name.as_bytes()) {
Ok(cookie) => cookie,
Err(_) => return None,
};
let atom = match cookie.reply() {
Ok(reply) => reply.atom,
Err(_) => return None,
};
(atom != 0).then_some(atom)
}
#[cfg(target_os = "linux")]
fn output_icc_profile<C: x11rb::connection::RequestConnection>(conn: &C, output: u32, atom: u32) -> Option<Vec<u8>> {
use x11rb::protocol::{randr::ConnectionExt as _, xproto::AtomEnum};
let cookie = match conn.randr_get_output_property(output, atom, AtomEnum::CARDINAL, 0, ICC_PROFILE_PROPERTY_LONG_LENGTH, false, false) {
Ok(cookie) => cookie,
Err(_) => return None,
};
let reply = match cookie.reply() {
Ok(reply) => reply,
Err(_) => return None,
};
if reply.type_ != u32::from(AtomEnum::CARDINAL) || reply.format != 8 || reply.bytes_after != 0 {
return None;
}
icc_profile(reply.data)
}
#[cfg(target_os = "linux")]
fn root_icc_profile<C: x11rb::connection::RequestConnection>(conn: &C, root: u32, atom: u32) -> Option<Vec<u8>> {
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt as _};
let cookie = match conn.get_property(false, root, atom, AtomEnum::ANY, 0, ICC_PROFILE_PROPERTY_LONG_LENGTH) {
Ok(cookie) => cookie,
Err(_) => return None,
};
let reply = match cookie.reply() {
Ok(reply) => reply,
Err(_) => return None,
};
if reply.format != 8 || reply.bytes_after != 0 {
return None;
}
icc_profile(reply.value)
}
#[cfg(target_os = "linux")]
fn capture(wayland: bool, scale: f32, stop: &std::sync::atomic::AtomicBool, placements: &[Placement]) -> Result<Capture, String> {
if wayland {
return portal(stop);
}
use x11rb::{
connection::Connection,
image::{Image, PixelLayout},
protocol::{randr::ConnectionExt as _, xproto::VisualClass},
};
let (conn, index) = x11rb::connect(None).map_err(|e| e.to_string())?;
let screen = conn.setup().roots.get(index).ok_or("X11 screen is missing")?;
let (w, h) = (screen.width_in_pixels, screen.height_in_pixels);
count(usize::from(w), usize::from(h))?;
let mut monitors = conn.randr_get_monitors(screen.root, true).ok().and_then(|c| c.reply().ok()).map(|r| r.monitors).unwrap_or_default();
monitors.sort_by_key(|m| !m.primary);
if !monitors.iter().any(|m| m.primary)
&& let Some(first) = monitors.first_mut()
{
first.primary = true;
}
let regions: Vec<(i16, i16, u16, u16, bool, Vec<x11rb::protocol::randr::Output>)> = if monitors.is_empty() {
vec![(0, 0, w, h, true, Vec::new())]
} else {
monitors.iter().map(|m| (m.x, m.y, m.width, m.height, m.primary, m.outputs.clone())).collect()
};
if regions.len() > 16 {
return Err("Too many screens for the color picker".into());
}
let mut total = 0usize;
for &(x, y, mw, mh, _, _) in &regions {
if x < 0 || y < 0 || u32::from(x as u16) + u32::from(mw) > u32::from(w) || u32::from(y as u16) + u32::from(mh) > u32::from(h) {
return Err("Invalid X11 display geometry".into());
}
total = total
.checked_add(count(usize::from(mw), usize::from(mh))?)
.filter(|&n| n <= MAX_PIXELS)
.ok_or("Combined displays exceed the screen picker memory budget")?;
}
let (image, visual_id) = Image::get(&conn, screen.root, 0, 0, w, h).map_err(|e| format!("Screen capture failed: {e}"))?;
let visual = screen.allowed_depths.iter().flat_map(|d| &d.visuals).find(|v| v.visual_id == visual_id).ok_or("Unsupported X11 screen visual")?;
if visual.class != VisualClass::TRUE_COLOR {
return Err("Screen picking requires an X11 TrueColor visual".into());
}
let layout = PixelLayout::from_visual_type(*visual).map_err(|e| e.to_string())?;
let output_profile_atom = icc_profile_atom(&conn, "_ICC_PROFILE");
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let byte = |v: u16| ((u32::from(v) + 128) / 257) as u8;
let mut images = Vec::new();
for (x, y, mw, mh, primary, outputs) in regions {
if stop.load(std::sync::atomic::Ordering::Relaxed) {
return Ok(Capture::Color(None));
}
let profile = output_profile_atom.and_then(|atom| outputs.iter().find_map(|output| output_icc_profile(&conn, *output, atom))).or_else(|| {
if !primary {
return None;
}
icc_profile_atom(&conn, "_ICC_PROFILE").and_then(|atom| root_icc_profile(&conn, screen.root, atom))
});
let mut rgba = Vec::with_capacity(count(usize::from(mw), usize::from(mh))?.saturating_mul(4));
for row in 0..mh {
for col in 0..mw {
let (r, g, b) = layout.decode(image.get_pixel((x as u16) + col, (y as u16) + row));
rgba.extend_from_slice(&[byte(r), byte(g), byte(b), 255]);
}
}
images.push(ScreenImage {
monitor: find_monitor(placements, i32::from(x), i32::from(y), u32::from(mw), u32::from(mh)),
position: egui::pos2(f32::from(x), f32::from(y)) / scale,
size: egui::vec2(f32::from(mw), f32::from(mh)) / scale,
width: usize::from(mw),
height: usize::from(mh),
rgba,
profile,
});
}
Ok(Capture::Images(images))
}
#[cfg(target_os = "linux")]
fn portal(stop: &std::sync::atomic::AtomicBool) -> Result<Capture, String> {
use std::collections::HashMap;
use zbus::{
blocking::Proxy,
zvariant::{OwnedObjectPath, OwnedValue, Value},
};
let conn = zbus::blocking::connection::Builder::session()
.map_err(|e| e.to_string())?
.method_timeout(std::time::Duration::from_secs(10))
.build()
.map_err(|e| e.to_string())?;
let unique = conn.unique_name().ok_or("Portal connection has no unique name")?.as_str().trim_start_matches(':').replace('.', "_");
let token = format!("photocraft_{}", std::process::id());
let path = format!("/org/freedesktop/portal/desktop/request/{unique}/{token}");
let request = Proxy::new(&conn, "org.freedesktop.portal.Desktop", path.as_str(), "org.freedesktop.portal.Request").map_err(|e| e.to_string())?;
use futures_lite::StreamExt;
let mut replies = futures_lite::future::block_on(request.inner().receive_signal("Response")).map_err(|e| e.to_string())?;
let screenshot = Proxy::new(&conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
.map_err(|e| e.to_string())?;
let options: HashMap<&str, Value<'_>> = HashMap::from([("handle_token", Value::from(token.as_str()))]);
let _handle: OwnedObjectPath =
screenshot.call("PickColor", &("", options)).map_err(|e| format!("The desktop portal does not support color picking: {e}"))?;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
let reply = loop {
if stop.load(std::sync::atomic::Ordering::Relaxed) || std::time::Instant::now() >= deadline {
let _: Result<(), _> = request.call("Close", &());
return Ok(Capture::Color(None));
}
let next = futures_lite::future::block_on(futures_lite::future::race(async { Some(replies.next().await) }, async {
async_io::Timer::after(std::time::Duration::from_millis(50)).await;
None
}));
if let Some(message) = next {
break message.ok_or("The desktop color picker closed without a result")?;
}
};
let (code, values): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
if code == 1 {
return Ok(Capture::Color(None));
}
if code != 0 {
return Err("The desktop color picker could not sample this screen".into());
}
let value = values.get("color").ok_or("Desktop picker returned no color")?;
let (r, g, b): (f64, f64, f64) = value.try_clone().map_err(|e| e.to_string())?.try_into().map_err(|e: zbus::zvariant::Error| e.to_string())?;
if [r, g, b].iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v)) {
return Err("Desktop picker returned an invalid color".into());
}
Ok(Capture::Color(Some([r as f32, g as f32, b as f32])))
}
#[cfg(target_os = "windows")]
fn capture(_wayland: bool, _scale: f32, stop: &std::sync::atomic::AtomicBool, placements: &[Placement]) -> Result<Capture, String> {
let monitors = xcap::Monitor::all().map_err(|e| e.to_string())?;
if monitors.is_empty() || monitors.len() > 16 {
return Err("No supported screen is available".into());
}
let mut budget = 0usize;
for m in &monitors {
budget = budget
.checked_add(count(m.width().map_err(|e| e.to_string())? as usize, m.height().map_err(|e| e.to_string())? as usize)?)
.filter(|&n| n <= MAX_PIXELS)
.ok_or("Combined displays exceed the screen picker memory budget")?;
}
let mut total = 0usize;
let mut images = Vec::new();
for m in monitors {
if stop.load(std::sync::atomic::Ordering::Relaxed) {
return Ok(Capture::Color(None));
}
let (w, h) = (m.width().map_err(|e| e.to_string())?, m.height().map_err(|e| e.to_string())?);
let scale = m.scale_factor().map_err(|e| e.to_string())?;
if !scale.is_finite() || scale <= 0.0 || scale > 16.0 {
return Err("Invalid display scale".into());
}
let captured = m.capture_image().map_err(|e| format!("Screen capture failed: {e}"))?;
let (width, height) = (captured.width() as usize, captured.height() as usize);
total = total.checked_add(count(width, height)?).filter(|&n| n <= MAX_PIXELS).ok_or("Combined displays exceed the screen picker memory budget")?;
let (x, y) = (m.x().map_err(|e| e.to_string())?, m.y().map_err(|e| e.to_string())?);
images.push(ScreenImage {
monitor: find_monitor(placements, x, y, w, h),
position: egui::pos2(x as f32, y as f32) / scale,
size: egui::vec2(w as f32, h as f32) / scale,
width,
height,
rgba: captured.into_raw(),
profile: None,
});
}
Ok(Capture::Images(images))
}
#[cfg(target_os = "macos")]
fn capture(_wayland: bool, _scale: f32, stop: &std::sync::atomic::AtomicBool, placements: &[Placement]) -> Result<Capture, String> {
use core_graphics2::{display::get_active_display_list, image::CGImageAlphaInfo as Alpha, window};
if !window::preflight_screen_capture_access() && !window::request_screen_capture_access() {
return Err("Allow PhotoCraft in System Settings > Privacy & Security > Screen Recording, then reopen PhotoCraft".into());
}
let displays = get_active_display_list(17).ok_or("Could not enumerate displays")?;
if displays.is_empty() || displays.len() > 16 {
return Err("No supported screen is available".into());
}
let mut budget = 0usize;
for display in &displays {
let mode = display.copy_display_mode().ok_or("Display mode is unavailable")?;
budget = budget
.checked_add(count(mode.pixel_width(), mode.pixel_height())?)
.filter(|&n| n <= MAX_PIXELS)
.ok_or("Combined displays exceed the screen picker memory budget")?;
}
let mut images = Vec::new();
let mut total = 0usize;
for display in displays {
if stop.load(std::sync::atomic::Ordering::Relaxed) {
return Ok(Capture::Color(None));
}
// Capture a composed monitor at native resolution through safe bindings. Keeping the
// CoreGraphics seam preserves PhotoCraft's existing macOS 11 deployment target.
let bounds = display.bounds();
let image = window::new_image(
bounds,
window::CGWindowListOption::OnScreenOnly,
window::kCGNullWindowID,
window::CGWindowImageOption::BestResolution | window::CGWindowImageOption::ShouldBeOpaque,
)
.ok_or("Screen capture failed; check Screen Recording permission")?;
let (width, height) = (image.width(), image.height());
total = total.checked_add(count(width, height)?).filter(|&n| n <= MAX_PIXELS).ok_or("Combined displays exceed the screen picker memory budget")?;
let profile = image.color_space().and_then(|space| space.copy_icc_data());
if profile.as_ref().is_some_and(|p| p.len() > 1024 * 1024) {
return Err("Screen profile exceeds the memory budget".into());
}
let info = image.bitmap_info().bits();
if image.bits_per_component() != 8 || image.bits_per_pixel() != 32 || info & (1 << 8) != 0 {
return Err("Unsupported screen capture pixel format".into());
}
let (first, premultiplied, opaque) = match image.alpha_info() {
Alpha::AlphaPremultipliedFirst => (true, true, false),
Alpha::AlphaPremultipliedLast => (false, true, false),
Alpha::AlphaFirst => (true, false, false),
Alpha::AlphaLast => (false, false, false),
Alpha::AlphaNoneSkipFirst => (true, false, true),
Alpha::AlphaNoneSkipLast => (false, false, true),
_ => return Err("Unsupported screen capture alpha layout".into()),
};
let little = match info & 0x7000 {
0 => cfg!(target_endian = "little"),
0x2000 => true,
0x4000 => false,
_ => return Err("Unsupported screen capture byte order".into()),
};
let order = match (first, little) {
(true, true) => [2, 1, 0, 3],
(true, false) => [1, 2, 3, 0],
(false, true) => [3, 2, 1, 0],
(false, false) => [0, 1, 2, 3],
};
let stride = image.bytes_per_row();
checked_stride(width, height, stride)?;
let bytes = image.data_provider().and_then(|p| p.copy_data()).ok_or("Screen image has no pixels")?;
let rgba = unpack_rgba(bytes.bytes(), width, height, stride, order, premultiplied, opaque)?;
let (w, h) = (bounds.size.width as f32, bounds.size.height as f32);
let (x, y) = (bounds.origin.x as f32, bounds.origin.y as f32);
if ![w, h, x, y].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 {
return Err("Invalid display geometry".into());
}
let scale = width as f32 / w;
images.push(ScreenImage {
monitor: find_monitor(placements, (x * scale).round() as i32, (y * scale).round() as i32, width as u32, height as u32),
position: egui::pos2(x, y),
size: egui::vec2(w, h),
width,
height,
rgba,
profile: profile.map(|p| p.bytes().to_vec()),
});
}
Ok(Capture::Images(images))
}
// CoreGraphics rows can be padded and their byte order/alpha vary. Kept platform independent
// so Linux CI also tests the macOS decoding path against synthetic pixels.
#[cfg(any(target_os = "macos", test))]
fn checked_stride(width: usize, height: usize, stride: usize) -> Result<usize, String> {
count(width, height)?;
let row = width.checked_mul(4).ok_or("Invalid screen row")?;
if stride < row || stride > row.saturating_add(4096) {
return Err("Invalid screen row stride".into());
}
stride.checked_mul(height).filter(|&n| n <= MAX_PIXELS.saturating_mul(4)).ok_or_else(|| "Screen buffer exceeds the memory budget".into())
}
#[cfg(any(target_os = "macos", test))]
fn unpack_rgba(bytes: &[u8], width: usize, height: usize, stride: usize, order: [usize; 4], premultiplied: bool, opaque: bool) -> Result<Vec<u8>, String> {
let length = checked_stride(width, height, stride)?;
if bytes.len() < length || order.iter().any(|&i| i > 3) {
return Err("Invalid screen pixel buffer".into());
}
let mut out = Vec::with_capacity(count(width, height)?.saturating_mul(4));
for row in bytes.chunks_exact(stride).take(height) {
for p in row[..width * 4].as_chunks::<4>().0 {
let a = if opaque { 255 } else { p[order[3]] };
for &i in &order[..3] {
let v = u32::from(p[i]);
out.push(if premultiplied && a != 255 {
if a == 0 { 0 } else { ((v * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8 }
} else {
v as u8
});
}
out.push(255);
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn screen_capture_decodes_padded_bgra_and_premultiplied_argb() {
assert_eq!(
unpack_rgba(&[10, 20, 30, 0, 99, 99, 99, 99, 40, 50, 60, 0, 99, 99, 99, 99], 1, 2, 8, [2, 1, 0, 3], false, true).unwrap(),
[30, 20, 10, 255, 60, 50, 40, 255]
);
assert_eq!(unpack_rgba(&[128, 64, 32, 16], 1, 1, 4, [1, 2, 3, 0], true, false).unwrap(), [128, 64, 32, 255]);
assert_eq!(unpack_rgba(&[0, 0, 0, 0], 1, 1, 4, [0, 1, 2, 3], true, false).unwrap(), [0, 0, 0, 255]);
}
#[test]
fn screen_capture_rejects_unbounded_or_truncated_buffers() {
assert!(count(usize::MAX, 2).is_err());
assert!(checked_stride(1, 1, usize::MAX).is_err());
assert!(checked_stride(1, MAX_PIXELS, 4096).is_err());
assert!(unpack_rgba(&[0; 3], 1, 1, 4, [0, 1, 2, 3], false, true).is_err());
assert!(unpack_rgba(&[0; 4], 1, 1, 4, [4, 1, 2, 3], false, true).is_err());
}
#[cfg(target_os = "linux")]
#[test]
fn x11_screen_capture_accepts_only_bounded_rgb_icc_profiles() {
let rgb = craft_cms::Builtin::Srgb.profile().to_bytes();
let bytes = rgb.as_ref().clone();
assert_eq!(icc_profile(bytes.clone()), Some(bytes));
assert!(icc_profile(Vec::new()).is_none());
assert!(icc_profile(vec![0; MAX_ICC_PROFILE_BYTES + 1]).is_none());
let cmyk = craft_cms::Builtin::CoatedCmyk.profile().to_bytes();
assert!(icc_profile(cmyk.as_ref().clone()).is_none());
}
#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires a live X11 display; draws only a tiny synthetic fixture"]
fn screen_capture_reads_a_known_x11_fixture_pixel() {
use x11rb::{
COPY_DEPTH_FROM_PARENT,
connection::Connection,
protocol::xproto::{ConfigureWindowAux, ConnectionExt, CreateWindowAux, StackMode, WindowClass},
};
let (conn, index) = x11rb::connect(None).unwrap();
let screen = &conn.setup().roots[index];
let window = conn.generate_id().unwrap();
conn.create_window(
COPY_DEPTH_FROM_PARENT,
window,
screen.root,
200,
200,
8,
8,
0,
WindowClass::INPUT_OUTPUT,
0,
&CreateWindowAux::new().override_redirect(1).background_pixel(0xff8040),
)
.unwrap()
.check()
.unwrap();
conn.map_window(window).unwrap().check().unwrap();
conn.configure_window(window, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE)).unwrap().check().unwrap();
conn.flush().unwrap();
// X11 request completion precedes the compositor presenting the mapped fixture.
std::thread::sleep(std::time::Duration::from_millis(150));
let images = capture(false, 1.0, &std::sync::atomic::AtomicBool::new(false), &[]);
conn.destroy_window(window).unwrap().check().unwrap();
conn.flush().unwrap();
let Capture::Images(images) = images.unwrap() else { panic!("not an image capture") };
let first = images.iter().find(|m| m.position.x <= 200.0 && m.position.y <= 200.0).unwrap();
let x = (200.0 - first.position.x) as usize;
let y = (200.0 - first.position.y) as usize;
let offset = (y * first.width + x) * 4;
assert_eq!(&first.rgba[offset..offset + 4], &[255, 128, 64, 255]);
}
#[cfg(target_os = "linux")]
#[test]
fn a_wayland_desktop_picks_through_the_portal_even_with_an_xwayland_window() {
use crate::linux_libs::DisplaySession;
// A pen or the X11 display-server preference opens the window through Xwayland, but the
// session is still Wayland: the X11 grab fails there with BadMatch (#8977).
assert!(uses_portal(DisplaySession::Wayland));
assert!(!uses_portal(DisplaySession::X11));
}
#[test]
fn screen_capture_matches_negative_and_hidpi_monitor_geometry() {
let m = [Placement { index: 2, x: -3840, y: 0, width: 3840, height: 2160 }];
assert_eq!(find_monitor(&m, -3840, 0, 3840, 2160), Some(2));
assert_eq!(find_monitor(&m, 0, 0, 1920, 1080), None);
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn capture(_wayland: bool, _scale: f32, _stop: &std::sync::atomic::AtomicBool, _placements: &[Placement]) -> Result<Capture, String> {
Err("Screen color picking is unavailable on this platform".into())
}
+31 -336
View File
@@ -1,338 +1,18 @@
//! Native platform services: file dialogs (rfd), filesystem, codecs.
//! Native platform services: filesystem, codecs, clipboard, crash recovery, the settings store and
//! the file panels.
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image};
use photocraft_doc::Document;
use photocraft_format::RecoveryStore;
use photocraft_ui_egui::{FileDialogAnswer, FileDialogReply, FileDialogRequest, Recoverable, Services};
use photocraft_ui_egui::{Recoverable, Services};
use std::cell::{Cell, RefCell};
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
#[cfg(test)]
mod recovery_tests;
/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster, Krita and Affinity documents, flat images, and
/// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl), swatches (.aco, .act, .ase) and keyboard shortcut sets
/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
const OPEN_EXTS: &[&str] = &[
"pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "dib", "tga",
"ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pnm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3",
"iff", "lbm", "ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz",
"aco", "act", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
/// Open dialog extensions that also match uppercase and mixed-case names (`IMG_0001.JPG`).
/// On Linux and the BSDs rfd turns each extension into a case-sensitive `*.ext` glob for the XDG
/// portal or zenity, so every letter becomes a character class, as the portal spec suggests
/// (`*.[iI][cC][oO]`). Windows and macOS take literal extensions and ignore case already.
fn open_filter_extensions(extensions: &[&str]) -> Vec<String> {
let case_sensitive_globs = cfg!(all(unix, not(target_os = "macos")));
let class = |c: char| if c.is_ascii_alphabetic() { format!("[{}{}]", c.to_ascii_lowercase(), c.to_ascii_uppercase()) } else { c.to_string() };
extensions.iter().map(|ext| if case_sensitive_globs { ext.chars().map(class).collect() } else { ext.to_string() }).collect()
}
/// File › Open's file types after All Formats, as Photoshop lists them: one per format, so a folder
/// of mixed files can be narrowed to one kind (#6337). The document formats, the rest by name as in
/// [`SAVE_FILTERS`], then the app's own resources. Together they cover every extension of
/// [`OPEN_EXTS`]. An explicit SVG filter also keeps vector artwork discoverable when a native
/// picker defaults to another filter.
const OPEN_FILTERS: &[(&str, &[&str])] = &[
("Photoshop", &["psd", "psb", "psdt"]),
("PhotoCraft", &["pcraft"]),
("Affinity", &["af", "afdesign", "afphoto", "afpub"]),
("Amiga IFF", &["iff", "lbm", "ilbm"]),
("BMP", &["bmp", "dib"]),
("DDS", &["dds"]),
("DICOM", &["dcm", "dicom", "dc3"]),
("DPX and Cineon", &["dpx", "cin"]),
("FITS", &["fits", "fit", "fts"]),
("GIF", &["gif"]),
("GIMP", &["xcf", "xcfgz", "gz"]),
("HEIF", &["heic", "heif", "hif"]),
("ICO", &["ico"]),
("JPEG", &["jpg", "jpeg"]),
("Krita", &["kra", "krz"]),
("OpenEXR", &["exr"]),
("OpenRaster", &["ora"]),
("Paint.NET", &["pdn"]),
("PCX", &["pcx"]),
("PNG", &["png"]),
("Portable Bitmap", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]),
("QOI", &["qoi"]),
("Radiance HDR", &["hdr"]),
("RAW images", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
("SVG", SVG_EXTS),
("Targa", &["tga"]),
("TIFF", &["tif", "tiff"]),
("WebP", &["webp"]),
("XPM", &["xpm"]),
("Brushes", &["abr"]),
("Gradients", &["grd"]),
("Styles", &["asl"]),
("Swatches", &["aco", "act", "ase"]),
("Keyboard Shortcuts", &["kys"]),
];
fn open_filters() -> Vec<(&'static str, Vec<String>)> {
std::iter::once(("All Formats", open_filter_extensions(OPEN_EXTS)))
.chain(OPEN_FILTERS.iter().map(|(name, exts)| (*name, open_filter_extensions(exts))))
.collect()
}
/// File › Save As formats: (filter name, extensions). PSD, PSB and PhotoCraft's own format, which
/// keep the most of a document, then the rest by name, so a long list stays easy to search. The
/// filter matching the suggested name's extension comes first, so a .pcraft document saves as
/// .pcraft by default and everything else keeps defaulting to PSD. The PSD type takes `.psb` too:
/// Windows adds the selected type's extension to a name whose extension isn't one of the type's,
/// so `art.psb` typed under the PSD type would come back as `art.psb.psd`.
const SAVE_FILTERS: &[(&str, &[&str])] = &[
("PSD Document", &["psd", "psb"]),
("PSB Large Document", &["psb"]),
("PhotoCraft", &["pcraft"]),
("Amiga IFF", &["iff"]),
("BMP", &["bmp", "dib"]),
("Cineon", &["cin"]),
// Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327).
("DDS", &["dds"]),
("DPX", &["dpx"]),
("FITS", &["fits", "fit"]),
("GIF", &["gif"]),
// BMP and GIF are also in Photoshop's Save As list; ICO is PhotoCraft's own (#4357): up to
// 256×256, with alpha.
("ICO", &["ico"]),
("JPEG", &["jpg", "jpeg"]),
("JPEG XL", &["jxl"]),
// The encoder picks P5, P6, P7 or PFM from the image, not from the name, so only the neutral
// .pnm is offered: a .pbm or .pgm name would hold pixmap data (CodeRabbit on #9775).
("Netpbm", &["pnm"]),
("OpenEXR", &["exr"]),
("OpenRaster", &["ora"]),
("PDF", &["pdf"]),
("PNG", &["png"]),
("Radiance HDR", &["hdr"]),
("Targa", &["tga"]),
("TIFF", &["tif", "tiff"]),
("WebP", &["webp"]),
];
/// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog
/// never swaps their extension for a document format's.
const OTHER_SAVE_FILTERS: &[(&str, &[&str])] = &[("Color Swatches", &["aco"]), ("Color Table", &["act"]), ("Swatch Exchange", &["ase"])];
/// `suggested` with a Netpbm subtype's extension (an opened .pgm) as the neutral .pnm, the name
/// every save dialog starts from: the encoder picks P5, P6, P7 or PFM from the image, so the old
/// suffix could name other data, and macOS and rfd keep the suggested name as it is.
fn netpbm_as_pnm(suggested: &str) -> String {
let path = Path::new(suggested);
let subtype = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).is_some_and(|e| ["pbm", "pgm", "ppm", "pam", "pfm"].contains(&e.as_str()));
if subtype { path.with_extension("pnm").to_string_lossy().into_owned() } else { suggested.to_string() }
}
/// Lists the save dialog's file types with the `suggested` type first (added if unlisted), so the dialog keeps that extension instead of .psd.
fn save_filters(suggested: &str) -> Vec<(String, Vec<String>)> {
let ext = Path::new(suggested).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
// A Netpbm subtype's name (an opened .pgm) starts on the Netpbm type as .pnm: the encoder picks
// the subtype from the image, so the old name could describe other data (CodeRabbit on #9775).
let ext = if ["pbm", "pgm", "ppm", "pam", "pfm"].contains(&ext.as_str()) { "pnm".to_string() } else { ext };
if let Some((name, exts)) = OTHER_SAVE_FILTERS.iter().find(|(_, exts)| exts.contains(&ext.as_str())) {
return vec![(name.to_string(), exts.iter().map(|e| e.to_string()).collect())];
}
let mut v: Vec<(String, Vec<String>)> = SAVE_FILTERS.iter().map(|(name, exts)| (name.to_string(), exts.iter().map(|e| e.to_string()).collect())).collect();
// The type the extension is first for (`.psb` starts on PSB, not on PSD's second extension),
// else any type that lists it.
let own = v.iter().position(|(_, exts)| exts.first() == Some(&ext));
match own.or_else(|| v.iter().position(|(_, exts)| exts.contains(&ext))) {
Some(i) => {
let (name, mut exts) = v.remove(i);
// Windows adds the first type's first extension to a bare name: `cat.jpeg` stays
// `.jpeg`, and `sky.fit` stays `.fit`.
exts.retain(|e| *e != ext);
exts.insert(0, ext);
v.insert(0, (name, exts));
}
None if !ext.is_empty() => v.insert(0, (ext.to_ascii_uppercase(), vec![ext])),
None => {}
}
v
}
/// `path` with the extension of the file type picked in the save dialog (`chosen`), where the
/// dialog left the name alone (#6121): the format follows the extension, and the GTK file chooser
/// keeps the typed name when another type is picked. Only a name that still has the extension the
/// dialog opened with (`opened_with`, `Untitled-1.psd` with PNG picked) or none gets the type's
/// extension, as PolyMeilex/rfd#341 does. An extension the user typed that PhotoCraft saves
/// (`art.png` with the PSD type untouched, the way to save a PNG before this) is theirs and stays,
/// and so does one of the type's own. One PhotoCraft doesn't save (`scan.2024`)
/// is part of the name, and the type's extension is added after it. The exception: two of the
/// type's own extensions (`art.psb.psd` under the PSD type) lose the last, since KDE's dialog adds
/// it after a typed one; the returned name can't tell that from a typed `art.psb.psd`, which is
/// rare, so that one is saved as `art.psb` too.
#[cfg(any(target_os = "linux", test))]
pub(crate) fn with_chosen_type(path: &Path, opened_with: Option<&str>, chosen: &[String]) -> PathBuf {
let Some(first) = chosen.first() else { return path.to_path_buf() };
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let opened_ext = opened_with.and_then(|n| Path::new(n).extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
// A name that already had one of the type's extensions, with the type's first one added after
// it (KDE's dialog does that: `art.psb` typed under the PSD type came back as `art.psb.psd`).
let inner = path.file_stem().map(Path::new).and_then(|s| s.extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
if let (Some(ext), Some(inner)) = (&ext, &inner)
&& ext != inner
&& chosen.contains(ext)
&& chosen.contains(inner)
{
return path.with_extension("");
}
match ext {
Some(ext) if chosen.contains(&ext) => path.to_path_buf(),
Some(ext) if opened_ext.as_ref() == Some(&ext) => path.with_extension(first),
Some(ext) if SAVE_FILTERS.iter().chain(OTHER_SAVE_FILTERS).any(|(_, exts)| exts.contains(&ext.as_str())) => path.to_path_buf(),
_ => {
let mut name = path.as_os_str().to_owned();
name.push(".");
name.push(first);
PathBuf::from(name)
}
}
}
/// The name the save dialog starts with. Where the type picked gives a bare name its extension
/// (`adds_extension`), the dialog gets the stem and the suggested type (listed first by
/// [`save_filters`]) supplies `.psd`:
/// - On Windows a visible extension stays put when the user picks another type (with File name
/// extensions shown, `image.psd` saved as PhotoCraft stayed `image.psd`, #4394).
/// - On Linux the portal's dialog keeps the name as typed, and before returning asks whether to
/// replace a file of that name, so `test.psd` with PNG picked asked to replace test.psd, which
/// the save leaves alone (#6121). From the stem [`with_chosen_type`] gives the picked type's
/// extension, and a name that then exists is asked about under that name
/// (`portal_save::save_as`).
///
/// A stem that still has a dot (`scan.jpg.psd`: Windows could keep `scan.jpg`) or an upper-case
/// extension (the user's spelling) keeps the whole name. Elsewhere the whole name is kept: the
/// macOS panel has no type list, and rfd's Linux dialogs don't say which type was picked.
fn dialog_file_name(suggested: &str, adds_extension: bool) -> Option<String> {
let path = Path::new(suggested);
let name = path.file_name()?.to_string_lossy().into_owned();
let (Some(stem), Some(ext)) = (path.file_stem(), path.extension().and_then(|e| e.to_str())) else { return Some(name) };
let bare = adds_extension && Path::new(stem).extension().is_none() && !ext.is_empty() && ext == ext.to_ascii_lowercase();
Some(if bare { stem.to_string_lossy().into_owned() } else { name })
}
/// Shows an Open or Save dialog without blocking the event loop (#673, #574): rfd's async dialog
/// is created here, on the main thread, with the window as its parent (a sheet on macOS, an owned
/// modal window elsewhere), and a helper thread waits for it and hands the answer to the app.
fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>, reply: FileDialogReply) {
let mut dialog = rfd::AsyncFileDialog::new();
if let Some(parent) = parent {
dialog = dialog.set_parent(parent);
}
let answer: Pin<Box<dyn Future<Output = Option<FileDialogAnswer>> + Send>> = match request {
FileDialogRequest::Open { multiple, initial_dir, extensions } => {
if let Some(dir) = initial_dir {
dialog = dialog.set_directory(dir);
}
// A command-specific filter must not inherit the image formats used by File › Open.
let dialog = if let Some(exts) = extensions {
dialog.add_filter("Supported Files", &open_filter_extensions(&exts.iter().map(String::as_str).collect::<Vec<_>>()))
} else {
open_filters().into_iter().fold(dialog, |dialog, (name, extensions)| dialog.add_filter(name, &extensions))
};
if multiple {
let picked = dialog.pick_files();
Box::pin(async move { picked.await.map(|files| answer(files.iter().map(|f| f.path()), false, FileDialogAnswer::Paths)) })
} else {
let picked = dialog.pick_file();
Box::pin(async move { picked.await.map(|file| answer([file.path()], false, FileDialogAnswer::Paths)) })
}
}
FileDialogRequest::Folder { initial_dir } => {
if let Some(dir) = initial_dir {
dialog = dialog.set_directory(dir);
}
let picked = dialog.pick_folder();
Box::pin(async move { picked.await.map(|folder| answer_one(folder.path(), true, FileDialogAnswer::FolderTo)) })
}
FileDialogRequest::Save { suggested } => {
let suggested = netpbm_as_pnm(&suggested);
let filters = save_filters(&suggested);
let name = dialog_file_name(&suggested, cfg!(windows));
let dir = Path::new(&suggested).parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf);
for (name, exts) in &filters {
dialog = dialog.add_filter(name, exts);
}
if let Some(name) = &name {
dialog = dialog.set_file_name(name);
}
if let Some(dir) = &dir {
dialog = dialog.set_directory(dir);
}
// On Linux the portal's own dialog, which reports the file type picked (#6121); rfd if
// the portal can't show it.
#[cfg(target_os = "linux")]
{
use eframe::wgpu::rwh::HasWindowHandle;
let parent = crate::portal_save::parent_id(parent.and_then(|p| p.window_handle().ok()).map(|h| h.as_raw()));
let req = crate::portal_save::SaveRequest {
parent,
name: dialog_file_name(&suggested, true),
suggested: Path::new(&suggested).file_name().map(|n| n.to_string_lossy().into_owned()),
folder: dir,
filters,
current: Some(0),
};
Box::pin(async move {
let portal = zbus::blocking::connection::Builder::session()
.and_then(|b| b.build())
.map_err(|e| e.to_string())
.and_then(|conn| crate::portal_save::save_as(&conn, req));
match portal {
Ok(path) => path.map(|p| answer_one(&p, true, FileDialogAnswer::SaveTo)),
Err(e) => {
log::info!("portal save dialog unavailable ({e}), using rfd");
dialog.save_file().await.map(|file| answer_one(file.path(), true, FileDialogAnswer::SaveTo))
}
}
})
}
#[cfg(not(target_os = "linux"))]
{
let _ = filters;
let picked = dialog.save_file();
Box::pin(async move { picked.await.map(|file| answer_one(file.path(), true, FileDialogAnswer::SaveTo)) })
}
}
};
// Without the thread the reply is dropped unanswered, which the app takes as Cancel.
if let Err(e) = std::thread::Builder::new().name("file dialog".into()).spawn(move || {
// An empty answer from a system with no dialog backend isn't a Cancel (#3354).
let answer = block_on(answer).or_else(|| crate::file_dialog_probe::known_problem().map(FileDialogAnswer::Unavailable));
reply.send(answer)
}) {
log::error!("couldn't wait for the file dialog: {e}");
}
}
/// The dialog's answer for the chosen `paths`, or the error for one whose name isn't valid
/// Unicode, which a lossy copy would turn into another file's name (#6601). `saving`: the paths
/// are to be written to.
fn answer<'a>(paths: impl IntoIterator<Item = &'a Path>, saving: bool, make: impl FnOnce(Vec<String>) -> FileDialogAnswer) -> FileDialogAnswer {
match paths.into_iter().map(|p| photocraft_ui_egui::file_open::path_text(p, saving)).collect() {
Ok(paths) => make(paths),
Err(e) => FileDialogAnswer::Unavailable(e),
}
}
/// [`answer`] for a dialog that picks one path.
fn answer_one(path: &Path, saving: bool, make: impl FnOnce(String) -> FileDialogAnswer) -> FileDialogAnswer {
match photocraft_ui_egui::file_open::path_text(path, saving) {
Ok(path) => make(path),
Err(e) => FileDialogAnswer::Unavailable(e),
}
}
/// Runs `future` to completion on this thread, sleeping until it is woken.
pub(crate) fn block_on<T>(future: impl Future<Output = T>) -> T {
struct Unpark(std::thread::Thread);
@@ -360,8 +40,16 @@ pub fn config_dir() -> Option<PathBuf> {
crate::app_dirs::config_dir()
}
pub fn prefs_file() -> Option<PathBuf> {
config_dir().map(|d| d.join("preferences.json"))
/// The preferences store in [`config_dir`] (in memory when there is none), importing the older
/// `preferences.json` on the first run (`photocraft_engine::prefs::store_options`).
fn settings_store() -> (craft::settings::SettingsStore<photocraft_engine::prefs::SavedPrefs>, craft::settings::LoadReport) {
craft::settings::SettingsStore::open_with(photocraft_engine::prefs::store_options(config_dir().as_deref()))
}
/// The preferences [`settings_store`] would load, read without opening it: the launch reads
/// before the window opens.
pub fn saved_prefs() -> photocraft_engine::prefs::SavedPrefs {
photocraft_engine::prefs::read_saved(config_dir().as_deref())
}
fn gpu_memo_file() -> Option<PathBuf> {
@@ -756,7 +444,21 @@ pub fn automation(workspace: Option<photocraft_automation::AuthorizedWorkspace>)
photocraft_ui_egui::AutomationServices { read, write, open_pcraft, save, command, authorize }
}
pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) -> Services {
/// What agent requests may read, write and run with the agent settings' folders
/// (`Services::agent_automation`): the automation policy always, and without folders no file
/// access. A folder that can't be opened, or isn't an absolute path, is left out (that direction
/// fails closed) and named, as at launch.
pub fn agent_automation(settings: &craft::automation::agents::AgentSettings) -> (photocraft_ui_egui::AutomationServices, Option<String>) {
let no_flags = photocraft_automation::args::AutomationArgs { automation_read_root: Vec::new(), automation_write_root: None };
match crate::automation_workspace(&no_flags, settings) {
Ok((workspace, warning)) => (automation(Some(workspace)), warning.map(|w| format!("Agents can connect, but without file access there: {w}"))),
Err(e) => (automation(Some(photocraft_automation::AuthorizedWorkspace::default())), Some(format!("Agents can connect, but without file access: {e}"))),
}
}
/// Every native service. `wake` requests a repaint from any thread; the file panels answer through it.
pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>, wake: craft::dialogs::Wake) -> Services {
let (files, file_panels) = craft::dialogs::service::FileService::new(wake);
let clip: Rc<RefCell<Option<arboard::Clipboard>>> = Rc::default();
let clip_unreadable: Rc<Cell<bool>> = Rc::default();
let automation = self::automation(automation);
@@ -771,7 +473,9 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
crate::crash_guard::guard("Export", || photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()))
})),
save_file: Some(Arc::new(save_file)),
file_dialog: Some(Box::new(show_file_dialog)),
files: Some(Arc::new(files)),
file_panels: Some(file_panels),
settings: Some(settings_store()),
write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))),
file_stamp: Some(Box::new(|path: &str| {
// Follows a symlink, as Save writes through it to the file it points at.
@@ -785,15 +489,9 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
automation_save: automation.save,
automation_command: automation.command,
automation_authorize: automation.authorize,
encode_png: Some(Box::new(|w, h, rgba| {
let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?;
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())
})),
inbox: None,
open_url: Some(Box::new(|url: &str| open::that(url).map_err(|e| e.to_string()))),
beep: Some(platform_beep),
check_updates: Some(crate::updates::service()),
last_update: Some(crate::updates::last_update),
clipboard_set_image: Some({
let clip = clip.clone();
guarded_clipboard_set(move |w: u32, h: u32, px: &[u8]| {
@@ -854,9 +552,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
})
}),
clipboard_unreadable: Some(Box::new(move || clip_unreadable.get())),
load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())),
photoshop_shortcuts: Some(Box::new(|| crate::photoshop_settings::live_keyboard_shortcuts(&|k| std::env::var_os(k)))),
save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))),
load_gpu_memo: Some(Box::new(load_gpu_memo_text)),
save_gpu_memo: Some(Box::new(|text: &str| {
if text.len() > photocraft_ui_egui::gpu_memo::MAX_GPU_MEMO_BYTES {
@@ -865,7 +561,6 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
write_atomic(&gpu_memo_file().ok_or("no config directory")?, text.as_bytes())
})),
shader_compiler: Some(shader_compiler_identity()),
system_theme: crate::appearance::service(),
append_text: Some(Box::new(|path: &str, text: &str| {
use std::io::Write;
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).map_err(|e| e.to_string())?;
+34 -357
View File
@@ -1,8 +1,9 @@
use super::*;
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image};
use photocraft_engine::Session;
use photocraft_format::list_recovery;
use photocraft_ui_egui::{PhotocraftApp, prefs_ui};
use serde_json::{Value, json};
use serde_json::json;
/// #6607: a PSD/PSB save streams the file model into the temporary file, which then holds
/// exactly the exported bytes; a serializer error halfway leaves the old file and no
@@ -39,73 +40,13 @@ fn a_psd_save_streams_the_exported_bytes_and_keeps_the_old_file_on_error() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #6601: a chosen path whose name isn't valid Unicode is reported, never handed on lossily
/// (Open would fail with "No such file", Save would write a second, renamed file).
#[test]
fn a_chosen_path_that_is_not_valid_unicode_is_an_error_not_another_name() {
#[cfg(unix)]
let bad = {
use std::os::unix::ffi::OsStrExt;
std::env::temp_dir().join(std::ffi::OsStr::from_bytes(b"img\xFF.png"))
};
#[cfg(windows)]
let bad = {
use std::os::windows::ffi::OsStringExt;
let mut wide: Vec<u16> = "img".encode_utf16().collect();
wide.push(0xD800);
wide.extend(".png".encode_utf16());
std::env::temp_dir().join(std::ffi::OsString::from_wide(&wide))
};
let good = std::env::temp_dir().join("ok.png");
let save = |path: &Path| answer_one(path, true, FileDialogAnswer::SaveTo);
assert!(matches!(save(&bad), FileDialogAnswer::Unavailable(e) if e.contains("not valid Unicode") && e.contains("another name")));
assert!(matches!(save(&good), FileDialogAnswer::SaveTo(p) if p == good.to_str().unwrap()));
let open = answer([good.as_path(), bad.as_path()], false, FileDialogAnswer::Paths);
assert!(matches!(open, FileDialogAnswer::Unavailable(e) if e.contains("open it again")));
}
/// #6121: the file type picked in the save dialog gives the name its extension where the
/// dialog left the one it opened with, and only there.
#[test]
fn the_picked_file_type_gives_the_name_its_extension() {
let exts = |e: &[&str]| e.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let (png, psd) = (exts(&["png"]), exts(&["psd", "psb"]));
let opened = Some("Untitled-1.psd");
let cases = [
// PNG picked, the name as the dialog opened (or renamed, its extension kept).
("/pics/Untitled-1.psd", opened, &png, "/pics/Untitled-1.png"),
("/pics/art.psd", opened, &png, "/pics/art.png"),
("/pics/ART.PSD", opened, &png, "/pics/ART.png"),
// No extension: the type's. One PhotoCraft doesn't save is part of the name.
("/pics/art", opened, &png, "/pics/art.png"),
("/pics/scan.2024", opened, &png, "/pics/scan.2024.png"),
// Typed, an extension PhotoCraft saves is the user's: kept, whatever the type says
// (the PSD type untouched, or PNG picked and .jpg typed).
("/pics/art.png", opened, &psd, "/pics/art.png"),
("/pics/art.jpg", opened, &png, "/pics/art.jpg"),
("/pics/art.pcraft", opened, &png, "/pics/art.pcraft"),
// Already the type's: kept, including its other extensions.
("/pics/art.png", opened, &png, "/pics/art.png"),
("/pics/art.PNG", opened, &png, "/pics/art.PNG"),
("/pics/big.psb", opened, &psd, "/pics/big.psb"),
// The dialog opened on a .pcraft: that is the extension the type replaces.
("/pics/art.pcraft", Some("art.pcraft"), &png, "/pics/art.png"),
("/pics/art.psd", Some("art.pcraft"), &png, "/pics/art.psd"),
];
for (typed, opened, chosen, want) in cases {
assert_eq!(with_chosen_type(Path::new(typed), opened, chosen), PathBuf::from(want), "{typed} (opened {opened:?})");
}
// No type picked: the name as typed.
assert_eq!(with_chosen_type(Path::new("/pics/art.psd"), opened, &[]), PathBuf::from("/pics/art.psd"));
}
/// Regression using the real clipboard on an isolated Windows CI runner.
#[cfg(target_os = "windows")]
#[test]
#[ignore = "requires exclusive use of the Windows clipboard"]
fn busy_native_clipboard_preserves_copied_shape() {
for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] {
let mut native = native(None);
let mut native = native(None, craft::host::Wake::none());
let services =
Services { clipboard_set_image: native.clipboard_set_image.take(), clipboard_get_image: native.clipboard_get_image.take(), ..Default::default() };
let mut app = PhotocraftApp::new(Session::new(), services);
@@ -147,82 +88,6 @@ fn busy_native_clipboard_preserves_copied_shape() {
}
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn open_filters_cover_uppercase_and_mixed_case_extensions() {
// Matches `text` against a glob of literals and `[..]` classes, as the portal would after `*.`.
fn matches(glob: &str, text: &str) -> bool {
let mut text = text.chars();
let mut glob = glob.chars();
while let Some(g) = glob.next() {
let class: String = if g == '[' { glob.by_ref().take_while(|&c| c != ']').collect() } else { g.to_string() };
if !text.next().is_some_and(|t| class.contains(t)) {
return false;
}
}
text.next().is_none()
}
assert_eq!(open_filter_extensions(&["cr2", "pcraft"]), ["[cC][rR]2", "[pP][cC][rR][aA][fF][tT]"]);
let globs = open_filter_extensions(OPEN_EXTS);
assert_eq!(globs.len(), OPEN_EXTS.len());
for (ext, glob) in OPEN_EXTS.iter().zip(&globs) {
// Every casing: lower, UPPER, and alternating both ways (JpG, jPg).
let alternating = |upper_first: bool| -> String {
ext.chars().enumerate().map(|(i, c)| if (i % 2 == 0) == upper_first { c.to_ascii_uppercase() } else { c }).collect()
};
for name in [ext.to_string(), ext.to_ascii_uppercase(), alternating(true), alternating(false)] {
assert!(matches(glob, &name), "{glob} should match .{name}");
}
assert!(!matches(glob, &format!("{ext}x")) && !matches(glob, &ext[..ext.len() - 1]), "{glob} matches only .{ext}");
}
assert!(!globs.iter().any(|glob| matches(glob, "txt")));
let svg_filter = open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts).unwrap_or_default();
assert_eq!(svg_filter, open_filter_extensions(SVG_EXTS));
let psd_filter = open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts).unwrap_or_default();
assert_eq!(psd_filter, open_filter_extensions(&["psd", "psb", "psdt"]));
assert!(psd_filter.iter().any(|glob| matches(glob, "psd")) && psd_filter.iter().any(|glob| matches(glob, "PSD")));
assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz")));
}
/// #6337: after All Formats, every format File › Open reads has its own filter, and no filter
/// offers an extension All Formats doesn't.
#[test]
fn every_open_format_has_its_own_filter() {
let filters = open_filters();
assert_eq!(filters[0], ("All Formats", open_filter_extensions(OPEN_EXTS)), "All Formats comes first");
let mut named: Vec<&str> = OPEN_FILTERS.iter().flat_map(|(_, exts)| exts.iter().copied()).collect();
let total = named.len();
named.sort_unstable();
named.dedup();
assert_eq!(named.len(), total, "an extension is listed under two filters");
let mut all = OPEN_EXTS.to_vec();
all.sort_unstable();
assert_eq!(named, all, "the named filters cover All Formats exactly");
let names: Vec<&str> = filters.iter().map(|(name, _)| *name).collect();
for name in ["Photoshop", "Affinity", "HEIF", "PNG", "JPEG", "TIFF", "Portable Bitmap", "OpenEXR", "Radiance HDR", "Paint.NET"] {
assert!(names.contains(&name), "{name}");
}
}
#[cfg(not(all(unix, not(target_os = "macos"))))]
#[test]
fn open_filters_keep_literal_extensions_on_windows_and_macos() {
assert_eq!(open_filter_extensions(OPEN_EXTS), OPEN_EXTS);
assert_eq!(open_filter_extensions(&["pcraft"]), ["pcraft"]);
assert_eq!(open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts), Some(vec!["svg".to_string(), "svgz".to_string()]));
assert_eq!(
open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts),
Some(vec!["psd".to_string(), "psb".to_string(), "psdt".to_string()])
);
}
#[test]
fn native_services_provide_update_transport() {
let services = native(None);
assert!(services.check_updates.is_some());
assert!(services.last_update.is_some());
}
#[test]
fn xwayland_command_matches_how_photocraft_was_installed() {
// Flatpak: WAYLAND_DISPLAY doesn't reach the sandbox's socket choice; flatpak's flags do.
@@ -240,174 +105,6 @@ fn xwayland_command_matches_how_photocraft_was_installed() {
assert_eq!(xwayland_command(None, Some("/opt/p.AppImage"), false), None);
}
/// Tests every native save dialog and records the suggested file name. Each name's file type must come first
/// in the save panel, or the panel appends the first type's extension (`photo.webp.psd`, `photo.gif.psd`).
#[test]
fn every_save_dialog_leads_with_its_own_extension() {
let asked: Rc<RefCell<Vec<String>>> = Rc::default();
let log = asked.clone();
// Record each save dialog's suggested name and cancel it, as the user would.
let services = Services {
file_dialog: Some(Box::new(move |request, _parent, reply| {
if let FileDialogRequest::Save { suggested } = request {
log.borrow_mut().push(suggested);
}
reply.send(None);
})),
..Default::default()
};
let mut app = PhotocraftApp::new(Session::new(), services);
let ctx = egui::Context::default();
// Dialogs are shown on the next frame: poll once so each is answered before the next asks.
let invoke = |app: &mut PhotocraftApp, id: &str| {
let r = photocraft_ui_egui::menus::invoke(app, &ctx, id, json!({}));
app.poll_file_dialog(&ctx, None);
r
};
let dialog = |app: &mut PhotocraftApp, id: &str, fields: Value| {
let d = invoke(app, id).unwrap()["dialog"].as_u64().unwrap();
for (k, v) in fields.as_object().unwrap() {
app.ui.dialog_mut(d).unwrap().fields.insert(k.clone(), v.clone());
}
let _ = photocraft_ui_egui::dialogs::confirm(app, d);
app.poll_file_dialog(&ctx, None);
};
new_doc(&mut app, "#ff0000");
// Save As, Save a Copy.
// Files in a format Save As can't write, like .dng, should suggest .psd instead.
let _ = invoke(&mut app, "file.saveAs");
for name in ["cat.pcraft", "cat.jpeg", "cat.gif", "cat.bmp", "cat.dng"] {
app.session.active_mut().unwrap().path = Some(name.into());
let _ = invoke(&mut app, "file.saveAs");
}
let _ = invoke(&mut app, "file.saveACopy");
// Export As, Quick Export, Save for Web (with and without slices).
for format in ["png", "jpg", "webp", "tif", "tga"] {
dialog(&mut app, "file.export.exportAs", json!({"format": format}));
}
for format in ["png", "jpg", "gif", "webp"] {
app.run("prefs.set", json!({"path": "export.quickExportFormat", "value": format})).unwrap();
let _ = invoke(&mut app, "file.export.quickExportAsPng");
}
for format in ["gif", "png8", "png24", "jpeg", "webp", "wbmp"] {
dialog(&mut app, "file.export.saveForWebLegacy", json!({"format": format}));
}
app.run("slice.new", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap();
dialog(&mut app, "file.export.saveForWebLegacy", json!({"html": true}));
// Measurement Log, Export/Import Presets.
app.run("image.analysis.recordMeasurements", json!({})).unwrap();
let _ = invoke(&mut app, "measurementLog.export");
dialog(&mut app, "edit.presets.exportImportPresets", json!({"action": "export"}));
let asked = asked.borrow();
let exts: Vec<&str> = asked.iter().filter_map(|s| s.rsplit_once('.').map(|(_, e)| e)).collect();
// The extension each save above should suggest, in order.
let want = [
"psd", // Save As untitled
"pcraft jpeg gif bmp psd", // Save As opened .pcraft .jpeg .gif .bmp .dng
"psd", // Save a Copy
"png jpg webp tif tga", // Export As
"png jpg gif webp", // Quick Export
"gif png png jpg webp wbmp html", // Save for Web: gif png8 png24 jpeg webp wbmp, then with slices
"csv pcpresets", // Measurement Log, Export Presets
]
.join(" ");
assert_eq!(exts, want.split(' ').collect::<Vec<_>>());
for (name, ext) in asked.iter().zip(exts) {
// The first type's first extension is the one Windows adds to the bare name.
assert_eq!(save_filters(name)[0].1.first().map(String::as_str), Some(ext), "{name}: {:?}", save_filters(name)[0]);
}
assert_eq!(save_filters("Untitled")[0].0, "PSD Document", "no extension keeps the default");
}
/// Every flat format Save As offers is one PhotoCraft writes, and ICO is among them (#4357).
#[test]
fn save_as_offers_only_writable_formats_including_ico() {
// Layered formats, and PDF, are written by `photocraft-io`, not a codec.
let layered = ["psd", "psb", "pcraft", "ora", "pdf"];
for (name, exts) in SAVE_FILTERS {
for ext in exts.iter().filter(|e| !layered.contains(e)) {
let format = photocraft_codecs::from_extension(ext).unwrap_or_else(|| panic!("{name}: .{ext} is no known format"));
assert!(format.caps().write, "{name}: .{ext} can't be written");
}
}
for ext in ["ico", "gif", "bmp", "dds", "pnm", "hdr", "dib", "jpeg", "tiff"] {
assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered");
}
// The codec writes P5/P6/P7/PF from the image, never from the name, so Netpbm offers only the
// neutral .pnm (#3609; CodeRabbit on #9775): a .pbm, .pgm or .pfm name would hold other data.
let netpbm = save_filters("Untitled").into_iter().find(|(name, _)| name == "Netpbm").map(|(_, exts)| exts);
assert_eq!(netpbm, Some(vec!["pnm".to_string()]));
// The suggested name itself becomes .pnm, as macOS and rfd keep it (CodeRabbit on #9775).
assert_eq!(netpbm_as_pnm("scans/image.pgm"), Path::new("scans/image.pnm").to_string_lossy());
assert_eq!(netpbm_as_pnm("image.PFM"), "image.pnm");
assert_eq!(netpbm_as_pnm("image.png"), "image.png");
assert_eq!(netpbm_as_pnm("Untitled-1"), "Untitled-1");
// Also when Save As starts from a subtype's name: no filter offers that subtype again.
for name in ["image.pbm", "image.pgm", "image.ppm", "image.pam", "image.pfm"] {
let filters = save_filters(name);
assert_eq!(filters[0], ("Netpbm".to_string(), vec!["pnm".to_string()]), "{name}");
let subtype = name.rsplit('.').next().unwrap_or_default();
assert!(!filters.iter().any(|(_, exts)| exts.iter().any(|e| e == subtype)), "{name}: .{subtype} is offered");
}
// File Open lists readable Save As formats in their own type. Export-only formats must
// stay absent from both Open filters rather than advertising an unavailable decoder.
for (name, exts) in SAVE_FILTERS {
for ext in exts.iter().filter(|e| **e != "pdf") {
if photocraft_codecs::from_extension(ext).is_some_and(|format| !format.caps().read) {
assert!(!OPEN_EXTS.contains(ext), "{name}: export-only .{ext} must not appear in All Formats");
assert!(!OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: export-only .{ext} must not appear in an Open type");
continue;
}
assert!(OPEN_EXTS.contains(ext), "{name}: Open's All Formats lacks .{ext}");
assert!(OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: no Open type lists .{ext}");
}
}
assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type");
// What Save As writes there: an icon up to 256×256, and a clear error past that.
let doc = |side: u32| {
let mut s = Session::new();
s.execute("file.new", json!({"width": side, "height": side})).unwrap();
s.active().unwrap().doc.clone()
};
let opts = export_options(&photocraft_ui_egui::ExportSettings::default());
let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap();
assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header");
// And what the Netpbm and Radiance rows write.
let pnm = photocraft_io::export(&doc(4), "x.pnm", &opts).unwrap();
assert_eq!(pnm.bytes[..2], *b"P6", "an RGB document saves as a binary pixmap");
let hdr = photocraft_io::export(&doc(4), "x.hdr", &opts).unwrap();
assert!(hdr.bytes.starts_with(b"#?RADIANCE"), "a Radiance header");
let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string();
assert!(err.contains("256"), "{err}");
}
/// #4394: with File name extensions shown, Windows kept `image.psd` when the type was changed to
/// PhotoCraft. Given the bare `image`, it adds the extension of whichever type is picked
/// (checked by hand with rfd 0.17.2 on Windows 11), defaulting to the first type's.
#[test]
fn the_windows_save_dialog_gets_a_bare_name_so_the_type_picks_the_extension() {
for (suggested, name, first) in [
("/pics/image.psd", "image", "psd"),
("/pics/image.psb", "image", "psb"),
("/pics/image.pcraft", "image", "pcraft"),
("/pics/sky.fit", "sky", "fit"),
("cat.jpeg", "cat", "jpeg"),
("swatches.aco", "swatches", "aco"),
] {
assert_eq!(dialog_file_name(suggested, true).as_deref(), Some(name), "{suggested}");
assert_eq!(save_filters(suggested)[0].1[0], first, "{suggested}");
// Elsewhere the dialogs keep the whole name (see `dialog_file_name`).
let whole = Path::new(suggested).file_name().unwrap().to_string_lossy().into_owned();
assert_eq!(dialog_file_name(suggested, false), Some(whole), "{suggested}");
}
// Kept whole: a second dot (Windows could keep `scan.jpg`), the user's upper case, no
// extension, and a dotfile.
for name in ["scan.jpg.psd", "my.photo.psd", "transparent.PNG", "Untitled", ".psd"] {
assert_eq!(dialog_file_name(name, true).as_deref(), Some(name));
}
assert_eq!(dialog_file_name("", true), None);
}
/// A name in another letter case reaches the same file where the file system ignores case
/// (Windows, and macOS by default), and only there. Two files with the same contents are two.
#[test]
@@ -477,8 +174,8 @@ const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
/// already queued finish, nothing else runs).
fn launch(dir: &Path) -> PhotocraftApp {
let mut app = PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf())));
let ctx = egui::Context::default();
prefs_ui::tick(&mut app, &ctx);
let ctx = app.ctx().clone();
prefs_ui::tick(&mut app, &ctx, std::time::Instant::now());
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.session.has_jobs() && std::time::Instant::now() < deadline {
photocraft_ui_egui::jobs_ui::tick(&mut app, &ctx);
@@ -504,17 +201,17 @@ fn new_doc(app: &mut PhotocraftApp, color: &str) {
fn autosave(app: &mut PhotocraftApp, ctx: &egui::Context) {
prefs_ui::autosave_now(app);
prefs_ui::tick(app, ctx);
prefs_ui::tick(app, ctx, std::time::Instant::now());
}
#[test]
fn recovered_documents_survive_a_second_crash_until_saved_or_closed() {
let dir = std::env::temp_dir().join(format!("photocraft-recovery-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let ctx = egui::Context::default();
// Launch 1: two unsaved documents are autosaved, then the app crashes.
{
let mut app = launch(&dir);
let ctx = app.ctx().clone();
new_doc(&mut app, "#ff0000");
new_doc(&mut app, "#0000ff");
autosave(&mut app, &ctx);
@@ -523,16 +220,18 @@ fn recovered_documents_survive_a_second_crash_until_saved_or_closed() {
// Launch 2 recovers both and crashes again before its first autosave (#444).
{
let mut app = launch(&dir);
let ctx = app.ctx().clone();
let mut docs = open_docs(&app);
docs.sort_by(|a, b| a.0[0].total_cmp(&b.0[0]));
assert_eq!(docs, [(BLUE, true), (RED, true)], "recovered and still unsaved");
prefs_ui::tick(&mut app, &ctx);
prefs_ui::tick(&mut app, &ctx, std::time::Instant::now());
}
assert_eq!(list_recovery(&dir).len(), 2, "recovering keeps the entries on disk");
// Launch 3 has both again; autosaving unchanged documents adds nothing, a new document
// (whose id may repeat one from an earlier launch) gets an entry of its own.
{
let mut app = launch(&dir);
let ctx = app.ctx().clone();
assert_eq!(app.session.documents().len(), 2);
autosave(&mut app, &ctx);
new_doc(&mut app, "#00ff00");
@@ -541,6 +240,7 @@ fn recovered_documents_survive_a_second_crash_until_saved_or_closed() {
assert_eq!(list_recovery(&dir).len(), 3);
// Launch 4: closing and saving recovered documents removes their entries, no duplicates.
let mut app = launch(&dir);
let ctx = app.ctx().clone();
assert_eq!(app.session.documents().len(), 3);
let red = index_of(&app, RED);
app.run("file.close", json!({"document": red})).unwrap();
@@ -548,35 +248,44 @@ fn recovered_documents_survive_a_second_crash_until_saved_or_closed() {
assert!(app.session.set_active(index_of(&app, BLUE)));
let st = app.session.active_mut().unwrap();
st.saved_revision = st.revision;
prefs_ui::tick(&mut app, &ctx);
prefs_ui::tick(&mut app, &ctx, std::time::Instant::now());
let left = list_recovery(&dir);
assert_eq!(left.len(), 1);
assert_eq!(photocraft_compose::flatten(&photocraft_format::recover(&left[0]).unwrap()).px.first().copied(), Some(GREEN));
let green = index_of(&app, GREEN);
app.run("file.close", json!({"document": green})).unwrap();
prefs_ui::tick(&mut app, &ctx);
prefs_ui::tick(&mut app, &ctx, std::time::Instant::now());
assert!(list_recovery(&dir).is_empty());
drop(app);
let _ = std::fs::remove_dir_all(&dir);
}
/// A background autosave that fails reaches the status line, and the same revision is written at
/// the next interval with no edit in between (not before it). Time moves only through the `now`
/// each tick hands the autosave timer; ticks repeated at one `now` queue nothing new.
#[test]
fn failed_background_autosave_is_reported_and_retried_without_another_edit() {
let dir = temp("autosave-retry");
let recovery = dir.join("Recovery");
// A regular file prevents creation of the recovery bundle directory.
std::fs::write(&recovery, b"blocked").unwrap();
let ctx = egui::Context::default();
let mut app = launch(&recovery);
let ctx = app.ctx().clone();
app.run("prefs.set", json!({"path": "fileHandling.autosaveMinutes", "value": 5})).unwrap();
new_doc(&mut app, "#ff0000");
let revision = app.session.active().unwrap().revision;
assert_ne!(revision, 0, "a sidecar-less bundle lists as revision 0");
autosave(&mut app, &ctx);
let interval = std::time::Duration::from_secs(5 * 60);
// The changed interval restarts the clock at this tick; the next one at the interval writes.
let start = std::time::Instant::now();
prefs_ui::tick(&mut app, &ctx, start);
let first = start + interval;
prefs_ui::tick(&mut app, &ctx, first);
let mut failed = false;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while std::time::Instant::now() < deadline {
prefs_ui::tick(&mut app, &ctx);
prefs_ui::tick(&mut app, &ctx, first);
if app.ui.status.starts_with("Autosave failed:") {
failed = true;
break;
@@ -587,10 +296,15 @@ fn failed_background_autosave_is_reported_and_retried_without_another_edit() {
assert!(app.ui.status_error);
assert!(list_recovery(&recovery).is_empty());
// No edit occurs: retrying this very same revision must still work.
// No edit occurs. Before the next interval nothing is written, even with the folder back.
std::fs::remove_file(&recovery).unwrap();
std::fs::create_dir(&recovery).unwrap();
autosave(&mut app, &ctx);
prefs_ui::tick(&mut app, &ctx, first + interval / 2);
let queued = app.services.flush_autosaves.as_mut().unwrap()();
assert!(queued.is_empty() && list_recovery(&recovery).is_empty(), "retried before the interval: {queued:?}");
// At the next interval the very same revision is written.
let second = first + interval;
prefs_ui::tick(&mut app, &ctx, second);
// The worker commits the bundle's manifest before it publishes the sidecar, and
// `list_recovery` lists a committed sidecar-less bundle (revision 0) on its own, so
// the first non-empty listing can come from the middle of the write. Wait for the write
@@ -598,7 +312,7 @@ fn failed_background_autosave_is_reported_and_retried_without_another_edit() {
let mut recovered = Vec::new();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while std::time::Instant::now() < deadline {
prefs_ui::tick(&mut app, &ctx);
prefs_ui::tick(&mut app, &ctx, second);
recovered = list_recovery(&recovery);
if recovered.iter().any(|e| e.info.revision == revision) {
break;
@@ -909,7 +623,7 @@ fn paste_turns_svg_text_on_the_clipboard_into_a_layer() {
..Default::default()
};
let mut app = PhotocraftApp::new(Session::new(), services);
let ctx = egui::Context::default();
let ctx = app.ctx().clone();
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let layers = app.session.active().unwrap().doc.layers.len();
let r = photocraft_ui_egui::menus::invoke(&mut app, &ctx, "edit.paste", json!({})).unwrap();
@@ -969,40 +683,3 @@ fn tiff_options_reach_the_written_file() {
assert_eq!(info.pages.iter().map(|p| (p.width, p.compression)).collect::<Vec<_>>(), [(200, 5), (100, 5), (50, 5)]);
assert!(!photocraft_codecs::decode(&bytes).unwrap().layout().has_alpha());
}
/// PSB is a save type of its own: it shows in the list, and the type gives a typed name its
/// extension. As an extension of the PSD type it was hidden, and KDE's dialog, which adds the
/// type's first extension, turned `art.psb` into `art.psb.psd`.
#[test]
fn psb_is_its_own_save_type() {
let filters = save_filters("Untitled-1.psd");
let (psd, psb) = (&filters[0], &filters[1]);
// The PSD type takes a typed .psb too, so Windows doesn't add .psd after it.
assert_eq!(psd.1, vec!["psd".to_string(), "psb".to_string()], "{psd:?}");
assert_eq!(psb.1, vec!["psb".to_string()], "{psb:?}");
let big = save_filters("big.psb");
assert_eq!((big[0].0.as_str(), big[0].1.clone()), ("PSB Large Document", vec!["psb".to_string()]), "a .psb starts on its own type");
let chosen = |f: &(String, Vec<String>)| with_chosen_type(Path::new("/pics/art"), Some("art.psd"), &f.1);
assert_eq!(chosen(psd), PathBuf::from("/pics/art.psd"));
assert_eq!(chosen(psb), PathBuf::from("/pics/art.psb"));
let opened = Some("Untitled-1");
assert_eq!(with_chosen_type(Path::new("/pics/art.psb"), opened, &psd.1), PathBuf::from("/pics/art.psb"), "a typed .psb stays");
// KDE adds the type's first extension after a typed one of its own: that one is taken back,
// also from an `art.psb.psd` typed in full (the dialog's answer is the same string).
assert_eq!(with_chosen_type(Path::new("/pics/art.psb.psd"), opened, &psd.1), PathBuf::from("/pics/art.psb"), "KDE's art.psb.psd");
// A dot that's part of the name stays (.jpg isn't one of the PSD type's).
assert_eq!(with_chosen_type(Path::new("/pics/scan.jpg.psd"), opened, &psd.1), PathBuf::from("/pics/scan.jpg.psd"));
}
/// The document formats, then the rest by name, so a long list stays easy to search.
#[test]
fn save_types_list_the_document_formats_then_the_rest_by_name() {
let names: Vec<&str> = SAVE_FILTERS.iter().map(|(name, _)| *name).collect();
assert_eq!(names[..3], ["PSD Document", "PSB Large Document", "PhotoCraft"]);
let key = |name: &&str| name.to_ascii_lowercase();
assert!(names[3..].is_sorted_by_key(key), "{:?}", &names[3..]);
let names: Vec<&str> = OPEN_FILTERS.iter().map(|(name, _)| *name).collect();
assert_eq!(names[..2], ["Photoshop", "PhotoCraft"]);
let formats = names.iter().position(|name| *name == "Brushes").expect("the app's own resources");
assert!(names[2..formats].is_sorted_by_key(key), "{:?}", &names[2..formats]);
}
+39 -39
View File
@@ -92,17 +92,6 @@ pub fn right_button_service() -> Option<photocraft_ui_egui::RightButtonDownFn> {
None
}
/// Where the pen is on the screen (Windows), for the title bar's pen moves (#7967).
#[cfg(target_os = "windows")]
pub fn pen_screen_service() -> Option<photocraft_ui_egui::PenScreenFn> {
Some(Box::new(|| photocraft_tablet::windows::pen_screen_px().map(|(x, y)| [x, y])))
}
#[cfg(not(target_os = "windows"))]
pub fn pen_screen_service() -> Option<photocraft_ui_egui::PenScreenFn> {
None
}
/// Which end of the pen is in use (Windows): flipping the pen to its eraser end selects the
/// Eraser (#2285). Elsewhere the end arrives with the samples in the stylus feed.
#[cfg(target_os = "windows")]
@@ -219,9 +208,8 @@ impl DisplayKind {
#[cfg(test)]
mod tests {
use super::*;
use photocraft_tablet::{Update, appkit, xi};
use photocraft_tablet::{Update, appkit};
use photocraft_ui_egui::PhotocraftApp;
use photocraft_ui_egui::canvas::{ToolEvent, tool_event};
use photocraft_ui_egui::state::Tool;
use serde_json::{Value, json};
@@ -240,30 +228,54 @@ mod tests {
}
/// The platform path end to end, minus the OS: raw AppKit / XInput2 values → the crate's
/// mapping → this module's sink → the stylus feed → the canvas's tool events → `paint.stroke`.
/// mapping → this module's sink → the stylus feed → window pointer input on the whole app → `paint.stroke`.
/// A light-to-heavy pen stroke must paint thin and faint at the light end and wide and opaque
/// at the heavy end (Size and Opacity on Pen Pressure); a mouse paints full strength.
fn pressure_stroke(mut next: impl FnMut(f32) -> Option<Sample>) -> (f64, f64, f64, f64) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let feed = app.stylus.feed.clone();
let sink = sink(feed);
app.session.execute("file.new", json!({"width": 240, "height": 80, "background": "white"})).unwrap();
app.session.execute("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).unwrap();
use egui_kittest::Harness;
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width": 240, "height": 80, "background": "white"})).unwrap();
// The app shares the harness's context, which is where the window's pointer input arrives.
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_max_steps(64).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
PhotocraftApp::with_context(cc.egui_ctx.clone(), session, Default::default())
});
let sink = sink(h.state().stylus.feed.clone());
// PLAN: assumed `PhotocraftApp::sync_views`, `last_canvas_rect` and `ui.views[..]` are public, as the app's own tests read them.
h.state_mut().sync_views();
h.run_steps(4);
// The tool first: each tool keeps its own brush, so the brush below is the Brush's.
h.state_mut().ui.tool = Tool::Brush;
h.run_steps(2);
h.state_mut().session.execute("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).unwrap();
let brush = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "pressureSize": true, "pressureOpacity": true, "smoothing": {"amount": 0}});
app.session.execute("tools.setBrush", json!({ "brush": brush })).unwrap();
app.ui.tool = Tool::Brush;
let m = egui::Modifiers::NONE;
h.state_mut().session.execute("tools.setBrush", json!({ "brush": brush })).unwrap();
{
let v = &mut h.state_mut().ui.views[0];
v.zoom = 1.0;
v.center = [120.0, 40.0];
v.clear_pending();
}
h.run_steps(2);
// The document point (x, y) on screen, with the view at 100 % centred on (120, 40).
let at = |h: &Harness<'_, PhotocraftApp>, x: f64, y: f64| h.state().last_canvas_rect.center() + egui::vec2((x - 120.0) as f32, (y - 40.0) as f32);
let n = 20;
for i in 0..=n {
let t = i as f32 / n as f32;
sink(next(0.1 + 0.9 * t));
let (x, y) = (20.0 + 200.0 * f64::from(t), 40.0);
let pressure = app.stylus.pressure();
let ev = if i == 0 { ToolEvent::Down { x, y, pressure } } else { ToolEvent::Move { x, y, pressure } };
tool_event(&mut app, ev, m);
let p = at(&h, 20.0 + 200.0 * f64::from(t), 40.0);
h.event(egui::Event::PointerMoved(p));
h.run_steps(1);
if i == 0 {
h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
}
}
tool_event(&mut app, ToolEvent::Up { x: 220.0, y: 40.0 }, m);
let end = at(&h, 220.0, 40.0);
h.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(3);
sink(None);
let app = h.state_mut();
// Darkness (1 - luma) along x = 50 (light end) and x = 200 (heavy end), and the painted
// half-width there.
let mut dark = |x: i32, y: i32| -> f64 {
@@ -303,18 +315,6 @@ mod tests {
assert!(m_dark > 0.9 && m_w >= heavy_w - 1.0, "mouse = pressure 1: {m_dark}, {m_w}");
}
#[test]
fn xinput_tablet_pressure_drives_stroke_width_and_opacity() {
let mut st = xi::State::default();
st.set_devices([xi::Device::new(9, "Wacom Intuos Pen stylus", [(2, "Abs Pressure".to_string(), 0.0, 65535.0)])]);
let (light_dark, light_w, heavy_dark, heavy_w) = pressure_stroke(|p| match st.handle(9, [(2, f64::from(p) * 65535.0)]) {
Update::Set(s) => s,
Update::Keep => None,
});
assert!(heavy_w > light_w * 2.0, "width responds: {light_w} → {heavy_w}");
assert!(heavy_dark > light_dark + 0.3, "opacity responds: {light_dark} → {heavy_dark}");
}
/// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the
/// pen's `KEY=1c03 0 0 0 0 0` has bit 0x140, BTN_TOOL_PEN) and of the same laptop without it.
const WITH_PEN: &str = "I: Bus=0011 Vendor=0001 Product=0001 Version=ab83\n\
+2 -2
View File
@@ -12,8 +12,8 @@
//! scale_factor, inner_size_points }`. eframe reads the file before any application code, so an
//! old value cannot be interpreted lazily: [`sanitize`] rewrites it before eframe loads it and
//! keeps a one-time `ui.ron.pre-0.37` backup. The old panel keys in the egui memory part are
//! untouched (`panels::panel_state_id` migrates them additively), but this window rewrite is
//! one-way: after it, a 0.36 build ignores the window entry and opens at its default geometry.
//! untouched, but this window rewrite is one-way: after it, a 0.36 build ignores the window entry
//! and opens at its default geometry.
//! Restoring the backup is the documented rollback.
use std::{collections::HashMap, path::Path};
-40
View File
@@ -1,40 +0,0 @@
//! Release checks through `craft-update`, the library every Craft App shares. Only public release
//! metadata is requested.
use photocraft_engine::updates_cmds::{CheckFn, CheckResult, Release};
pub fn service() -> CheckFn {
Box::new(|| {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::Builder::new()
.name("update check".into())
.spawn(move || {
let result = check();
if let Err(e) = &result {
log::warn!("Update check: {e}");
}
let _ = tx.send(result);
})
.map_err(|e| format!("Could not start update check: {e}"))?;
Ok(rx)
})
}
/// What the last self-update came to, once: `craft-update` removes its records as it reads them.
pub fn last_update() -> Option<Result<String, String>> {
use craft_update::self_update::{Outcome, current_version, take_outcome};
let app = &photocraft_ui_egui::UPDATE_APP;
let paths = craft_update::Paths::for_app(app).ok()?;
let version = photocraft_engine::build_info::VERSION;
let running = current_version(app, version).map_or_else(|| version.to_string(), |v| v.to_string());
match take_outcome(&paths, &running)? {
Outcome::Installed(installed) => Some(Ok(installed.to_string())),
Outcome::Failed(reason) => Some(Err(reason)),
}
}
fn check() -> CheckResult {
let http = craft_update::Http::new("PhotoCraft/Update")?;
let found = craft_update::check_for_update(&photocraft_ui_egui::UPDATE_APP, &http, photocraft_engine::build_info::VERSION)?;
Ok(found.map(|release| Release { version: release.tag.trim_start_matches(['v', 'V']).to_string(), url: release.html_url }))
}
-209
View File
@@ -1,209 +0,0 @@
//! The macOS menu bar end to end, on the main thread (`harness = false`): install it through the
//! real muda backend (`src/mac_menu.rs`), read AppKit's menu bar back, open a document and see the
//! items update in place, then choose items the two ways AppKit can: a key equivalent (a real ⌘R
//! key-down through `-[NSMenu performKeyEquivalent:]`) must reach egui as the key press it was, and
//! a click (`-[NSMenu performActionForItemAtIndex:]`) must run as a click, also when the click is
//! ↩ inside the open menu.
// The app's own module, built into this test (cargo builds harness = false tests with cfg(test), so its
// unit tests compile here too without a harness to run them).
#[cfg(target_os = "macos")]
#[path = "../src/mac_menu.rs"]
#[allow(unused_imports, dead_code)]
mod mac_menu;
#[cfg(target_os = "macos")]
fn main() {
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSEvent, NSEventMask, NSEventModifierFlags, NSEventSubtype, NSEventType, NSMenu};
use objc2_foundation::{NSPoint, NSString};
use photocraft_ui_egui::PhotocraftApp;
use photocraft_ui_egui::native_menu;
use serde_json::json;
// Without a harness nothing answers cargo-nextest's `--list`, so it ran the whole test as its
// listing and failed on the output. List the one test, as libtest's terse format would, and
// nothing for `--ignored` (nextest asks twice). Running it passes `<name> --exact`, which falls
// through to the test below.
let args: Vec<String> = std::env::args().collect();
if args.iter().any(|a| a == "--list") {
if !args.iter().any(|a| a == "--ignored") {
println!("mac_menu_appkit: test");
}
return;
}
let mtm = MainThreadMarker::new().expect("harness = false runs on the main thread");
let nsapp = NSApplication::sharedApplication(mtm);
nsapp.finishLaunching();
let titles = |menu: &NSMenu| -> Vec<String> {
(0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).filter(|it| !it.isSeparatorItem()).map(|it| it.title().to_string()).collect()
};
let submenu = |menu: &NSMenu, title: &str| -> Retained<NSMenu> {
(0..menu.numberOfItems())
.filter_map(|i| menu.itemAtIndex(i))
.find(|it| it.title().to_string() == title)
.and_then(|it| it.submenu())
.unwrap_or_else(|| panic!("no {title} submenu in {:?}", titles(menu)))
};
let index = |menu: &NSMenu, title: &str| -> isize {
(0..menu.numberOfItems())
.find(|&i| menu.itemAtIndex(i).is_some_and(|it| it.title().to_string() == title))
.unwrap_or_else(|| panic!("no {title} in {:?}", titles(menu)))
};
let main_menu = || nsapp.mainMenu().expect("a main menu");
// Make `event` AppKit's current event, as the run loop does before dispatching it.
let dequeue = |event: &NSEvent| {
nsapp.postEvent_atStart(event, true);
let mode = NSString::from_str("kCFRunLoopDefaultMode");
let got = nsapp.nextEventMatchingMask_untilDate_inMode_dequeue(NSEventMask::Any, None, &mode, true).expect("the posted event");
assert_eq!(got.r#type(), event.r#type());
got
};
let key_down = |chars: &str, code: u16, flags: NSEventModifierFlags| {
let s = NSString::from_str(chars);
NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
NSEventType::KeyDown,
NSPoint::new(0.0, 0.0),
flags,
0.0,
0,
None,
&s,
&s,
false,
code,
)
.expect("a key event")
};
let other = || {
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
NSEventType::ApplicationDefined,
NSPoint::new(0.0, 0.0),
NSEventModifierFlags::empty(),
0.0,
0,
None,
NSEventSubtype::ApplicationActivated.0,
0,
0,
)
.expect("an application-defined event")
};
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default());
let ctx = egui::Context::default();
let frame = |app: &mut PhotocraftApp, raw: egui::RawInput| {
let mut out = ctx.run_ui(raw, |ui| {
native_menu::run(app, ui.ctx());
photocraft_ui_egui::shortcuts::handle(app, ui.ctx());
native_menu::sync(app, ui.ctx());
});
out.textures_delta.clear();
};
app.services.native_menu = mac_menu::install(&ctx, &app);
assert!(app.services.native_menu.is_some(), "the menu bar installed");
// The Mac layout, as AppKit has it.
let bar = main_menu();
let tops: Vec<String> = (0..bar.numberOfItems()).filter_map(|i| bar.itemAtIndex(i)?.submenu()).map(|m| m.title().to_string()).collect();
assert_eq!(tops, ["PhotoCraft", "File", "Edit", "Image", "Layer", "Type", "Select", "Filter", "View", "Window", "Help"]);
let app_menu = submenu(&bar, "PhotoCraft");
let names = titles(&app_menu);
for want in ["About PhotoCraft", "Settings", "Language", "Appearance", "Hide PhotoCraft", "Quit PhotoCraft"] {
assert!(names.iter().any(|n| n == want), "{want} missing from the app menu: {names:?}");
}
let quit = app_menu.itemAtIndex(index(&app_menu, "Quit PhotoCraft")).expect("Quit");
assert_eq!(quit.keyEquivalent().to_string(), "q");
assert_eq!(quit.keyEquivalentModifierMask(), NSEventModifierFlags::Command);
assert!(!titles(&submenu(&bar, "File")).iter().any(|n| n == "Exit"), "Exit moved to the app menu as Quit");
assert_eq!(nsapp.windowsMenu().map(|m| m.title().to_string()).as_deref(), Some("Window"), "AppKit knows the Window menu");
assert_eq!(nsapp.helpMenu().map(|m| m.title().to_string()).as_deref(), Some("Help"), "AppKit knows the Help menu");
// Opening a document enables Layer › New › Layer… in place: same NSMenu, no rebuild.
let new_layer = |bar: &NSMenu| {
let new = submenu(&submenu(bar, "Layer"), "New");
new.itemAtIndex(index(&new, "Layer…")).expect("Layer…").isEnabled()
};
assert!(!new_layer(&bar), "no document: New Layer is disabled");
app.run("file.new", json!({"width": 64, "height": 48})).expect("a document");
frame(&mut app, egui::RawInput::default());
assert!(Retained::as_ptr(&bar) == Retained::as_ptr(&main_menu()), "opening a document updated the menu, not rebuilt it");
assert!(new_layer(&main_menu()), "with a document New Layer is enabled");
// A key equivalent: ⌘R reaches egui as ⌘R and toggles View › Rulers once.
let rulers = app.ui.extras.rulers;
let press = dequeue(&key_down("r", 15, NSEventModifierFlags::Command));
assert!(main_menu().performKeyEquivalent(&press), "⌘R is View › Rulers' key equivalent");
let mut raw = egui::RawInput::default();
if let Some(m) = app.services.native_menu.as_mut() {
m.raw_input(&mut raw);
}
let keys: Vec<_> = raw
.events
.iter()
.filter_map(|e| if let egui::Event::Key { key, pressed, modifiers, .. } = e { Some((*key, *pressed, modifiers.command)) } else { None })
.collect();
// AppKit took only the key-down; winit delivers the key-up itself (#1638).
assert_eq!(keys, [(egui::Key::R, true, true)], "the key press");
frame(&mut app, raw);
let ran: Vec<String> = photocraft_ui_egui::shortcut_dispatch::take_log(&ctx).into_iter().map(|(id, _)| id).collect();
assert_eq!(ran, ["view.rulers"], "⌘R ran Rulers, whichever ⌘R item AppKit matched");
assert_eq!(app.ui.extras.rulers, !rulers, "⌘R toggled Rulers once");
// A click: View › Rulers chosen with the mouse runs the command.
let view = submenu(&main_menu(), "View");
let at = index(&view, "Rulers");
dequeue(&other());
view.performActionForItemAtIndex(at);
let mut raw = egui::RawInput::default();
if let Some(m) = app.services.native_menu.as_mut() {
m.raw_input(&mut raw);
}
assert!(raw.events.is_empty(), "a click is no key press: {:?}", raw.events);
frame(&mut app, raw);
assert_eq!(app.ui.extras.rulers, rulers, "the click toggled Rulers back");
// ↩ inside the open menu is a key-down without ⌘: still a click.
dequeue(&key_down("\r", 36, NSEventModifierFlags::empty()));
view.performActionForItemAtIndex(at);
let mut raw = egui::RawInput::default();
if let Some(m) = app.services.native_menu.as_mut() {
m.raw_input(&mut raw);
}
assert!(raw.events.is_empty(), "↩ in the menu is a click: {:?}", raw.events);
frame(&mut app, raw);
assert_eq!(app.ui.extras.rulers, !rulers, "↩ on Rulers toggled it");
// Window ends with the open documents (#2991). Opening one rebuilds only the Window menu,
// which AppKit still knows as its Window menu; choosing a row brings that document forward.
app.run("file.new", json!({"width": 32, "height": 32})).expect("a second document");
frame(&mut app, egui::RawInput::default());
assert!(Retained::as_ptr(&bar) == Retained::as_ptr(&main_menu()), "a new document rebuilt only the Window menu");
let window = submenu(&main_menu(), "Window");
assert!(nsapp.windowsMenu().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)), "AppKit knows the new Window menu");
let names: Vec<String> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
// The last rows (both documents are "Untitled").
let rows = [window.numberOfItems() - 2, window.numberOfItems() - 1];
let shown: Vec<String> = rows.iter().filter_map(|&i| window.itemAtIndex(i)).map(|it| it.title().to_string()).collect();
assert_eq!(shown, names, "in tab order, after Bring All to Front: {:?}", titles(&window));
let checked = |menu: &NSMenu, at: isize| menu.itemAtIndex(at).is_some_and(|it| it.state() == 1);
assert!(!checked(&window, rows[0]) && checked(&window, rows[1]), "the active document is checked");
dequeue(&other());
window.performActionForItemAtIndex(rows[0]);
let mut raw = egui::RawInput::default();
if let Some(m) = app.services.native_menu.as_mut() {
m.raw_input(&mut raw);
}
frame(&mut app, raw);
assert_eq!(app.session.active_index(), Some(0), "choosing the first row brought it forward");
let window = submenu(&main_menu(), "Window");
assert!(checked(&window, rows[0]) && !checked(&window, rows[1]), "the check moved in place");
println!("mac_menu_appkit: ok");
}
#[cfg(not(target_os = "macos"))]
fn main() {}
-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" />
</svg>

Before

Width:  |  Height:  |  Size: 300 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 5H3" />
<path d="M17 12H7" />
<path d="M19 19H5" />
</svg>

Before

Width:  |  Height:  |  Size: 279 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M3 20h18" />
<rect x="5" y="4" width="5" height="12" rx="1" />
<rect x="14" y="9" width="5" height="7" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 416 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M12 3v18" />
<rect x="5" y="5" width="14" height="5" rx="1" />
<rect x="8" y="14" width="8" height="5" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 416 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M4 3v18" />
<rect x="8" y="5" width="12" height="5" rx="1" />
<rect x="8" y="14" width="7" height="5" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 415 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M20 3v18" />
<rect x="4" y="5" width="12" height="5" rx="1" />
<rect x="9" y="14" width="7" height="5" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 416 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M3 4h18" />
<rect x="5" y="8" width="5" height="12" rx="1" />
<rect x="14" y="8" width="5" height="7" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 415 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M3 12h18" />
<rect x="5" y="5" width="5" height="14" rx="1" />
<rect x="14" y="8" width="5" height="8" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 416 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 5h18" />
<path d="M3 12h18" />
<path d="M3 19h18" />
</svg>

Before

Width:  |  Height:  |  Size: 279 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 5H3" />
<path d="M15 12H3" />
<path d="M17 19H3" />
</svg>

Before

Width:  |  Height:  |  Size: 279 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 5H3" />
<path d="M21 12H9" />
<path d="M21 19H7" />
</svg>

Before

Width:  |  Height:  |  Size: 279 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="2" y="4" width="20" height="16" rx="2" />
<path d="M10 4v4" />
<path d="M2 8h20" />
<path d="M6 4v4" />
</svg>

Before

Width:  |  Height:  |  Size: 329 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Artboard tool glyph (not from an icon set): a board with a tick at each end of its edges. -->
<rect x="7" y="7" width="10" height="10" rx="1" />
<path d="M7 2v2.5M17 2v2.5M7 19.5V22M17 19.5V22" />
<path d="M2 7h2.5M2 17h2.5M19.5 7H22M19.5 17H22" />
</svg>

Before

Width:  |  Height:  |  Size: 487 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="M4.929 4.929 19.07 19.071" />
</svg>

Before

Width:  |  Height:  |  Size: 285 B

-21
View File
@@ -1,21 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10 12.01h.01" />
<path d="M10 16.01h.01" />
<path d="M14 12.01h.01" />
<path d="M14 16.01h.01" />
<path d="M18 8v12" />
<path d="M6 8v12" />
<rect x="2" y="8" width="20" height="12" rx="2" />
<path d="M20 1v4" />
<path d="M22 3h-4" />
</svg>

Before

Width:  |  Height:  |  Size: 471 B

-19
View File
@@ -1,19 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10 10.01h.01" />
<path d="M10 14.01h.01" />
<path d="M14 10.01h.01" />
<path d="M14 14.01h.01" />
<path d="M18 6v12" />
<path d="M6 6v12" />
<rect x="2" y="6" width="20" height="12" rx="2" />
</svg>

Before

Width:  |  Height:  |  Size: 424 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="15" cy="9" r="7" />
<circle cx="9" cy="15" r="7" />
</svg>

Before

Width:  |  Height:  |  Size: 276 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m16 22-1-4" />
<path d="M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1" />
<path d="M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z" />
<path d="m8 22 1-4" />
</svg>

Before

Width:  |  Height:  |  Size: 470 B

-19
View File
@@ -1,19 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m11 10 3 3" />
<path d="M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z" />
<path d="M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031" />
<path d="M2.5 9A6 6 0 0 1 8 3" />
<path d="m6 1.5 2 1.5-2 1.5" />
<path d="M21.5 15a6 6 0 0 1-5.5 6" />
<path d="m18 19.5-2 1.5 2 1.5" />
</svg>

Before

Width:  |  Height:  |  Size: 544 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m11 10 3 3" />
<path d="M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z" />
<path d="M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031" />
</svg>

Before

Width:  |  Height:  |  Size: 398 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 6 9 17l-5-5" />
</svg>

Before

Width:  |  Height:  |  Size: 239 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m6 9 6 6 6-6" />
</svg>

Before

Width:  |  Height:  |  Size: 236 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m15 18-6-6 6-6" />
</svg>

Before

Width:  |  Height:  |  Size: 238 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m9 18 6-6-6-6" />
</svg>

Before

Width:  |  Height:  |  Size: 237 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m18 15-6-6-6 6" />
</svg>

Before

Width:  |  Height:  |  Size: 238 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m11 17-5-5 5-5" />
<path d="m18 17-5-5 5-5" />
</svg>

Before

Width:  |  Height:  |  Size: 268 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m6 17 5-5-5-5" />
<path d="m13 17 5-5-5-5" />
</svg>

Before

Width:  |  Height:  |  Size: 267 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="1" />
<circle cx="12" cy="12" r="10" />
</svg>

Before

Width:  |  Height:  |  Size: 279 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
</svg>

Before

Width:  |  Height:  |  Size: 244 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own clipping-mask cursor (not from an icon set): a hooked arrow down onto the layer below. -->
<path d="M5 4h4.5a5.5 5.5 0 0 1 5.5 5.5V16" />
<path d="m11.5 12.5 3.5 3.5 3.5-3.5" />
<path d="M5 20.5h14" />
</svg>

Before

Width:  |  Height:  |  Size: 440 B

-18
View File
@@ -1,18 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own release-clipping-mask cursor: clip-below.svg unchanged, plus a small "no" badge (thinner strokes keep it legible at cursor size). -->
<path d="M5 4h4.5a5.5 5.5 0 0 1 5.5 5.5V16" />
<path d="m11.5 12.5 3.5 3.5 3.5-3.5" />
<path d="M5 20.5h14" />
<circle cx="20" cy="4" r="3.25" stroke-width="1.5" />
<path d="m17.7 1.7 4.6 4.6" stroke-width="1.5" />
</svg>

Before

Width:  |  Height:  |  Size: 591 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="M12 6v6l4 2" />
</svg>

Before

Width:  |  Height:  |  Size: 271 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z" />
</svg>

Before

Width:  |  Height:  |  Size: 275 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z" />
</svg>

Before

Width:  |  Height:  |  Size: 351 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="M12 2a10 10 0 0 0 0 20z" fill="currentColor" stroke="none" />
</svg>

Before

Width:  |  Height:  |  Size: 317 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Convert Point glyph: a corner point, an angle with a square anchor on its apex. -->
<rect x="9.75" y="4.75" width="4.5" height="4.5" />
<path d="M10.5 9.25 4 19" />
<path d="M13.5 9.25 20 19" />
</svg>

Before

Width:  |  Height:  |  Size: 433 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</svg>

Before

Width:  |  Height:  |  Size: 339 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M5 5H19V19H5Z" />
<path d="M9.67 2.8V5M14.33 2.8V5M9.67 19v2.2M14.33 19v2.2M2.8 9.67H5M2.8 14.33H5M19 9.67h2.2M19 14.33h2.2" />
<path d="M5 5L19 19M19 5L5 19" />
</svg>

Before

Width:  |  Height:  |  Size: 387 B

@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M5 5H19V19H5Z" />
<path d="M9.67 2.8V5M14.33 2.8V5M9.67 19v2.2M14.33 19v2.2M2.8 9.67H5M2.8 14.33H5M19 9.67h2.2M19 14.33h2.2" />
<path d="M10.35 5V19M13.65 5V19M5 10.35H19M5 13.65H19" />
</svg>

Before

Width:  |  Height:  |  Size: 411 B

@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M5 5H19V19H5Z" />
<path d="M9.67 2.8V5M14.33 2.8V5M9.67 19v2.2M14.33 19v2.2M2.8 9.67H5M2.8 14.33H5M19 9.67h2.2M19 14.33h2.2" />
<path d="M15.31 10.14L15.33 10.26L15.33 10.38L15.30 10.52L15.23 10.65L15.14 10.77L15.01 10.87L14.85 10.96L14.67 11.00L14.46 11.01L14.25 10.98L14.04 10.89L13.83 10.75L13.65 10.56L13.51 10.32L13.41 10.04L13.37 9.72L13.40 9.38L13.52 9.03L13.71 8.70L13.99 8.39L14.35 8.13L14.79 7.94L15.29 7.85L15.83 7.86L16.39 8.00L16.95 8.27L17.46 8.68L17.91 9.22L18.25 9.89L18.46 10.67L18.50 11.52L18.35 12.42L17.98 13.33L17.40 14.19L16.59 14.96L15.57 15.58L14.37 15.99L13.03 16.15L11.58 16.01L10.11 15.54L8.68 14.71L7.38 13.52L6.29 11.99L5.50 10.14" />
</svg>

Before

Width:  |  Height:  |  Size: 889 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M5 5H19V19H5Z" />
<path d="M9.67 2.8V5M14.33 2.8V5M9.67 19v2.2M14.33 19v2.2M2.8 9.67H5M2.8 14.33H5M19 9.67h2.2M19 14.33h2.2" />
<path d="M8.5 5V19M12 5V19M15.5 5V19M5 8.5H19M5 12H19M5 15.5H19" />
</svg>

Before

Width:  |  Height:  |  Size: 421 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M5 5H19V19H5Z" />
<path d="M9.67 2.8V5M14.33 2.8V5M9.67 19v2.2M14.33 19v2.2M2.8 9.67H5M2.8 14.33H5M19 9.67h2.2M19 14.33h2.2" />
<path d="M9.67 5V19M14.33 5V19M5 9.67H19M5 14.33H19" />
</svg>

Before

Width:  |  Height:  |  Size: 409 B

-15
View File
@@ -1,15 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M5 5H19V19H5Z" />
<path d="M9.67 2.8V5M14.33 2.8V5M9.67 19v2.2M14.33 19v2.2M2.8 9.67H5M2.8 14.33H5M19 9.67h2.2M19 14.33h2.2" />
<path d="M5 5L19 19M5 19L12 12" />
</svg>

Before

Width:  |  Height:  |  Size: 388 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M6 2v14a2 2 0 0 0 2 2h14" />
<path d="M18 22V8a2 2 0 0 0-2-2H2" />
</svg>

Before

Width:  |  Height:  |  Size: 288 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z" />
</svg>

Before

Width:  |  Height:  |  Size: 357 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z" />
<rect x="16.5" y="16.5" width="4.5" height="4.5" />
</svg>

Before

Width:  |  Height:  |  Size: 410 B

-19
View File
@@ -1,19 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M4 7h16" />
<rect x="7" y="2" width="10" height="3" rx="1" />
<path d="M4 14h16" />
<rect x="7" y="9" width="10" height="3" rx="1" />
<path d="M4 21h16" />
<rect x="7" y="16" width="10" height="3" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 516 B

-22
View File
@@ -1,22 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<rect x="2" y="6" width="4" height="12" rx="1" />
<path d="M4 2v2" />
<path d="M4 20v2" />
<rect x="10" y="6" width="4" height="12" rx="1" />
<path d="M12 2v2" />
<path d="M12 20v2" />
<rect x="18" y="6" width="4" height="12" rx="1" />
<path d="M20 2v2" />
<path d="M20 20v2" />
</svg>

Before

Width:  |  Height:  |  Size: 585 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M3 4v16" />
<path d="M21 4v16" />
<rect x="9" y="7" width="6" height="10" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 387 B

-19
View File
@@ -1,19 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M3 4v16" />
<rect x="5" y="7" width="3" height="10" rx="1" />
<path d="M10 4v16" />
<rect x="12" y="7" width="3" height="10" rx="1" />
<path d="M17 4v16" />
<rect x="19" y="7" width="3" height="10" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 517 B

-19
View File
@@ -1,19 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M7 4v16" />
<rect x="2" y="7" width="3" height="10" rx="1" />
<path d="M14 4v16" />
<rect x="9" y="7" width="3" height="10" rx="1" />
<path d="M21 4v16" />
<rect x="16" y="7" width="3" height="10" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 516 B

-19
View File
@@ -1,19 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M4 3h16" />
<rect x="7" y="5" width="10" height="3" rx="1" />
<path d="M4 10h16" />
<rect x="7" y="12" width="10" height="3" rx="1" />
<path d="M4 17h16" />
<rect x="7" y="19" width="10" height="3" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 517 B

-22
View File
@@ -1,22 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<rect x="6" y="2" width="12" height="4" rx="1" />
<path d="M2 4h2" />
<path d="M20 4h2" />
<rect x="6" y="10" width="12" height="4" rx="1" />
<path d="M2 12h2" />
<path d="M20 12h2" />
<rect x="6" y="18" width="12" height="4" rx="1" />
<path d="M2 20h2" />
<path d="M20 20h2" />
</svg>

Before

Width:  |  Height:  |  Size: 585 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Move tool options-bar glyph (not from an icon set). -->
<path d="M4 3h16" />
<path d="M4 21h16" />
<rect x="7" y="9" width="10" height="6" rx="1" />
</svg>

Before

Width:  |  Height:  |  Size: 387 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z" />
</svg>

Before

Width:  |  Height:  |  Size: 325 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<ellipse cx="12" cy="12" rx="10" ry="7" stroke-dasharray="3.5 3.23" />
</svg>

Before

Width:  |  Height:  |  Size: 281 B

-18
View File
@@ -1,18 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21" />
<path d="m5.082 11.09 8.828 8.828" />
<path d="M2 2h1" />
<path d="M6 2h1" />
<path d="M2 6h1" />
<path d="M4 4h1" />
</svg>

Before

Width:  |  Height:  |  Size: 471 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21" />
<path d="m5.082 11.09 8.828 8.828" />
<path d="M5 1v5" />
<path d="M7.5 3.5h-5" />
</svg>

Before

Width:  |  Height:  |  Size: 432 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21" />
<path d="m5.082 11.09 8.828 8.828" />
</svg>

Before

Width:  |  Height:  |  Size: 383 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49" />
<path d="M14.084 14.158a3 3 0 0 1-4.242-4.242" />
<path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143" />
<path d="m2 2 20 20" />
</svg>

Before

Width:  |  Height:  |  Size: 504 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0" />
<circle cx="12" cy="12" r="3" />
</svg>

Before

Width:  |  Height:  |  Size: 360 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" />
<path d="M14 2v4a2 2 0 0 0 2 2h4" />
</svg>

Before

Width:  |  Height:  |  Size: 321 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4" />
</svg>

Before

Width:  |  Height:  |  Size: 314 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2" />
</svg>

Before

Width:  |  Height:  |  Size: 401 B

-13
View File
@@ -1,13 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" />
</svg>

Before

Width:  |  Height:  |  Size: 342 B

-14
View File
@@ -1,14 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M4 9.5c2.7-2 5.3-2 8 0s5.3 2 8 0" />
<path d="M4 15.5c2.7-2 5.3-2 8 0s5.3 2 8 0" />
</svg>

Before

Width:  |  Height:  |  Size: 305 B

-16
View File
@@ -1,16 +0,0 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 4h10M8 4v10" />
<path d="M14 8h7M17.5 8v6" />
<path d="M3 19h18" />
<circle cx="9" cy="19" r="2" fill="currentColor" />
</svg>

Before

Width:  |  Height:  |  Size: 348 B

Loaded 100 of 1529 files, more files were not shown because too many files have changed in this diff. Show more